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"
46 #include "WordLangTuple.h"
49 #include "frontends/alert.h"
51 #include "insets/InsetBibitem.h"
52 #include "insets/InsetLabel.h"
53 #include "insets/InsetSpecialChar.h"
55 #include "support/debug.h"
56 #include "support/docstring_list.h"
57 #include "support/ExceptionMessage.h"
58 #include "support/gettext.h"
59 #include "support/lassert.h"
60 #include "support/lstrings.h"
61 #include "support/textutils.h"
67 using namespace lyx::support;
73 /// Inset identifier (above 0x10ffff, for ucs-4)
74 char_type const META_INSET = 0x200001;
79 /////////////////////////////////////////////////////////////////////
83 /////////////////////////////////////////////////////////////////////
85 class SpellResultRange {
87 SpellResultRange(FontSpan range, SpellChecker::Result result)
88 : range_(range), result_(result)
91 FontSpan const & range() const { return range_; }
93 void range(FontSpan const & r) { range_ = r; }
95 SpellChecker::Result result() const { return result_; }
97 void result(SpellChecker::Result r) { result_ = r; }
99 bool inside(pos_type pos) const { return range_.inside(pos); }
101 bool covered(FontSpan const & r) const
103 // 1. first of new range inside current range or
104 // 2. last of new range inside current range or
105 // 3. first of current range inside new range or
106 // 4. last of current range inside new range
107 return range_.inside(r.first) || range_.inside(r.last) ||
108 r.inside(range_.first) || r.inside(range_.last);
111 void shift(pos_type pos, int offset)
113 if (range_.first > pos) {
114 range_.first += offset;
115 range_.last += offset;
116 } else if (range_.last >= pos) {
117 range_.last += offset;
122 SpellChecker::Result result_ ;
126 /////////////////////////////////////////////////////////////////////
130 /////////////////////////////////////////////////////////////////////
132 class SpellCheckerState {
136 needs_refresh_ = true;
137 current_change_number_ = 0;
140 void setRange(FontSpan const & fp, SpellChecker::Result state)
143 RangesIterator et = ranges_.end();
144 RangesIterator it = ranges_.begin();
145 for (; it != et; ++it) {
146 if (!it->covered(fp))
147 result.push_back(SpellResultRange(it->range(), it->result()));
148 else if (state == SpellChecker::WORD_OK) {
149 // trim or split the current misspelled range
150 // store misspelled ranges only
151 FontSpan range = it->range();
152 if (fp.first > range.first) {
153 // misspelled area in front of WORD_OK
154 range.last = fp.first - 1;
155 result.push_back(SpellResultRange(range, it->result()));
158 if (fp.last < range.last) {
159 // misspelled area after WORD_OK range
160 range.first = fp.last + 1;
161 result.push_back(SpellResultRange(range, it->result()));
166 if (state != SpellChecker::WORD_OK)
167 ranges_.push_back(SpellResultRange(fp, state));
170 void increasePosAfterPos(pos_type pos)
172 correctRangesAfterPos(pos, 1);
176 void decreasePosAfterPos(pos_type pos)
178 correctRangesAfterPos(pos, -1);
182 void refreshLast(pos_type pos)
184 if (pos < refresh_.last)
188 SpellChecker::Result getState(pos_type pos) const
190 SpellChecker::Result result = SpellChecker::WORD_OK;
191 RangesIterator et = ranges_.end();
192 RangesIterator it = ranges_.begin();
193 for (; it != et; ++it) {
194 if(it->inside(pos)) {
201 FontSpan const & getRange(pos_type pos) const
203 /// empty span to indicate mismatch
204 static FontSpan empty_;
205 RangesIterator et = ranges_.end();
206 RangesIterator it = ranges_.begin();
207 for (; it != et; ++it) {
208 if(it->inside(pos)) {
215 bool needsRefresh() const
217 return needs_refresh_;
220 SpellChecker::ChangeNumber currentChangeNumber() const
222 return current_change_number_;
225 void refreshRange(pos_type & first, pos_type & last) const
227 first = refresh_.first;
228 last = refresh_.last;
231 void needsRefresh(pos_type pos)
233 if (needs_refresh_ && pos != -1) {
234 if (pos < refresh_.first)
235 refresh_.first = pos;
236 if (pos > refresh_.last)
238 } else if (pos != -1) {
239 // init request check for neighbour positions too
240 refresh_.first = pos > 0 ? pos - 1 : 0;
241 // no need for special end of paragraph check
242 refresh_.last = pos + 1;
244 needs_refresh_ = pos != -1;
247 void needsCompleteRefresh(SpellChecker::ChangeNumber change_number)
249 needs_refresh_ = true;
252 current_change_number_ = change_number;
255 typedef vector<SpellResultRange> Ranges;
256 typedef Ranges::const_iterator RangesIterator;
258 /// the area of the paragraph with pending spell check
261 /// spell state cache version number
262 SpellChecker::ChangeNumber current_change_number_;
265 void correctRangesAfterPos(pos_type pos, int offset)
267 RangesIterator et = ranges_.end();
268 Ranges::iterator it = ranges_.begin();
269 for (; it != et; ++it) {
270 it->shift(pos, offset);
276 /////////////////////////////////////////////////////////////////////
278 // Paragraph::Private
280 /////////////////////////////////////////////////////////////////////
282 class Paragraph::Private
286 Private(Paragraph * owner, Layout const & layout);
287 /// "Copy constructor"
288 Private(Private const &, Paragraph * owner);
289 /// Copy constructor from \p beg to \p end
290 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
293 void insertChar(pos_type pos, char_type c, Change const & change);
295 /// Output the surrogate pair formed by \p c and \p next to \p os.
296 /// \return the number of characters written.
297 int latexSurrogatePair(otexstream & os, char_type c, char_type next,
298 OutputParams const &);
300 /// Output a space in appropriate formatting (or a surrogate pair
301 /// if the next character is a combining character).
302 /// \return whether a surrogate pair was output.
303 bool simpleTeXBlanks(OutputParams const &,
306 unsigned int & column,
308 Layout const & style);
310 /// Output consecutive unicode chars, belonging to the same script as
311 /// specified by the latex macro \p ltx, to \p os starting from \p i.
312 /// \return the number of characters written.
313 int writeScriptChars(otexstream & os, docstring const & ltx,
314 Change const &, Encoding const &, pos_type & i);
316 /// This could go to ParagraphParameters if we want to.
317 int startTeXParParams(BufferParams const &, otexstream &,
318 OutputParams const &) const;
320 /// This could go to ParagraphParameters if we want to.
321 bool endTeXParParams(BufferParams const &, otexstream &,
322 OutputParams const &) const;
325 void latexInset(BufferParams const &,
330 Font const & outerfont,
332 Change & running_change,
333 Layout const & style,
335 unsigned int & column);
338 void latexSpecialChar(
340 BufferParams const & bparams,
341 OutputParams const & runparams,
342 Font const & running_font,
343 Change const & running_change,
344 Layout const & style,
347 unsigned int & column);
354 unsigned int & column);
360 unsigned int & column);
362 bool latexSpecialTypewriter(
366 unsigned int & column);
368 bool latexSpecialPhrase(
372 unsigned int & column,
373 OutputParams const & runparams);
376 void validate(LaTeXFeatures & features) const;
378 /// Checks if the paragraph contains only text and no inset or font change.
379 bool onlyText(Buffer const & buf, Font const & outerfont,
380 pos_type initial) const;
382 /// match a string against a particular point in the paragraph
383 bool isTextAt(string const & str, pos_type pos) const;
385 /// a vector of speller skip positions
386 typedef vector<FontSpan> SkipPositions;
387 typedef SkipPositions::const_iterator SkipPositionsIterator;
389 void appendSkipPosition(SkipPositions & skips, pos_type const pos) const;
391 Language * getSpellLanguage(pos_type const from) const;
393 Language * locateSpellRange(pos_type & from, pos_type & to,
394 SkipPositions & skips) const;
396 bool hasSpellerChange() const
398 SpellChecker::ChangeNumber speller_change_number = 0;
399 if (theSpellChecker())
400 speller_change_number = theSpellChecker()->changeNumber();
401 return speller_change_number > speller_state_.currentChangeNumber();
404 bool ignoreWord(docstring const & word) const ;
406 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
408 pos_type textsize = owner_->size();
409 // check for sane arguments
410 if (to <= from || from >= textsize)
412 FontSpan fp = FontSpan(from, to - 1);
413 speller_state_.setRange(fp, state);
416 void requestSpellCheck(pos_type pos)
419 speller_state_.needsCompleteRefresh(speller_state_.currentChangeNumber());
421 speller_state_.needsRefresh(pos);
424 void readySpellCheck()
426 speller_state_.needsRefresh(-1);
429 bool needsSpellCheck() const
431 return speller_state_.needsRefresh();
434 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
436 speller_state_.refreshRange(first, last);
438 last = owner_->size();
441 pos_type endpos = last;
442 owner_->locateWord(first, endpos, WHOLE_WORD);
445 owner_->locateWord(last, endpos, WHOLE_WORD);
450 int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
454 while (it != et && it->first < start) {
455 int skip = it->last - it->first + 1;
463 void markMisspelledWords(pos_type const & first, pos_type const & last,
464 SpellChecker::Result result,
465 docstring const & word,
466 SkipPositions const & skips);
468 InsetCode ownerCode() const
470 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
473 /// Which Paragraph owns us?
477 Inset const * inset_owner_;
486 ParagraphParameters params_;
488 /// for recording and looking up changes
492 InsetList insetlist_;
495 pos_type begin_of_body_;
497 typedef docstring TextContainer;
501 typedef set<docstring> Words;
502 typedef map<Language, Words> LangWordsMap;
506 Layout const * layout_;
508 SpellCheckerState speller_state_;
514 struct special_phrase {
520 special_phrase const special_phrases[] = {
521 { "LyX", from_ascii("\\LyX{}"), false },
522 { "TeX", from_ascii("\\TeX{}"), true },
523 { "LaTeX2e", from_ascii("\\LaTeXe{}"), true },
524 { "LaTeX", from_ascii("\\LaTeX{}"), true },
527 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
532 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
533 : owner_(owner), inset_owner_(0), id_(-1), begin_of_body_(0), layout_(&layout)
539 // Initialization of the counter for the paragraph id's,
541 // FIXME: There should be a more intelligent way to generate and use the
542 // paragraph ids per buffer instead a global static counter for all InsetText
543 // in the running program.
544 static int paragraph_id = -1;
546 Paragraph::Private::Private(Private const & p, Paragraph * owner)
547 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
548 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
549 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
552 id_ = ++paragraph_id;
553 requestSpellCheck(p.text_.size());
557 Paragraph::Private::Private(Private const & p, Paragraph * owner,
558 pos_type beg, pos_type end)
559 : owner_(owner), inset_owner_(p.inset_owner_),
560 params_(p.params_), changes_(p.changes_),
561 insetlist_(p.insetlist_, beg, end),
562 begin_of_body_(p.begin_of_body_), words_(p.words_),
565 id_ = ++paragraph_id;
566 if (beg >= pos_type(p.text_.size()))
568 text_ = p.text_.substr(beg, end - beg);
570 FontList::const_iterator fcit = fontlist_.begin();
571 FontList::const_iterator fend = fontlist_.end();
572 for (; fcit != fend; ++fcit) {
573 if (fcit->pos() < beg)
575 if (fcit->pos() >= end) {
576 // Add last entry in the fontlist_.
577 fontlist_.set(text_.size() - 1, fcit->font());
580 // Add a new entry in the fontlist_.
581 fontlist_.set(fcit->pos() - beg, fcit->font());
583 requestSpellCheck(p.text_.size());
587 void Paragraph::addChangesToToc(DocIterator const & cdit,
588 Buffer const & buf) const
590 d->changes_.addToToc(cdit, buf);
594 bool Paragraph::isDeleted(pos_type start, pos_type end) const
596 LASSERT(start >= 0 && start <= size(), /**/);
597 LASSERT(end > start && end <= size() + 1, /**/);
599 return d->changes_.isDeleted(start, end);
603 bool Paragraph::isChanged(pos_type start, pos_type end) const
605 LASSERT(start >= 0 && start <= size(), /**/);
606 LASSERT(end > start && end <= size() + 1, /**/);
608 return d->changes_.isChanged(start, end);
612 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
614 // keep the logic here in sync with the logic of eraseChars()
618 Change const change = d->changes_.lookup(size());
619 return change.inserted() && change.currentAuthor();
623 void Paragraph::setChange(Change const & change)
625 // beware of the imaginary end-of-par character!
626 d->changes_.set(change, 0, size() + 1);
629 * Propagate the change recursively - but not in case of DELETED!
631 * Imagine that your co-author makes changes in an existing inset. He
632 * sends your document to you and you come to the conclusion that the
633 * inset should go completely. If you erase it, LyX must not delete all
634 * text within the inset. Otherwise, the change tracked insertions of
635 * your co-author get lost and there is no way to restore them later.
637 * Conclusion: An inset's content should remain untouched if you delete it
640 if (!change.deleted()) {
641 for (pos_type pos = 0; pos < size(); ++pos) {
642 if (Inset * inset = getInset(pos))
643 inset->setChange(change);
649 void Paragraph::setChange(pos_type pos, Change const & change)
651 LASSERT(pos >= 0 && pos <= size(), /**/);
652 d->changes_.set(change, pos);
654 // see comment in setChange(Change const &) above
655 if (!change.deleted() && pos < size())
656 if (Inset * inset = getInset(pos))
657 inset->setChange(change);
661 Change const & Paragraph::lookupChange(pos_type pos) const
663 LASSERT(pos >= 0 && pos <= size(), /**/);
664 return d->changes_.lookup(pos);
668 void Paragraph::acceptChanges(pos_type start, pos_type end)
670 LASSERT(start >= 0 && start <= size(), /**/);
671 LASSERT(end > start && end <= size() + 1, /**/);
673 for (pos_type pos = start; pos < end; ++pos) {
674 switch (lookupChange(pos).type) {
675 case Change::UNCHANGED:
676 // accept changes in nested inset
677 if (Inset * inset = getInset(pos))
678 inset->acceptChanges();
681 case Change::INSERTED:
682 d->changes_.set(Change(Change::UNCHANGED), pos);
683 // also accept changes in nested inset
684 if (Inset * inset = getInset(pos))
685 inset->acceptChanges();
688 case Change::DELETED:
689 // Suppress access to non-existent
690 // "end-of-paragraph char"
692 eraseChar(pos, false);
703 void Paragraph::rejectChanges(pos_type start, pos_type end)
705 LASSERT(start >= 0 && start <= size(), /**/);
706 LASSERT(end > start && end <= size() + 1, /**/);
708 for (pos_type pos = start; pos < end; ++pos) {
709 switch (lookupChange(pos).type) {
710 case Change::UNCHANGED:
711 // reject changes in nested inset
712 if (Inset * inset = getInset(pos))
713 inset->rejectChanges();
716 case Change::INSERTED:
717 // Suppress access to non-existent
718 // "end-of-paragraph char"
720 eraseChar(pos, false);
726 case Change::DELETED:
727 d->changes_.set(Change(Change::UNCHANGED), pos);
729 // Do NOT reject changes within a deleted inset!
730 // There may be insertions of a co-author inside of it!
738 void Paragraph::Private::insertChar(pos_type pos, char_type c,
739 Change const & change)
741 LASSERT(pos >= 0 && pos <= int(text_.size()), /**/);
744 changes_.insert(change, pos);
746 // This is actually very common when parsing buffers (and
747 // maybe inserting ascii text)
748 if (pos == pos_type(text_.size())) {
749 // when appending characters, no need to update tables
751 // but we want spell checking
752 requestSpellCheck(pos);
756 text_.insert(text_.begin() + pos, c);
758 // Update the font table.
759 fontlist_.increasePosAfterPos(pos);
762 insetlist_.increasePosAfterPos(pos);
764 // Update list of misspelled positions
765 speller_state_.increasePosAfterPos(pos);
769 bool Paragraph::insertInset(pos_type pos, Inset * inset,
770 Change const & change)
772 LASSERT(inset, /**/);
773 LASSERT(pos >= 0 && pos <= size(), /**/);
775 // Paragraph::insertInset() can be used in cut/copy/paste operation where
776 // d->inset_owner_ is not set yet.
777 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
780 d->insertChar(pos, META_INSET, change);
781 LASSERT(d->text_[pos] == META_INSET, /**/);
783 // Add a new entry in the insetlist_.
784 d->insetlist_.insert(inset, pos);
786 // Some insets require run of spell checker
787 requestSpellCheck(pos);
792 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
794 LASSERT(pos >= 0 && pos <= size(), return false);
796 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
799 Change change = d->changes_.lookup(pos);
801 // set the character to DELETED if
802 // a) it was previously unchanged or
803 // b) it was inserted by a co-author
805 if (!change.changed() ||
806 (change.inserted() && !change.currentAuthor())) {
807 setChange(pos, Change(Change::DELETED));
808 // request run of spell checker
809 requestSpellCheck(pos);
813 if (change.deleted())
817 // Don't physically access the imaginary end-of-paragraph character.
818 // eraseChar() can only mark it as DELETED. A physical deletion of
819 // end-of-par must be handled externally.
825 d->changes_.erase(pos);
827 // if it is an inset, delete the inset entry
828 if (d->text_[pos] == META_INSET)
829 d->insetlist_.erase(pos);
831 d->text_.erase(d->text_.begin() + pos);
833 // Update the fontlist_
834 d->fontlist_.erase(pos);
836 // Update the insetlist_
837 d->insetlist_.decreasePosAfterPos(pos);
839 // Update list of misspelled positions
840 d->speller_state_.decreasePosAfterPos(pos);
841 d->speller_state_.refreshLast(size());
847 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
849 LASSERT(start >= 0 && start <= size(), /**/);
850 LASSERT(end >= start && end <= size() + 1, /**/);
853 for (pos_type count = end - start; count; --count) {
854 if (!eraseChar(i, trackChanges))
861 int Paragraph::Private::latexSurrogatePair(otexstream & os, char_type c,
862 char_type next, OutputParams const & runparams)
864 // Writing next here may circumvent a possible font change between
865 // c and next. Since next is only output if it forms a surrogate pair
866 // with c we can ignore this:
867 // A font change inside a surrogate pair does not make sense and is
868 // hopefully impossible to input.
869 // FIXME: change tracking
870 // Is this correct WRT change tracking?
871 Encoding const & encoding = *(runparams.encoding);
872 docstring latex1 = encoding.latexChar(next).first;
873 if (runparams.inIPA) {
874 string const tipashortcut = Encodings::TIPAShortcut(next);
875 if (!tipashortcut.empty()) {
876 latex1 = from_ascii(tipashortcut);
879 docstring const latex2 = encoding.latexChar(c).first;
880 if (docstring(1, next) == latex1) {
881 // the encoding supports the combination
882 os << latex2 << latex1;
883 return latex1.length() + latex2.length();
884 } else if (runparams.local_font &&
885 runparams.local_font->language()->lang() == "polutonikogreek") {
886 // polutonikogreek only works without the brackets
887 os << latex1 << latex2;
888 return latex1.length() + latex2.length();
890 os << latex1 << '{' << latex2 << '}';
891 return latex1.length() + latex2.length() + 2;
895 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
898 unsigned int & column,
900 Layout const & style)
902 if (style.pass_thru || runparams.pass_thru)
905 if (i + 1 < int(text_.size())) {
906 char_type next = text_[i + 1];
907 if (Encodings::isCombiningChar(next)) {
908 // This space has an accent, so we must always output it.
909 column += latexSurrogatePair(os, ' ', next, runparams) - 1;
914 if (runparams.linelen > 0
915 && column > runparams.linelen
917 && text_[i - 1] != ' '
918 && (i + 1 < int(text_.size()))
919 // same in FreeSpacing mode
920 && !owner_->isFreeSpacing()
921 // In typewriter mode, we want to avoid
922 // ! . ? : at the end of a line
923 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
924 && (text_[i - 1] == '.'
925 || text_[i - 1] == '?'
926 || text_[i - 1] == ':'
927 || text_[i - 1] == '!'))) {
929 os.texrow().start(owner_->id(), i + 1);
931 } else if (style.free_spacing) {
940 int Paragraph::Private::writeScriptChars(otexstream & os,
941 docstring const & ltx,
942 Change const & runningChange,
943 Encoding const & encoding,
946 // FIXME: modifying i here is not very nice...
948 // We only arrive here when a proper language for character text_[i] has
949 // not been specified (i.e., it could not be translated in the current
950 // latex encoding) or its latex translation has been forced, and it
951 // belongs to a known script.
952 // Parameter ltx contains the latex translation of text_[i] as specified
953 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
954 // The latex macro name "textXXX" specifies the script to which text_[i]
955 // belongs and we use it in order to check whether characters from the
956 // same script immediately follow, such that we can collect them in a
957 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
958 // for the first char but only "<spec>" for all subsequent chars.
959 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
960 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
961 string script = to_ascii(ltx.substr(1, brace1 - 1));
964 bool closing_brace = true;
965 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
966 // Correct encoding is being used, so we can avoid \textgreek.
969 closing_brace = false;
971 os << ltx.substr(pos, length);
972 int size = text_.size();
973 while (i + 1 < size) {
974 char_type const next = text_[i + 1];
975 // Stop here if next character belongs to another script
976 // or there is a change in change tracking status.
977 if (!Encodings::isKnownScriptChar(next, script) ||
978 runningChange != owner_->lookupChange(i + 1))
982 FontList::const_iterator cit = fontlist_.begin();
983 FontList::const_iterator end = fontlist_.end();
984 for (; cit != end; ++cit) {
985 if (cit->pos() >= i && !found) {
986 prev_font = cit->font();
989 if (cit->pos() >= i + 1)
992 // Stop here if there is a font attribute or encoding change.
993 if (found && cit != end && prev_font != cit->font())
995 docstring const latex = encoding.latexChar(next).first;
996 docstring::size_type const b1 =
997 latex.find_first_of(from_ascii("{"));
998 docstring::size_type const b2 =
999 latex.find_last_of(from_ascii("}"));
1000 int const len = b2 - b1 - 1;
1001 os << latex.substr(b1 + 1, len);
1005 if (closing_brace) {
1013 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
1015 pos_type const len = str.length();
1017 // is the paragraph large enough?
1018 if (pos + len > int(text_.size()))
1021 // does the wanted text start at point?
1022 for (string::size_type i = 0; i < str.length(); ++i) {
1023 // Caution: direct comparison of characters works only
1024 // because str is pure ASCII.
1025 if (str[i] != text_[pos + i])
1029 return fontlist_.hasChangeInRange(pos, len);
1033 void Paragraph::Private::latexInset(BufferParams const & bparams,
1035 OutputParams & runparams,
1036 Font & running_font,
1038 Font const & outerfont,
1040 Change & running_change,
1041 Layout const & style,
1043 unsigned int & column)
1045 Inset * inset = owner_->getInset(i);
1046 LASSERT(inset, /**/);
1048 if (style.pass_thru) {
1049 inset->plaintext(os.os(), runparams);
1053 // FIXME: move this to InsetNewline::latex
1054 if (inset->lyxCode() == NEWLINE_CODE) {
1055 // newlines are handled differently here than
1056 // the default in simpleTeXSpecialChars().
1057 if (!style.newline_allowed) {
1061 column += running_font.latexWriteEndChanges(
1062 os, bparams, runparams,
1063 basefont, basefont);
1067 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
1070 basefont = owner_->getLayoutFont(bparams, outerfont);
1071 running_font = basefont;
1073 if (runparams.moving_arg)
1077 os.texrow().start(owner_->id(), i + 1);
1081 if (owner_->isDeleted(i)) {
1082 if( ++runparams.inDeletedInset == 1)
1083 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1086 if (inset->canTrackChanges()) {
1087 column += Changes::latexMarkChange(os, bparams, running_change,
1088 Change(Change::UNCHANGED), runparams);
1089 running_change = Change(Change::UNCHANGED);
1093 odocstream::pos_type const len = os.os().tellp();
1095 if (inset->forceLTR()
1096 && !runparams.use_polyglossia
1097 && running_font.isRightToLeft()
1098 // ERT is an exception, it should be output with no
1099 // decorations at all
1100 && inset->lyxCode() != ERT_CODE) {
1101 if (running_font.language()->lang() == "farsi")
1108 // FIXME: Bug: we can have an empty font change here!
1109 // if there has just been a font change, we are going to close it
1110 // right now, which means stupid latex code like \textsf{}. AFAIK,
1111 // this does not harm dvi output. A minor bug, thus (JMarc)
1113 // Some insets cannot be inside a font change command.
1114 // However, even such insets *can* be placed in \L or \R
1115 // or their equivalents (for RTL language switches), so we don't
1116 // close the language in those cases.
1117 // ArabTeX, though, cannot handle this special behavior, it seems.
1118 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
1119 || running_font.language()->lang() == "arabic_arabtex";
1120 if (open_font && !inset->inheritFont()) {
1121 bool closeLanguage = arabtex
1122 || basefont.isRightToLeft() == running_font.isRightToLeft();
1123 unsigned int count = running_font.latexWriteEndChanges(os,
1124 bparams, runparams, basefont, basefont, closeLanguage);
1126 // if any font properties were closed, update the running_font,
1127 // making sure, however, to leave the language as it was
1129 // FIXME: probably a better way to keep track of the old
1130 // language, than copying the entire font?
1131 Font const copy_font(running_font);
1132 basefont = owner_->getLayoutFont(bparams, outerfont);
1133 running_font = basefont;
1135 running_font.setLanguage(copy_font.language());
1136 // leave font open if language is still open
1137 open_font = (running_font.language() == basefont.language());
1139 runparams.local_font = &basefont;
1143 int prev_rows = os.texrow().rows();
1146 runparams.lastid = id_;
1147 runparams.lastpos = i;
1148 inset->latex(os, runparams);
1149 } catch (EncodingException & e) {
1150 // add location information and throw again.
1157 if (running_font.language()->lang() == "farsi")
1163 if (os.texrow().rows() > prev_rows) {
1164 os.texrow().start(owner_->id(), i + 1);
1167 column += (unsigned int)(os.os().tellp() - len);
1170 if (owner_->isDeleted(i))
1171 --runparams.inDeletedInset;
1175 void Paragraph::Private::latexSpecialChar(otexstream & os,
1176 BufferParams const & bparams,
1177 OutputParams const & runparams,
1178 Font const & running_font,
1179 Change const & running_change,
1180 Layout const & style,
1183 unsigned int & column)
1185 // With polyglossia, brackets and stuff need not be reversed
1186 // in RTL scripts (see bug #8251)
1187 char_type const c = (runparams.use_polyglossia) ?
1188 owner_->getUChar(bparams, i) : text_[i];
1190 if (style.pass_thru || runparams.pass_thru) {
1192 Encoding const * const enc = runparams.encoding;
1193 if (enc && !enc->encodable(c))
1194 throw EncodingException(c);
1200 // TIPA uses its own T3 encoding
1201 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1203 // If T1 font encoding is used, use the special
1204 // characters it provides.
1205 // NOTE: some languages reset the font encoding
1207 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1208 && lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
1211 // \tt font needs special treatment
1212 if (!runparams.inIPA
1213 && running_font.fontInfo().family() == TYPEWRITER_FAMILY
1214 && latexSpecialTypewriter(c, os, i, column))
1217 // Otherwise, we use what LaTeX provides us.
1220 os << "\\textbackslash{}";
1224 os << "\\textless{}";
1228 os << "\\textgreater{}";
1232 os << "\\textbar{}";
1239 os << "\\char`\\\"{}";
1244 case '%': case '#': case '{':
1252 os << "\\textasciitilde{}";
1257 os << "\\textasciicircum{}";
1264 // avoid being mistaken for optional arguments
1272 // Blanks are printed before font switching.
1273 // Sure? I am not! (try nice-latex)
1274 // I am sure it's correct. LyX might be smarter
1275 // in the future, but for now, nothing wrong is
1281 if (latexSpecialPhrase(os, i, end_pos, column, runparams))
1287 Encoding const & encoding = *(runparams.encoding);
1288 char_type next = '\0';
1289 if (i + 1 < int(text_.size())) {
1290 next = text_[i + 1];
1291 if (Encodings::isCombiningChar(next)) {
1292 column += latexSurrogatePair(os, c, next, runparams) - 1;
1298 pair<docstring, bool> latex = encoding.latexChar(c);
1299 docstring nextlatex;
1300 bool nexttipas = false;
1301 string nexttipashortcut;
1302 if (next != '\0' && next != META_INSET) {
1303 nextlatex = encoding.latexChar(next).first;
1304 if (runparams.inIPA) {
1305 nexttipashortcut = Encodings::TIPAShortcut(next);
1306 nexttipas = !nexttipashortcut.empty();
1310 if (runparams.inIPA) {
1311 string const tipashortcut = Encodings::TIPAShortcut(c);
1312 if (!tipashortcut.empty()) {
1313 latex.first = from_ascii(tipashortcut);
1314 latex.second = false;
1318 if (Encodings::isKnownScriptChar(c, script)
1319 && prefixIs(latex.first, from_ascii("\\" + script)))
1320 column += writeScriptChars(os, latex.first,
1321 running_change, encoding, i) - 1;
1322 else if (latex.second
1323 && ((!prefixIs(nextlatex, '\\')
1324 && !prefixIs(nextlatex, '{')
1325 && !prefixIs(nextlatex, '}'))
1327 && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1329 // Prevent eating of a following
1330 // space or command corruption by
1331 // following characters
1332 if (next == ' ' || next == '\0') {
1333 column += latex.first.length() + 1;
1334 os << latex.first << "{}";
1336 column += latex.first.length();
1337 os << latex.first << " ";
1340 column += latex.first.length() - 1;
1348 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1349 pos_type i, unsigned int & column)
1355 // In T1 encoding, these characters exist
1356 // but we should avoid ligatures
1357 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1359 os << "\\textcompwordmark{}";
1366 // soul.sty breaks with \char`\"
1367 os << "\\textquotedbl{}";
1376 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1377 pos_type /*i*/, unsigned int & column)
1387 os << "\\textvertline{}";
1396 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, otexstream & os,
1397 pos_type i, unsigned int & column)
1401 // within \ttfamily, "--" is merged to "-" (no endash)
1402 // so we avoid this rather irritating ligature
1403 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
1410 // everything else has to be checked separately
1411 // (depending on the encoding)
1419 /// If [start_pos, end_pos) does not include entirely the special phrase, then
1420 /// do not apply the macro transformation.
1421 bool Paragraph::Private::latexSpecialPhrase(otexstream & os, pos_type & i, pos_type end_pos,
1422 unsigned int & column, OutputParams const & runparams)
1424 // FIXME: if we have "LaTeX" with a font
1425 // change in the middle (before the 'T', then
1426 // the "TeX" part is still special cased.
1427 // Really we should only operate this on
1428 // "words" for some definition of word
1430 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1431 if (!isTextAt(special_phrases[pnr].phrase, i)
1432 || (end_pos != -1 && i + int(special_phrases[pnr].phrase.size()) > end_pos))
1434 if (runparams.moving_arg)
1436 os << special_phrases[pnr].macro;
1437 i += special_phrases[pnr].phrase.length() - 1;
1438 column += special_phrases[pnr].macro.length() - 1;
1445 void Paragraph::Private::validate(LaTeXFeatures & features) const
1447 if (layout_->inpreamble && inset_owner_) {
1448 bool const is_command = layout_->latextype == LATEX_COMMAND;
1449 Buffer const & buf = inset_owner_->buffer();
1450 BufferParams const & bp = buf.params();
1453 // Using a string stream here circumvents the encoding
1454 // switching machinery of odocstream. Therefore the
1455 // output is wrong if this paragraph contains content
1456 // that needs to switch encoding.
1457 odocstringstream ods;
1458 otexstream os(ods, texrow);
1460 os << '\\' << from_ascii(layout_->latexname());
1461 // we have to provide all the optional arguments here, even though
1462 // the last one is the only one we care about.
1463 // Separate handling of optional argument inset.
1464 if (layout_->optargs != 0 || layout_->reqargs != 0)
1465 latexArgInsets(*owner_, os, features.runparams(),
1466 layout_->reqargs, layout_->optargs);
1468 os << from_ascii(layout_->latexparam());
1470 docstring::size_type const length = ods.str().length();
1471 // this will output "{" at the beginning, but not at the end
1472 owner_->latex(bp, f, os, features.runparams(), 0, -1, true);
1473 if (ods.str().length() > length) {
1476 string const snippet = to_utf8(ods.str());
1477 features.addPreambleSnippet(snippet);
1481 if (features.runparams().flavor == OutputParams::HTML
1482 && layout_->htmltitle()) {
1483 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1486 // check the params.
1487 if (!params_.spacing().isDefault())
1488 features.require("setspace");
1491 features.useLayout(layout_->name());
1494 fontlist_.validate(features);
1496 // then the indentation
1497 if (!params_.leftIndent().zero())
1498 features.require("ParagraphLeftIndent");
1501 InsetList::const_iterator icit = insetlist_.begin();
1502 InsetList::const_iterator iend = insetlist_.end();
1503 for (; icit != iend; ++icit) {
1505 icit->inset->validate(features);
1506 if (layout_->needprotect &&
1507 icit->inset->lyxCode() == FOOT_CODE)
1508 features.require("NeedLyXFootnoteCode");
1512 // then the contents
1513 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1514 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1515 if (!special_phrases[pnr].builtin
1516 && isTextAt(special_phrases[pnr].phrase, i)) {
1517 features.require(special_phrases[pnr].phrase);
1521 Encodings::validate(text_[i], features);
1525 /////////////////////////////////////////////////////////////////////
1529 /////////////////////////////////////////////////////////////////////
1532 Layout const emptyParagraphLayout;
1535 Paragraph::Paragraph()
1536 : d(new Paragraph::Private(this, emptyParagraphLayout))
1543 Paragraph::Paragraph(Paragraph const & par)
1544 : itemdepth(par.itemdepth),
1545 d(new Paragraph::Private(*par.d, this))
1551 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1552 : itemdepth(par.itemdepth),
1553 d(new Paragraph::Private(*par.d, this, beg, end))
1559 Paragraph & Paragraph::operator=(Paragraph const & par)
1561 // needed as we will destroy the private part before copying it
1563 itemdepth = par.itemdepth;
1567 d = new Private(*par.d, this);
1574 Paragraph::~Paragraph()
1583 // this shall be called just before every "os << ..." action.
1584 void flushString(ostream & os, docstring & s)
1593 void Paragraph::write(ostream & os, BufferParams const & bparams,
1594 depth_type & dth) const
1596 // The beginning or end of a deeper (i.e. nested) area?
1597 if (dth != d->params_.depth()) {
1598 if (d->params_.depth() > dth) {
1599 while (d->params_.depth() > dth) {
1600 os << "\n\\begin_deeper";
1604 while (d->params_.depth() < dth) {
1605 os << "\n\\end_deeper";
1611 // First write the layout
1612 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1614 d->params_.write(os);
1616 Font font1(inherit_font, bparams.language);
1618 Change running_change = Change(Change::UNCHANGED);
1620 // this string is used as a buffer to avoid repetitive calls
1621 // to to_utf8(), which turn out to be expensive (JMarc)
1622 docstring write_buffer;
1625 for (pos_type i = 0; i <= size(); ++i) {
1627 Change const change = lookupChange(i);
1628 if (change != running_change)
1629 flushString(os, write_buffer);
1630 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1631 running_change = change;
1636 // Write font changes
1637 Font font2 = getFontSettings(bparams, i);
1638 if (font2 != font1) {
1639 flushString(os, write_buffer);
1640 font2.lyxWriteChanges(font1, os);
1645 char_type const c = d->text_[i];
1648 if (Inset const * inset = getInset(i)) {
1649 flushString(os, write_buffer);
1650 if (inset->directWrite()) {
1651 // international char, let it write
1652 // code directly so it's shorter in
1658 os << "\\begin_inset ";
1660 os << "\n\\end_inset\n\n";
1666 flushString(os, write_buffer);
1667 os << "\n\\backslash\n";
1671 flushString(os, write_buffer);
1672 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1679 if ((column > 70 && c == ' ')
1681 flushString(os, write_buffer);
1685 // this check is to amend a bug. LyX sometimes
1686 // inserts '\0' this could cause problems.
1688 write_buffer.push_back(c);
1690 LYXERR0("NUL char in structure.");
1696 flushString(os, write_buffer);
1697 os << "\n\\end_layout\n";
1701 void Paragraph::validate(LaTeXFeatures & features) const
1703 d->validate(features);
1707 void Paragraph::insert(pos_type start, docstring const & str,
1708 Font const & font, Change const & change)
1710 for (size_t i = 0, n = str.size(); i != n ; ++i)
1711 insertChar(start + i, str[i], font, change);
1715 void Paragraph::appendChar(char_type c, Font const & font,
1716 Change const & change)
1719 d->changes_.insert(change, d->text_.size());
1720 // when appending characters, no need to update tables
1721 d->text_.push_back(c);
1722 setFont(d->text_.size() - 1, font);
1723 d->requestSpellCheck(d->text_.size() - 1);
1727 void Paragraph::appendString(docstring const & s, Font const & font,
1728 Change const & change)
1730 pos_type end = s.size();
1731 size_t oldsize = d->text_.size();
1732 size_t newsize = oldsize + end;
1733 size_t capacity = d->text_.capacity();
1734 if (newsize >= capacity)
1735 d->text_.reserve(max(capacity + 100, newsize));
1737 // when appending characters, no need to update tables
1740 // FIXME: Optimize this!
1741 for (size_t i = oldsize; i != newsize; ++i) {
1743 d->changes_.insert(change, i);
1744 d->requestSpellCheck(i);
1746 d->fontlist_.set(oldsize, font);
1747 d->fontlist_.set(newsize - 1, font);
1751 void Paragraph::insertChar(pos_type pos, char_type c,
1754 d->insertChar(pos, c, Change(trackChanges ?
1755 Change::INSERTED : Change::UNCHANGED));
1759 void Paragraph::insertChar(pos_type pos, char_type c,
1760 Font const & font, bool trackChanges)
1762 d->insertChar(pos, c, Change(trackChanges ?
1763 Change::INSERTED : Change::UNCHANGED));
1768 void Paragraph::insertChar(pos_type pos, char_type c,
1769 Font const & font, Change const & change)
1771 d->insertChar(pos, c, change);
1776 bool Paragraph::insertInset(pos_type pos, Inset * inset,
1777 Font const & font, Change const & change)
1779 bool const success = insertInset(pos, inset, change);
1780 // Set the font/language of the inset...
1786 void Paragraph::resetFonts(Font const & font)
1788 d->fontlist_.clear();
1789 d->fontlist_.set(0, font);
1790 d->fontlist_.set(d->text_.size() - 1, font);
1793 // Gets uninstantiated font setting at position.
1794 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1798 LYXERR0("pos: " << pos << " size: " << size());
1799 LASSERT(pos <= size(), /**/);
1802 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1803 if (cit != d->fontlist_.end())
1806 if (pos == size() && !empty())
1807 return getFontSettings(bparams, pos - 1);
1809 // Optimisation: avoid a full font instantiation if there is no
1810 // language change from previous call.
1811 static Font previous_font;
1812 static Language const * previous_lang = 0;
1813 Language const * lang = getParLanguage(bparams);
1814 if (lang != previous_lang) {
1815 previous_lang = lang;
1816 previous_font = Font(inherit_font, lang);
1818 return previous_font;
1822 FontSpan Paragraph::fontSpan(pos_type pos) const
1824 LASSERT(pos <= size(), /**/);
1827 FontList::const_iterator cit = d->fontlist_.begin();
1828 FontList::const_iterator end = d->fontlist_.end();
1829 for (; cit != end; ++cit) {
1830 if (cit->pos() >= pos) {
1831 if (pos >= beginOfBody())
1832 return FontSpan(max(start, beginOfBody()),
1835 return FontSpan(start,
1836 min(beginOfBody() - 1,
1839 start = cit->pos() + 1;
1842 // This should not happen, but if so, we take no chances.
1843 // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1844 return FontSpan(pos, pos);
1848 // Gets uninstantiated font setting at position 0
1849 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1851 if (!empty() && !d->fontlist_.empty())
1852 return d->fontlist_.begin()->font();
1854 // Optimisation: avoid a full font instantiation if there is no
1855 // language change from previous call.
1856 static Font previous_font;
1857 static Language const * previous_lang = 0;
1858 if (bparams.language != previous_lang) {
1859 previous_lang = bparams.language;
1860 previous_font = Font(inherit_font, bparams.language);
1863 return previous_font;
1867 // Gets the fully instantiated font at a given position in a paragraph
1868 // This is basically the same function as Text::GetFont() in text2.cpp.
1869 // The difference is that this one is used for generating the LaTeX file,
1870 // and thus cosmetic "improvements" are disallowed: This has to deliver
1871 // the true picture of the buffer. (Asger)
1872 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1873 Font const & outerfont) const
1875 LASSERT(pos >= 0, /**/);
1877 Font font = getFontSettings(bparams, pos);
1879 pos_type const body_pos = beginOfBody();
1880 FontInfo & fi = font.fontInfo();
1882 fi.realize(d->layout_->labelfont);
1884 fi.realize(d->layout_->font);
1886 fi.realize(outerfont.fontInfo());
1887 fi.realize(bparams.getFont().fontInfo());
1893 Font const Paragraph::getLabelFont
1894 (BufferParams const & bparams, Font const & outerfont) const
1896 FontInfo tmpfont = d->layout_->labelfont;
1897 tmpfont.realize(outerfont.fontInfo());
1898 tmpfont.realize(bparams.getFont().fontInfo());
1899 return Font(tmpfont, getParLanguage(bparams));
1903 Font const Paragraph::getLayoutFont
1904 (BufferParams const & bparams, Font const & outerfont) const
1906 FontInfo tmpfont = d->layout_->font;
1907 tmpfont.realize(outerfont.fontInfo());
1908 tmpfont.realize(bparams.getFont().fontInfo());
1909 return Font(tmpfont, getParLanguage(bparams));
1913 /// Returns the height of the highest font in range
1914 FontSize Paragraph::highestFontInRange
1915 (pos_type startpos, pos_type endpos, FontSize def_size) const
1917 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1921 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1923 char_type c = d->text_[pos];
1924 if (!lyxrc.rtl_support || !getFontSettings(bparams, pos).isRightToLeft())
1927 // FIXME: The arabic special casing is due to the difference of arabic
1928 // round brackets input introduced in r18599. Check if this should be
1929 // unified with Hebrew or at least if all bracket types should be
1930 // handled the same (file format change in either case).
1931 string const & lang = getFontSettings(bparams, pos).language()->lang();
1932 bool const arabic = lang == "arabic_arabtex" || lang == "arabic_arabi"
1937 uc = arabic ? c : ')';
1940 uc = arabic ? c : '(';
1966 void Paragraph::setFont(pos_type pos, Font const & font)
1968 LASSERT(pos <= size(), /**/);
1970 // First, reduce font against layout/label font
1971 // Update: The setCharFont() routine in text2.cpp already
1972 // reduces font, so we don't need to do that here. (Asger)
1974 d->fontlist_.set(pos, font);
1978 void Paragraph::makeSameLayout(Paragraph const & par)
1980 d->layout_ = par.d->layout_;
1981 d->params_ = par.d->params_;
1985 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1987 if (isFreeSpacing())
1993 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1994 if (eraseChar(pos, trackChanges))
2000 return count > 0 || pos > 0;
2004 bool Paragraph::hasSameLayout(Paragraph const & par) const
2006 return par.d->layout_ == d->layout_
2007 && d->params_.sameLayout(par.d->params_);
2011 depth_type Paragraph::getDepth() const
2013 return d->params_.depth();
2017 depth_type Paragraph::getMaxDepthAfter() const
2019 if (d->layout_->isEnvironment())
2020 return d->params_.depth() + 1;
2022 return d->params_.depth();
2026 char Paragraph::getAlign() const
2028 if (d->params_.align() == LYX_ALIGN_LAYOUT)
2029 return d->layout_->align;
2031 return d->params_.align();
2035 docstring const & Paragraph::labelString() const
2037 return d->params_.labelString();
2041 // the next two functions are for the manual labels
2042 docstring const Paragraph::getLabelWidthString() const
2044 if (d->layout_->margintype == MARGIN_MANUAL
2045 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2046 return d->params_.labelWidthString();
2048 return _("Senseless with this layout!");
2052 void Paragraph::setLabelWidthString(docstring const & s)
2054 d->params_.labelWidthString(s);
2058 docstring Paragraph::expandLabel(Layout const & layout,
2059 BufferParams const & bparams) const
2061 return expandParagraphLabel(layout, bparams, true);
2065 docstring Paragraph::expandDocBookLabel(Layout const & layout,
2066 BufferParams const & bparams) const
2068 return expandParagraphLabel(layout, bparams, false);
2072 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2073 BufferParams const & bparams, bool process_appendix) const
2075 DocumentClass const & tclass = bparams.documentClass();
2076 string const & lang = getParLanguage(bparams)->code();
2077 bool const in_appendix = process_appendix && d->params_.appendix();
2078 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2080 if (fmt.empty() && layout.labeltype == LABEL_COUNTER
2081 && !layout.counter.empty())
2082 return tclass.counters().theCounter(layout.counter, lang);
2084 // handle 'inherited level parts' in 'fmt',
2085 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2086 size_t const i = fmt.find('@', 0);
2087 if (i != docstring::npos) {
2088 size_t const j = fmt.find('@', i + 1);
2089 if (j != docstring::npos) {
2090 docstring parent(fmt, i + 1, j - i - 1);
2091 docstring label = from_ascii("??");
2092 if (tclass.hasLayout(parent))
2093 docstring label = expandParagraphLabel(tclass[parent], bparams,
2095 fmt = docstring(fmt, 0, i) + label
2096 + docstring(fmt, j + 1, docstring::npos);
2100 return tclass.counters().counterLabel(fmt, lang);
2104 void Paragraph::applyLayout(Layout const & new_layout)
2106 d->layout_ = &new_layout;
2107 LyXAlignment const oldAlign = d->params_.align();
2109 if (!(oldAlign & d->layout_->alignpossible)) {
2110 frontend::Alert::warning(_("Alignment not permitted"),
2111 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2112 d->params_.align(LYX_ALIGN_LAYOUT);
2117 pos_type Paragraph::beginOfBody() const
2119 return d->begin_of_body_;
2123 void Paragraph::setBeginOfBody()
2125 if (d->layout_->labeltype != LABEL_MANUAL) {
2126 d->begin_of_body_ = 0;
2130 // Unroll the first two cycles of the loop
2131 // and remember the previous character to
2132 // remove unnecessary getChar() calls
2134 pos_type end = size();
2135 if (i < end && !isNewline(i)) {
2137 char_type previous_char = 0;
2140 previous_char = d->text_[i];
2141 if (!isNewline(i)) {
2143 while (i < end && previous_char != ' ') {
2148 previous_char = temp;
2154 d->begin_of_body_ = i;
2158 bool Paragraph::allowParagraphCustomization() const
2160 return inInset().allowParagraphCustomization();
2164 bool Paragraph::usePlainLayout() const
2166 return inInset().usePlainLayout();
2170 bool Paragraph::isPassThru() const
2172 return inInset().getLayout().isPassThru() || d->layout_->pass_thru;
2177 // paragraphs inside floats need different alignment tags to avoid
2180 bool noTrivlistCentering(InsetCode code)
2182 return code == FLOAT_CODE
2183 || code == WRAP_CODE
2184 || code == CELL_CODE;
2188 string correction(string const & orig)
2190 if (orig == "flushleft")
2191 return "raggedright";
2192 if (orig == "flushright")
2193 return "raggedleft";
2194 if (orig == "center")
2200 string const corrected_env(string const & suffix, string const & env,
2201 InsetCode code, bool const lastpar)
2203 string output = suffix + "{";
2204 if (noTrivlistCentering(code)) {
2206 // the last paragraph in non-trivlist-aligned
2207 // context is special (to avoid unwanted whitespace)
2208 if (suffix == "\\begin")
2209 return "\\" + correction(env) + "{}";
2212 output += correction(env);
2216 if (suffix == "\\begin")
2222 void adjust_column(string const & str, int & column)
2224 if (!contains(str, "\n"))
2225 column += str.size();
2228 column = rsplit(str, tmp, '\n').size();
2235 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2236 otexstream & os, OutputParams const & runparams) const
2240 if (params_.noindent() && !layout_->pass_thru) {
2241 os << "\\noindent ";
2245 LyXAlignment const curAlign = params_.align();
2247 if (curAlign == layout_->align)
2251 case LYX_ALIGN_NONE:
2252 case LYX_ALIGN_BLOCK:
2253 case LYX_ALIGN_LAYOUT:
2254 case LYX_ALIGN_SPECIAL:
2255 case LYX_ALIGN_DECIMAL:
2257 case LYX_ALIGN_LEFT:
2258 case LYX_ALIGN_RIGHT:
2259 case LYX_ALIGN_CENTER:
2260 if (runparams.moving_arg) {
2267 string const begin_tag = "\\begin";
2268 InsetCode code = ownerCode();
2269 bool const lastpar = runparams.isLastPar;
2272 case LYX_ALIGN_NONE:
2273 case LYX_ALIGN_BLOCK:
2274 case LYX_ALIGN_LAYOUT:
2275 case LYX_ALIGN_SPECIAL:
2276 case LYX_ALIGN_DECIMAL:
2278 case LYX_ALIGN_LEFT: {
2280 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2281 output = corrected_env(begin_tag, "flushleft", code, lastpar);
2283 output = corrected_env(begin_tag, "flushright", code, lastpar);
2284 os << from_ascii(output);
2285 adjust_column(output, column);
2287 } case LYX_ALIGN_RIGHT: {
2289 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2290 output = corrected_env(begin_tag, "flushright", code, lastpar);
2292 output = corrected_env(begin_tag, "flushleft", code, lastpar);
2293 os << from_ascii(output);
2294 adjust_column(output, column);
2296 } case LYX_ALIGN_CENTER: {
2298 output = corrected_env(begin_tag, "center", code, lastpar);
2299 os << from_ascii(output);
2300 adjust_column(output, column);
2309 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2310 otexstream & os, OutputParams const & runparams) const
2312 LyXAlignment const curAlign = params_.align();
2314 if (curAlign == layout_->align)
2318 case LYX_ALIGN_NONE:
2319 case LYX_ALIGN_BLOCK:
2320 case LYX_ALIGN_LAYOUT:
2321 case LYX_ALIGN_SPECIAL:
2322 case LYX_ALIGN_DECIMAL:
2324 case LYX_ALIGN_LEFT:
2325 case LYX_ALIGN_RIGHT:
2326 case LYX_ALIGN_CENTER:
2327 if (runparams.moving_arg)
2333 string const end_tag = "\n\\par\\end";
2334 InsetCode code = ownerCode();
2335 bool const lastpar = runparams.isLastPar;
2338 case LYX_ALIGN_NONE:
2339 case LYX_ALIGN_BLOCK:
2340 case LYX_ALIGN_LAYOUT:
2341 case LYX_ALIGN_SPECIAL:
2342 case LYX_ALIGN_DECIMAL:
2344 case LYX_ALIGN_LEFT: {
2345 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2346 output = corrected_env(end_tag, "flushleft", code, lastpar);
2348 output = corrected_env(end_tag, "flushright", code, lastpar);
2349 os << from_ascii(output);
2351 } case LYX_ALIGN_RIGHT: {
2352 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2353 output = corrected_env(end_tag, "flushright", code, lastpar);
2355 output = corrected_env(end_tag, "flushleft", code, lastpar);
2356 os << from_ascii(output);
2358 } case LYX_ALIGN_CENTER: {
2359 output = corrected_env(end_tag, "center", code, lastpar);
2360 os << from_ascii(output);
2365 return !output.empty() || lastpar;
2369 // This one spits out the text of the paragraph
2370 void Paragraph::latex(BufferParams const & bparams,
2371 Font const & outerfont,
2373 OutputParams const & runparams,
2374 int start_pos, int end_pos, bool force) const
2376 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2378 // FIXME This check should not be needed. Perhaps issue an
2379 // error if it triggers.
2380 Layout const & style = inInset().forcePlainLayout() ?
2381 bparams.documentClass().plainLayout() : *d->layout_;
2383 if (!force && style.inpreamble)
2386 bool const allowcust = allowParagraphCustomization();
2388 // Current base font for all inherited font changes, without any
2389 // change caused by an individual character, except for the language:
2390 // It is set to the language of the first character.
2391 // As long as we are in the label, this font is the base font of the
2392 // label. Before the first body character it is set to the base font
2396 // Maybe we have to create a optional argument.
2397 pos_type body_pos = beginOfBody();
2398 unsigned int column = 0;
2401 // the optional argument is kept in curly brackets in
2402 // case it contains a ']'
2403 // This is not strictly needed, but if this is changed it
2404 // would be a file format change, and tex2lyx would need
2405 // to be adjusted, since it unconditionally removes the
2406 // braces when it parses \item.
2409 basefont = getLabelFont(bparams, outerfont);
2411 basefont = getLayoutFont(bparams, outerfont);
2414 // Which font is currently active?
2415 Font running_font(basefont);
2416 // Do we have an open font change?
2417 bool open_font = false;
2419 Change runningChange = Change(Change::UNCHANGED);
2421 Encoding const * const prev_encoding = runparams.encoding;
2423 os.texrow().start(id(), 0);
2425 // if the paragraph is empty, the loop will not be entered at all
2427 if (style.isCommand()) {
2432 column += d->startTeXParParams(bparams, os, runparams);
2435 for (pos_type i = 0; i < size(); ++i) {
2436 // First char in paragraph or after label?
2437 if (i == body_pos) {
2440 column += running_font.latexWriteEndChanges(
2441 os, bparams, runparams,
2442 basefont, basefont);
2445 basefont = getLayoutFont(bparams, outerfont);
2446 running_font = basefont;
2448 column += Changes::latexMarkChange(os, bparams,
2449 runningChange, Change(Change::UNCHANGED),
2451 runningChange = Change(Change::UNCHANGED);
2456 if (style.isCommand()) {
2462 column += d->startTeXParParams(bparams, os,
2466 Change const & change = runparams.inDeletedInset
2467 ? runparams.changeOfDeletedInset : lookupChange(i);
2469 if (bparams.outputChanges && runningChange != change) {
2471 column += running_font.latexWriteEndChanges(
2472 os, bparams, runparams, basefont, basefont);
2475 basefont = getLayoutFont(bparams, outerfont);
2476 running_font = basefont;
2478 column += Changes::latexMarkChange(os, bparams, runningChange,
2480 runningChange = change;
2483 // do not output text which is marked deleted
2484 // if change tracking output is disabled
2485 if (!bparams.outputChanges && change.deleted()) {
2491 // Fully instantiated font
2492 Font const font = getFont(bparams, i, outerfont);
2494 Font const last_font = running_font;
2496 // Do we need to close the previous font?
2498 (font != running_font ||
2499 font.language() != running_font.language()))
2501 column += running_font.latexWriteEndChanges(
2502 os, bparams, runparams, basefont,
2503 (i == body_pos-1) ? basefont : font);
2504 running_font = basefont;
2508 string const running_lang = runparams.use_polyglossia ?
2509 running_font.language()->polyglossia() : running_font.language()->babel();
2510 // close babel's font environment before opening CJK.
2511 string const lang_end_command = runparams.use_polyglossia ?
2512 "\\end{$$lang}" : lyxrc.language_command_end;
2513 if (!running_lang.empty() &&
2514 font.language()->encoding()->package() == Encoding::CJK) {
2515 string end_tag = subst(lang_end_command,
2518 os << from_ascii(end_tag);
2519 column += end_tag.length();
2522 // Switch file encoding if necessary (and allowed)
2523 if (!runparams.pass_thru && !style.pass_thru &&
2524 runparams.encoding->package() != Encoding::none &&
2525 font.language()->encoding()->package() != Encoding::none) {
2526 pair<bool, int> const enc_switch =
2527 switchEncoding(os.os(), bparams, runparams,
2528 *(font.language()->encoding()));
2529 if (enc_switch.first) {
2530 column += enc_switch.second;
2531 runparams.encoding = font.language()->encoding();
2535 char_type const c = d->text_[i];
2537 // Do we need to change font?
2538 if ((font != running_font ||
2539 font.language() != running_font.language()) &&
2542 odocstringstream ods;
2543 column += font.latexWriteStartChanges(ods, bparams,
2544 runparams, basefont,
2546 running_font = font;
2548 docstring fontchange = ods.str();
2549 // check whether the fontchange ends with a \\textcolor
2550 // modifier and the text starts with a space (bug 4473)
2551 docstring const last_modifier = rsplit(fontchange, '\\');
2552 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2553 os << fontchange << from_ascii("{}");
2554 // check if the fontchange ends with a trailing blank
2555 // (like "\small " (see bug 3382)
2556 else if (suffixIs(fontchange, ' ') && c == ' ')
2557 os << fontchange.substr(0, fontchange.size() - 1)
2558 << from_ascii("{}");
2563 // FIXME: think about end_pos implementation...
2564 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2565 // FIXME: integrate this case in latexSpecialChar
2566 // Do not print the separation of the optional argument
2567 // if style.pass_thru is false. This works because
2568 // latexSpecialChar ignores spaces if
2569 // style.pass_thru is false.
2570 if (i != body_pos - 1) {
2571 if (d->simpleTeXBlanks(runparams, os,
2572 i, column, font, style)) {
2573 // A surrogate pair was output. We
2574 // must not call latexSpecialChar
2575 // in this iteration, since it would output
2576 // the combining character again.
2583 OutputParams rp = runparams;
2584 rp.free_spacing = style.free_spacing;
2585 rp.local_font = &font;
2586 rp.intitle = style.intitle;
2588 // Two major modes: LaTeX or plain
2589 // Handle here those cases common to both modes
2590 // and then split to handle the two modes separately.
2591 if (c == META_INSET) {
2592 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2593 d->latexInset(bparams, os, rp, running_font,
2594 basefont, outerfont, open_font,
2595 runningChange, style, i, column);
2598 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2600 d->latexSpecialChar(os, bparams, rp, running_font, runningChange,
2601 style, i, end_pos, column);
2602 } catch (EncodingException & e) {
2603 if (runparams.dryrun) {
2604 os << "<" << _("LyX Warning: ")
2605 << _("uncodable character") << " '";
2609 // add location information and throw again.
2618 // Set the encoding to that returned from latexSpecialChar (see
2619 // comment for encoding member in OutputParams.h)
2620 runparams.encoding = rp.encoding;
2623 // If we have an open font definition, we have to close it
2625 #ifdef FIXED_LANGUAGE_END_DETECTION
2627 running_font.latexWriteEndChanges(os, bparams,
2628 runparams, basefont,
2629 next_->getFont(bparams, 0, outerfont));
2631 running_font.latexWriteEndChanges(os, bparams,
2632 runparams, basefont, basefont);
2635 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2636 //FIXME: there as we start another \selectlanguage with the next paragraph if
2637 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2638 running_font.latexWriteEndChanges(os, bparams, runparams,
2639 basefont, basefont);
2643 column += Changes::latexMarkChange(os, bparams, runningChange,
2644 Change(Change::UNCHANGED), runparams);
2646 // Needed if there is an optional argument but no contents.
2647 if (body_pos > 0 && body_pos == size()) {
2651 if (allowcust && d->endTeXParParams(bparams, os, runparams)
2652 && runparams.encoding != prev_encoding) {
2653 runparams.encoding = prev_encoding;
2654 if (!runparams.isFullUnicode())
2655 os << setEncoding(prev_encoding->iconvName());
2658 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2662 bool Paragraph::emptyTag() const
2664 for (pos_type i = 0; i < size(); ++i) {
2665 if (Inset const * inset = getInset(i)) {
2666 InsetCode lyx_code = inset->lyxCode();
2667 // FIXME testing like that is wrong. What is
2669 if (lyx_code != TOC_CODE &&
2670 lyx_code != INCLUDE_CODE &&
2671 lyx_code != GRAPHICS_CODE &&
2672 lyx_code != ERT_CODE &&
2673 lyx_code != LISTINGS_CODE &&
2674 lyx_code != FLOAT_CODE &&
2675 lyx_code != TABULAR_CODE) {
2679 char_type c = d->text_[i];
2680 if (c != ' ' && c != '\t')
2688 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2691 for (pos_type i = 0; i < size(); ++i) {
2692 if (Inset const * inset = getInset(i)) {
2693 InsetCode lyx_code = inset->lyxCode();
2694 if (lyx_code == LABEL_CODE) {
2695 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2696 docstring const & id = il->getParam("name");
2697 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2705 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2709 for (i = 0; i < size(); ++i) {
2710 if (Inset const * inset = getInset(i)) {
2711 inset->docbook(os, runparams);
2713 char_type c = d->text_[i];
2716 os << sgml::escapeChar(c);
2723 pos_type Paragraph::firstWordLyXHTML(XHTMLStream & xs, OutputParams const & runparams)
2727 for (i = 0; i < size(); ++i) {
2728 if (Inset const * inset = getInset(i)) {
2729 inset->xhtml(xs, runparams);
2731 char_type c = d->text_[i];
2741 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2744 pos_type size = text_.size();
2745 for (pos_type i = initial; i < size; ++i) {
2746 Font font = owner_->getFont(buf.params(), i, outerfont);
2747 if (text_[i] == META_INSET)
2749 if (i != initial && font != font_old)
2758 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2760 OutputParams const & runparams,
2761 Font const & outerfont,
2762 pos_type initial) const
2764 bool emph_flag = false;
2766 Layout const & style = *d->layout_;
2768 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2770 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2773 // parsing main loop
2774 for (pos_type i = initial; i < size(); ++i) {
2775 Font font = getFont(buf.params(), i, outerfont);
2777 // handle <emphasis> tag
2778 if (font_old.emph() != font.fontInfo().emph()) {
2779 if (font.fontInfo().emph() == FONT_ON) {
2782 } else if (i != initial) {
2783 os << "</emphasis>";
2788 if (Inset const * inset = getInset(i)) {
2789 inset->docbook(os, runparams);
2791 char_type c = d->text_[i];
2793 if (style.pass_thru)
2796 os << sgml::escapeChar(c);
2798 font_old = font.fontInfo();
2802 os << "</emphasis>";
2805 if (style.free_spacing)
2807 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2812 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2814 OutputParams const & runparams,
2815 Font const & outerfont,
2816 pos_type initial) const
2820 bool emph_flag = false;
2821 bool bold_flag = false;
2823 Layout const & style = *d->layout_;
2825 xs.startParagraph(allowEmpty());
2827 if (!runparams.for_toc && runparams.html_make_pars) {
2828 // generate a magic label for this paragraph
2829 string const attr = "id='" + magicLabel() + "'";
2830 xs << html::CompTag("a", attr);
2834 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2836 // parsing main loop
2837 for (pos_type i = initial; i < size(); ++i) {
2838 // let's not show deleted material in the output
2842 Font font = getFont(buf.params(), i, outerfont);
2845 if (font_old.emph() != font.fontInfo().emph()) {
2846 if (font.fontInfo().emph() == FONT_ON) {
2847 xs << html::StartTag("em");
2849 } else if (emph_flag && i != initial) {
2850 xs << html::EndTag("em");
2855 if (font_old.series() != font.fontInfo().series()) {
2856 if (font.fontInfo().series() == BOLD_SERIES) {
2857 xs << html::StartTag("strong");
2859 } else if (bold_flag && i != initial) {
2860 xs << html::EndTag("strong");
2865 // Other such tags? What about the other text ranges?
2867 Inset const * inset = getInset(i);
2869 if (!runparams.for_toc || inset->isInToc()) {
2870 OutputParams np = runparams;
2871 if (!inset->getLayout().htmlisblock())
2872 np.html_in_par = true;
2873 retval += inset->xhtml(xs, np);
2876 char_type c = getUChar(buf.params(), i);
2878 if (style.pass_thru)
2880 else if (c == '-') {
2883 if (j < size() && d->text_[j] == '-') {
2885 if (j < size() && d->text_[j] == '-') {
2886 str += from_ascii("—");
2889 str += from_ascii("–");
2895 // We don't want to escape the entities. Note that
2896 // it is safe to do this, since str can otherwise
2897 // only be "-". E.g., it can't be "<".
2898 xs << XHTMLStream::ESCAPE_NONE << str;
2902 font_old = font.fontInfo();
2911 bool Paragraph::isHfill(pos_type pos) const
2913 Inset const * inset = getInset(pos);
2914 return inset && (inset->lyxCode() == SPACE_CODE &&
2915 inset->isStretchableSpace());
2919 bool Paragraph::isNewline(pos_type pos) const
2921 Inset const * inset = getInset(pos);
2922 return inset && inset->lyxCode() == NEWLINE_CODE;
2926 bool Paragraph::isLineSeparator(pos_type pos) const
2928 char_type const c = d->text_[pos];
2929 if (isLineSeparatorChar(c))
2931 Inset const * inset = getInset(pos);
2932 return inset && inset->isLineSeparator();
2936 bool Paragraph::isWordSeparator(pos_type pos) const
2940 if (Inset const * inset = getInset(pos))
2941 return !inset->isLetter();
2942 // if we have a hard hyphen (no en- or emdash) or apostrophe
2943 // we pass this to the spell checker
2944 // FIXME: this method is subject to change, visit
2945 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
2946 // to get an impression how complex this is.
2947 if (isHardHyphenOrApostrophe(pos))
2949 char_type const c = d->text_[pos];
2950 // We want to pass the escape chars to the spellchecker
2951 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
2952 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
2956 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
2958 pos_type const psize = size();
2961 char_type const c = d->text_[pos];
2962 if (c != '-' && c != '\'')
2964 int nextpos = pos + 1;
2965 int prevpos = pos > 0 ? pos - 1 : 0;
2966 if ((nextpos == psize || isSpace(nextpos))
2967 && (pos == 0 || isSpace(prevpos)))
2970 || ((nextpos == psize || d->text_[nextpos] != '-')
2971 && (pos == 0 || d->text_[prevpos] != '-'));
2975 bool Paragraph::isSameSpellRange(pos_type pos1, pos_type pos2) const
2978 || d->speller_state_.getRange(pos1) == d->speller_state_.getRange(pos2);
2982 bool Paragraph::isChar(pos_type pos) const
2984 if (Inset const * inset = getInset(pos))
2985 return inset->isChar();
2986 char_type const c = d->text_[pos];
2987 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
2991 bool Paragraph::isSpace(pos_type pos) const
2993 if (Inset const * inset = getInset(pos))
2994 return inset->isSpace();
2995 char_type const c = d->text_[pos];
2996 return lyx::isSpace(c);
3001 Paragraph::getParLanguage(BufferParams const & bparams) const
3004 return getFirstFontSettings(bparams).language();
3005 // FIXME: we should check the prev par as well (Lgb)
3006 return bparams.language;
3010 bool Paragraph::isRTL(BufferParams const & bparams) const
3012 return lyxrc.rtl_support
3013 && getParLanguage(bparams)->rightToLeft()
3014 && !inInset().getLayout().forceLTR();
3018 void Paragraph::changeLanguage(BufferParams const & bparams,
3019 Language const * from, Language const * to)
3021 // change language including dummy font change at the end
3022 for (pos_type i = 0; i <= size(); ++i) {
3023 Font font = getFontSettings(bparams, i);
3024 if (font.language() == from) {
3025 font.setLanguage(to);
3027 d->requestSpellCheck(i);
3033 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
3035 Language const * doc_language = bparams.language;
3036 FontList::const_iterator cit = d->fontlist_.begin();
3037 FontList::const_iterator end = d->fontlist_.end();
3039 for (; cit != end; ++cit)
3040 if (cit->font().language() != ignore_language &&
3041 cit->font().language() != latex_language &&
3042 cit->font().language() != doc_language)
3048 void Paragraph::getLanguages(std::set<Language const *> & languages) const
3050 FontList::const_iterator cit = d->fontlist_.begin();
3051 FontList::const_iterator end = d->fontlist_.end();
3053 for (; cit != end; ++cit) {
3054 Language const * lang = cit->font().language();
3055 if (lang != ignore_language &&
3056 lang != latex_language)
3057 languages.insert(lang);
3062 docstring Paragraph::asString(int options) const
3064 return asString(0, size(), options);
3068 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
3070 odocstringstream os;
3073 && options & AS_STR_LABEL
3074 && !d->params_.labelString().empty())
3075 os << d->params_.labelString() << ' ';
3077 for (pos_type i = beg; i < end; ++i) {
3078 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
3080 char_type const c = d->text_[i];
3081 if (isPrintable(c) || c == '\t'
3082 || (c == '\n' && (options & AS_STR_NEWLINES)))
3084 else if (c == META_INSET && (options & AS_STR_INSETS)) {
3085 getInset(i)->toString(os);
3086 if (getInset(i)->asInsetMath())
3095 void Paragraph::forToc(docstring & os, size_t maxlen) const
3097 if (!d->params_.labelString().empty())
3098 os += d->params_.labelString() + ' ';
3099 for (pos_type i = 0; i < size() && os.length() < maxlen; ++i) {
3102 char_type const c = d->text_[i];
3105 else if (c == '\t' || c == '\n')
3107 else if (c == META_INSET)
3108 getInset(i)->forToc(os, maxlen);
3113 docstring Paragraph::stringify(pos_type beg, pos_type end, int options, OutputParams & runparams) const
3115 odocstringstream os;
3118 && options & AS_STR_LABEL
3119 && !d->params_.labelString().empty())
3120 os << d->params_.labelString() << ' ';
3122 for (pos_type i = beg; i < end; ++i) {
3123 char_type const c = d->text_[i];
3124 if (isPrintable(c) || c == '\t'
3125 || (c == '\n' && (options & AS_STR_NEWLINES)))
3127 else if (c == META_INSET && (options & AS_STR_INSETS)) {
3128 getInset(i)->plaintext(os, runparams);
3136 void Paragraph::setInsetOwner(Inset const * inset)
3138 d->inset_owner_ = inset;
3142 int Paragraph::id() const
3148 void Paragraph::setId(int id)
3154 Layout const & Paragraph::layout() const
3160 void Paragraph::setLayout(Layout const & layout)
3162 d->layout_ = &layout;
3166 void Paragraph::setDefaultLayout(DocumentClass const & tc)
3168 setLayout(tc.defaultLayout());
3172 void Paragraph::setPlainLayout(DocumentClass const & tc)
3174 setLayout(tc.plainLayout());
3178 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
3180 if (usePlainLayout())
3181 setPlainLayout(tclass);
3183 setDefaultLayout(tclass);
3187 Inset const & Paragraph::inInset() const
3189 LASSERT(d->inset_owner_, throw ExceptionMessage(BufferException,
3190 _("Memory problem"), _("Paragraph not properly initialized")));
3191 return *d->inset_owner_;
3195 ParagraphParameters & Paragraph::params()
3201 ParagraphParameters const & Paragraph::params() const
3207 bool Paragraph::isFreeSpacing() const
3209 if (d->layout_->free_spacing)
3211 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
3215 bool Paragraph::allowEmpty() const
3217 if (d->layout_->keepempty)
3219 return d->inset_owner_ && d->inset_owner_->allowEmpty();
3223 char_type Paragraph::transformChar(char_type c, pos_type pos) const
3225 if (!Encodings::isArabicChar(c))
3228 char_type prev_char = ' ';
3229 char_type next_char = ' ';
3231 for (pos_type i = pos - 1; i >= 0; --i) {
3232 char_type const par_char = d->text_[i];
3233 if (!Encodings::isArabicComposeChar(par_char)) {
3234 prev_char = par_char;
3239 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
3240 char_type const par_char = d->text_[i];
3241 if (!Encodings::isArabicComposeChar(par_char)) {
3242 next_char = par_char;
3247 if (Encodings::isArabicChar(next_char)) {
3248 if (Encodings::isArabicChar(prev_char) &&
3249 !Encodings::isArabicSpecialChar(prev_char))
3250 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
3252 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
3254 if (Encodings::isArabicChar(prev_char) &&
3255 !Encodings::isArabicSpecialChar(prev_char))
3256 return Encodings::transformChar(c, Encodings::FORM_FINAL);
3258 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
3263 bool Paragraph::brokenBiblio() const
3265 // there is a problem if there is no bibitem at position 0 or
3266 // if there is another bibitem in the paragraph.
3267 return d->layout_->labeltype == LABEL_BIBLIO
3268 && (d->insetlist_.find(BIBITEM_CODE) != 0
3269 || d->insetlist_.find(BIBITEM_CODE, 1) > 0);
3273 int Paragraph::fixBiblio(Buffer const & buffer)
3275 // FIXME: What about the case where paragraph is not BIBLIO
3276 // but there is an InsetBibitem?
3277 // FIXME: when there was already an inset at 0, the return value is 1,
3278 // which does not tell whether another inset has been remove; the
3279 // cursor cannot be correctly updated.
3281 if (d->layout_->labeltype != LABEL_BIBLIO)
3284 bool const track_changes = buffer.params().trackChanges;
3285 int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
3286 bool const hasbibitem0 = bibitem_pos == 0;
3289 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
3290 // There was an InsetBibitem at pos 0, and no other one => OK
3291 if (bibitem_pos == -1)
3293 // there is a bibitem at the 0 position, but since
3294 // there is a second one, we copy the second on the
3295 // first. We're assuming there are at most two of
3296 // these, which there should be.
3297 // FIXME: why does it make sense to do that rather
3298 // than keep the first? (JMarc)
3299 Inset * inset = d->insetlist_.release(bibitem_pos);
3300 eraseChar(bibitem_pos, track_changes);
3301 d->insetlist_.begin()->inset = inset;
3302 return -bibitem_pos;
3305 // We need to create an inset at the beginning
3307 if (bibitem_pos > 0) {
3308 // there was one somewhere in the paragraph, let's move it
3309 inset = d->insetlist_.release(bibitem_pos);
3310 eraseChar(bibitem_pos, track_changes);
3313 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
3314 InsetCommandParams(BIBITEM_CODE));
3316 insertInset(0, inset, Change(track_changes ? Change::INSERTED
3317 : Change::UNCHANGED));
3323 void Paragraph::checkAuthors(AuthorList const & authorList)
3325 d->changes_.checkAuthors(authorList);
3329 bool Paragraph::isChanged(pos_type pos) const
3331 return lookupChange(pos).changed();
3335 bool Paragraph::isInserted(pos_type pos) const
3337 return lookupChange(pos).inserted();
3341 bool Paragraph::isDeleted(pos_type pos) const
3343 return lookupChange(pos).deleted();
3347 InsetList const & Paragraph::insetList() const
3349 return d->insetlist_;
3353 void Paragraph::setBuffer(Buffer & b)
3355 d->insetlist_.setBuffer(b);
3359 Inset * Paragraph::releaseInset(pos_type pos)
3361 Inset * inset = d->insetlist_.release(pos);
3362 /// does not honour change tracking!
3363 eraseChar(pos, false);
3368 Inset * Paragraph::getInset(pos_type pos)
3370 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3371 ? d->insetlist_.get(pos) : 0;
3375 Inset const * Paragraph::getInset(pos_type pos) const
3377 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3378 ? d->insetlist_.get(pos) : 0;
3382 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
3383 pos_type & right, TextCase action)
3385 // process sequences of modified characters; in change
3386 // tracking mode, this approach results in much better
3387 // usability than changing case on a char-by-char basis
3390 bool const trackChanges = bparams.trackChanges;
3392 bool capitalize = true;
3394 for (; pos < right; ++pos) {
3395 char_type oldChar = d->text_[pos];
3396 char_type newChar = oldChar;
3398 // ignore insets and don't play with deleted text!
3399 if (oldChar != META_INSET && !isDeleted(pos)) {
3401 case text_lowercase:
3402 newChar = lowercase(oldChar);
3404 case text_capitalization:
3406 newChar = uppercase(oldChar);
3410 case text_uppercase:
3411 newChar = uppercase(oldChar);
3416 if (isWordSeparator(pos) || isDeleted(pos)) {
3417 // permit capitalization again
3421 if (oldChar != newChar) {
3423 if (pos != right - 1)
3425 // step behind the changing area
3429 int erasePos = pos - changes.size();
3430 for (size_t i = 0; i < changes.size(); i++) {
3431 insertChar(pos, changes[i],
3432 getFontSettings(bparams,
3435 if (!eraseChar(erasePos, trackChanges)) {
3438 ++right; // expand selection
3446 int Paragraph::find(docstring const & str, bool cs, bool mw,
3447 pos_type start_pos, bool del) const
3449 pos_type pos = start_pos;
3450 int const strsize = str.length();
3452 pos_type const parsize = d->text_.size();
3453 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
3454 // Ignore "invisible" letters such as ligature breaks
3455 // and hyphenation chars while searching
3456 while (pos < parsize - 1 && isInset(pos)) {
3457 odocstringstream os;
3458 getInset(pos)->toString(os);
3459 if (!getInset(pos)->isLetter() || !os.str().empty())
3463 if (cs && str[i] != d->text_[pos])
3465 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
3467 if (!del && isDeleted(pos))
3474 // if necessary, check whether string matches word
3476 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
3479 && !isWordSeparator(pos))
3483 return pos - start_pos;
3487 char_type Paragraph::getChar(pos_type pos) const
3489 return d->text_[pos];
3493 pos_type Paragraph::size() const
3495 return d->text_.size();
3499 bool Paragraph::empty() const
3501 return d->text_.empty();
3505 bool Paragraph::isInset(pos_type pos) const
3507 return d->text_[pos] == META_INSET;
3511 bool Paragraph::isSeparator(pos_type pos) const
3513 //FIXME: Are we sure this can be the only separator?
3514 return d->text_[pos] == ' ';
3518 void Paragraph::deregisterWords()
3520 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3521 Private::LangWordsMap::const_iterator ite = d->words_.end();
3522 for (; itl != ite; ++itl) {
3523 WordList * wl = theWordList(itl->first);
3524 Private::Words::const_iterator it = (itl->second).begin();
3525 Private::Words::const_iterator et = (itl->second).end();
3526 for (; it != et; ++it)
3533 void Paragraph::locateWord(pos_type & from, pos_type & to,
3534 word_location const loc) const
3537 case WHOLE_WORD_STRICT:
3538 if (from == 0 || from == size()
3539 || isWordSeparator(from)
3540 || isWordSeparator(from - 1)) {
3544 // no break here, we go to the next
3547 // If we are already at the beginning of a word, do nothing
3548 if (!from || isWordSeparator(from - 1))
3550 // no break here, we go to the next
3553 // always move the cursor to the beginning of previous word
3554 while (from && !isWordSeparator(from - 1))
3558 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3561 // no need to move the 'from' cursor
3565 while (to < size() && !isWordSeparator(to))
3570 void Paragraph::collectWords()
3572 pos_type n = size();
3573 for (pos_type pos = 0; pos < n; ++pos) {
3574 if (isWordSeparator(pos))
3576 pos_type from = pos;
3577 locateWord(from, pos, WHOLE_WORD);
3578 if ((pos - from) >= (int)lyxrc.completion_minlength) {
3579 docstring word = asString(from, pos, AS_STR_NONE);
3580 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
3581 if (cit == d->fontlist_.end())
3583 Language const * lang = cit->font().language();
3584 d->words_[*lang].insert(word);
3590 void Paragraph::registerWords()
3592 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3593 Private::LangWordsMap::const_iterator ite = d->words_.end();
3594 for (; itl != ite; ++itl) {
3595 WordList * wl = theWordList(itl->first);
3596 Private::Words::const_iterator it = (itl->second).begin();
3597 Private::Words::const_iterator et = (itl->second).end();
3598 for (; it != et; ++it)
3604 void Paragraph::updateWords()
3612 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
3614 SkipPositionsIterator begin = skips.begin();
3615 SkipPositions::iterator end = skips.end();
3616 if (pos > 0 && begin < end) {
3618 if (end->last == pos - 1) {
3623 skips.insert(end, FontSpan(pos, pos));
3627 Language * Paragraph::Private::locateSpellRange(
3628 pos_type & from, pos_type & to,
3629 SkipPositions & skips) const
3631 // skip leading white space
3632 while (from < to && owner_->isWordSeparator(from))
3634 // don't check empty range
3637 // get current language
3638 Language * lang = getSpellLanguage(from);
3639 pos_type last = from;
3640 bool samelang = true;
3641 bool sameinset = true;
3642 while (last < to && samelang && sameinset) {
3643 // hop to end of word
3644 while (last < to && !owner_->isWordSeparator(last)) {
3645 if (owner_->getInset(last)) {
3646 appendSkipPosition(skips, last);
3647 } else if (owner_->isDeleted(last)) {
3648 appendSkipPosition(skips, last);
3652 // hop to next word while checking for insets
3653 while (sameinset && last < to && owner_->isWordSeparator(last)) {
3654 if (Inset const * inset = owner_->getInset(last))
3655 sameinset = inset->isChar() && inset->isLetter();
3656 if (sameinset && owner_->isDeleted(last)) {
3657 appendSkipPosition(skips, last);
3662 if (sameinset && last < to) {
3663 // now check for language change
3664 samelang = lang == getSpellLanguage(last);
3667 // if language change detected backstep is needed
3675 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
3678 const_cast<Language *>(owner_->getFontSettings(
3679 inset_owner_->buffer().params(), from).language());
3680 if (lang == inset_owner_->buffer().params().language
3681 && !lyxrc.spellchecker_alt_lang.empty()) {
3683 string const lang_variety =
3684 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
3685 lang->setCode(lang_code);
3686 lang->setVariety(lang_variety);
3692 void Paragraph::requestSpellCheck(pos_type pos)
3694 d->requestSpellCheck(pos);
3698 bool Paragraph::needsSpellCheck() const
3700 SpellChecker::ChangeNumber speller_change_number = 0;
3701 if (theSpellChecker())
3702 speller_change_number = theSpellChecker()->changeNumber();
3703 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
3704 d->speller_state_.needsCompleteRefresh(speller_change_number);
3706 return d->needsSpellCheck();
3710 bool Paragraph::Private::ignoreWord(docstring const & word) const
3712 // Ignore words with digits
3713 // FIXME: make this customizable
3714 // (note that some checkers ignore words with digits by default)
3715 docstring::const_iterator cit = word.begin();
3716 docstring::const_iterator const end = word.end();
3717 for (; cit != end; ++cit) {
3718 if (isNumber((*cit)))
3725 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
3726 WordLangTuple & wl, docstring_list & suggestions,
3727 bool do_suggestion, bool check_learned) const
3729 SpellChecker::Result result = SpellChecker::WORD_OK;
3730 SpellChecker * speller = theSpellChecker();
3734 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
3737 locateWord(from, to, WHOLE_WORD);
3738 if (from == to || from >= size())
3741 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
3742 Language * lang = d->getSpellLanguage(from);
3744 wl = WordLangTuple(word, lang);
3749 if (needsSpellCheck() || check_learned) {
3751 if (!d->ignoreWord(word)) {
3752 bool const trailing_dot = to < size() && d->text_[to] == '.';
3753 result = speller->check(wl);
3754 if (SpellChecker::misspelled(result) && trailing_dot) {
3755 wl = WordLangTuple(word.append(from_ascii(".")), lang);
3756 result = speller->check(wl);
3757 if (!SpellChecker::misspelled(result)) {
3758 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
3760 from << ".." << to << "]");
3762 // spell check with dot appended failed too
3763 // restore original word/lang value
3764 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
3765 wl = WordLangTuple(word, lang);
3769 if (!SpellChecker::misspelled(result)) {
3770 // area up to the begin of the next word is not misspelled
3771 while (end < size() && isWordSeparator(end))
3774 d->setMisspelled(from, end, result);
3776 result = d->speller_state_.getState(from);
3780 suggestions.clear();
3782 if (SpellChecker::misspelled(result)) {
3783 LYXERR(Debug::GUI, "misspelled word: \"" <<
3785 from << ".." << to << "]");
3787 speller->suggest(wl, suggestions);
3793 void Paragraph::Private::markMisspelledWords(
3794 pos_type const & first, pos_type const & last,
3795 SpellChecker::Result result,
3796 docstring const & word,
3797 SkipPositions const & skips)
3799 if (!SpellChecker::misspelled(result)) {
3800 setMisspelled(first, last, SpellChecker::WORD_OK);
3804 SpellChecker * speller = theSpellChecker();
3805 // locate and enumerate the error positions
3806 int nerrors = speller->numMisspelledWords();
3808 SkipPositionsIterator it = skips.begin();
3809 SkipPositionsIterator et = skips.end();
3810 for (int index = 0; index < nerrors; ++index) {
3813 speller->misspelledWord(index, wstart, wlen);
3814 /// should not happen if speller supports range checks
3815 if (!wlen) continue;
3816 docstring const misspelled = word.substr(wstart, wlen);
3817 wstart += first + numskipped;
3818 if (snext < wstart) {
3819 /// mark the range of correct spelling
3820 numskipped += countSkips(it, et, wstart);
3821 setMisspelled(snext,
3822 wstart - 1, SpellChecker::WORD_OK);
3824 snext = wstart + wlen;
3825 numskipped += countSkips(it, et, snext);
3826 /// mark the range of misspelling
3827 setMisspelled(wstart, snext, result);
3828 LYXERR(Debug::GUI, "misspelled word: \"" <<
3829 misspelled << "\" [" <<
3830 wstart << ".." << (snext-1) << "]");
3833 if (snext <= last) {
3834 /// mark the range of correct spelling at end
3835 setMisspelled(snext, last, SpellChecker::WORD_OK);
3840 void Paragraph::spellCheck() const
3842 SpellChecker * speller = theSpellChecker();
3843 if (!speller || empty() ||!needsSpellCheck())
3847 d->rangeOfSpellCheck(start, endpos);
3848 if (speller->canCheckParagraph()) {
3849 // loop until we leave the range
3850 for (pos_type first = start; first < endpos; ) {
3851 pos_type last = endpos;
3852 Private::SkipPositions skips;
3853 Language * lang = d->locateSpellRange(first, last, skips);
3854 if (first >= endpos)
3856 // start the spell checker on the unit of meaning
3857 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
3858 WordLangTuple wl = WordLangTuple(word, lang);
3859 SpellChecker::Result result = word.size() ?
3860 speller->check(wl) : SpellChecker::WORD_OK;
3861 d->markMisspelledWords(first, last, result, word, skips);
3865 static docstring_list suggestions;
3866 pos_type to = endpos;
3867 while (start < endpos) {
3869 spellCheck(start, to, wl, suggestions, false);
3873 d->readySpellCheck();
3877 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
3879 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
3880 if (result || pos <= 0 || pos > size())
3882 if (check_boundary && (pos == size() || isWordSeparator(pos)))
3883 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
3888 string Paragraph::magicLabel() const
3891 ss << "magicparlabel-" << id();