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"
28 #include "BufferEncodings.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 "texstream.h"
44 #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"
55 #include "insets/InsetText.h"
57 #include "mathed/InsetMathHull.h"
59 #include "support/debug.h"
60 #include "support/docstring_list.h"
61 #include "support/ExceptionMessage.h"
62 #include "support/gettext.h"
63 #include "support/lassert.h"
64 #include "support/lstrings.h"
65 #include "support/textutils.h"
72 using namespace lyx::support;
74 // OSX clang, gcc < 4.8.0, and msvc < 2015 do not support C++11 thread_local
75 #if defined(__APPLE__) || (defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ < 8)
76 #define THREAD_LOCAL_STATIC static __thread
77 #elif defined(_MSC_VER) && (_MSC_VER < 1900)
78 #define THREAD_LOCAL_STATIC static __declspec(thread)
80 #define THREAD_LOCAL_STATIC thread_local static
87 /// Inset identifier (above 0x10ffff, for ucs-4)
88 char_type const META_INSET = 0x200001;
93 /////////////////////////////////////////////////////////////////////
97 /////////////////////////////////////////////////////////////////////
99 class SpellResultRange {
101 SpellResultRange(FontSpan range, SpellChecker::Result result)
102 : range_(range), result_(result)
105 FontSpan const & range() const { return range_; }
107 void range(FontSpan const & r) { range_ = r; }
109 SpellChecker::Result result() const { return result_; }
111 void result(SpellChecker::Result r) { result_ = r; }
113 bool contains(pos_type pos) const { return range_.contains(pos); }
115 bool covered(FontSpan const & r) const
117 // 1. first of new range inside current range or
118 // 2. last of new range inside current range or
119 // 3. first of current range inside new range or
120 // 4. last of current range inside new range
121 //FIXME: is this the same as !range_.intersect(r).empty() ?
122 return range_.contains(r.first) || range_.contains(r.last) ||
123 r.contains(range_.first) || r.contains(range_.last);
126 void shift(pos_type pos, int offset)
128 if (range_.first > pos) {
129 range_.first += offset;
130 range_.last += offset;
131 } else if (range_.last >= pos) {
132 range_.last += offset;
137 SpellChecker::Result result_ ;
141 /////////////////////////////////////////////////////////////////////
145 /////////////////////////////////////////////////////////////////////
147 class SpellCheckerState {
151 needs_refresh_ = true;
152 current_change_number_ = 0;
155 void setRange(FontSpan const & fp, SpellChecker::Result state)
158 RangesIterator et = ranges_.end();
159 RangesIterator it = ranges_.begin();
160 for (; it != et; ++it) {
161 if (!it->covered(fp))
162 result.push_back(SpellResultRange(it->range(), it->result()));
163 else if (state == SpellChecker::WORD_OK) {
164 // trim or split the current misspelled range
165 // store misspelled ranges only
166 FontSpan range = it->range();
167 if (fp.first > range.first) {
168 // misspelled area in front of WORD_OK
169 range.last = fp.first - 1;
170 result.push_back(SpellResultRange(range, it->result()));
173 if (fp.last < range.last) {
174 // misspelled area after WORD_OK range
175 range.first = fp.last + 1;
176 result.push_back(SpellResultRange(range, it->result()));
181 if (state != SpellChecker::WORD_OK)
182 ranges_.push_back(SpellResultRange(fp, state));
185 void increasePosAfterPos(pos_type pos)
187 correctRangesAfterPos(pos, 1);
191 void decreasePosAfterPos(pos_type pos)
193 correctRangesAfterPos(pos, -1);
197 void refreshLast(pos_type pos)
199 if (pos < refresh_.last)
203 SpellChecker::Result getState(pos_type pos) const
205 SpellChecker::Result result = SpellChecker::WORD_OK;
206 RangesIterator et = ranges_.end();
207 RangesIterator it = ranges_.begin();
208 for (; it != et; ++it) {
209 if(it->contains(pos)) {
216 FontSpan const & getRange(pos_type pos) const
218 /// empty span to indicate mismatch
219 static FontSpan empty_;
220 RangesIterator et = ranges_.end();
221 RangesIterator it = ranges_.begin();
222 for (; it != et; ++it) {
223 if(it->contains(pos)) {
230 bool needsRefresh() const
232 return needs_refresh_;
235 SpellChecker::ChangeNumber currentChangeNumber() const
237 return current_change_number_;
240 void refreshRange(pos_type & first, pos_type & last) const
242 first = refresh_.first;
243 last = refresh_.last;
246 void needsRefresh(pos_type pos)
248 if (needs_refresh_ && pos != -1) {
249 if (pos < refresh_.first)
250 refresh_.first = pos;
251 if (pos > refresh_.last)
253 } else if (pos != -1) {
254 // init request check for neighbour positions too
255 refresh_.first = pos > 0 ? pos - 1 : 0;
256 // no need for special end of paragraph check
257 refresh_.last = pos + 1;
259 needs_refresh_ = pos != -1;
262 void needsCompleteRefresh(SpellChecker::ChangeNumber change_number)
264 needs_refresh_ = true;
267 current_change_number_ = change_number;
270 typedef vector<SpellResultRange> Ranges;
271 typedef Ranges::const_iterator RangesIterator;
273 /// the area of the paragraph with pending spell check
276 /// spell state cache version number
277 SpellChecker::ChangeNumber current_change_number_;
280 void correctRangesAfterPos(pos_type pos, int offset)
282 RangesIterator et = ranges_.end();
283 Ranges::iterator it = ranges_.begin();
284 for (; it != et; ++it) {
285 it->shift(pos, offset);
291 /////////////////////////////////////////////////////////////////////
293 // Paragraph::Private
295 /////////////////////////////////////////////////////////////////////
297 class Paragraph::Private
299 // Enforce our own "copy" constructor
300 Private(Private const &) = delete;
301 Private & operator=(Private const &) = delete;
302 // Unique ID generator
303 static int make_id();
306 Private(Paragraph * owner, Layout const & layout);
307 /// "Copy constructor"
308 Private(Private const &, Paragraph * owner);
309 /// Copy constructor from \p beg to \p end
310 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
313 void insertChar(pos_type pos, char_type c, Change const & change);
315 /// Output the surrogate pair formed by \p c and \p next to \p os.
316 /// \return the number of characters written.
317 int latexSurrogatePair(BufferParams const &, otexstream & os,
318 char_type c, char_type next,
319 OutputParams const &);
321 /// Output a space in appropriate formatting (or a surrogate pair
322 /// if the next character is a combining character).
323 /// \return whether a surrogate pair was output.
324 bool simpleTeXBlanks(BufferParams const &,
325 OutputParams const &,
328 unsigned int & column,
330 Layout const & style);
332 /// This could go to ParagraphParameters if we want to.
333 int startTeXParParams(BufferParams const &, otexstream &,
334 OutputParams const &) const;
336 /// This could go to ParagraphParameters if we want to.
337 bool endTeXParParams(BufferParams const &, otexstream &,
338 OutputParams const &) const;
341 void latexInset(BufferParams const &,
346 Font const & outerfont,
348 Change & running_change,
349 Layout const & style,
351 unsigned int & column);
354 void latexSpecialChar(
356 BufferParams const & bparams,
357 OutputParams const & runparams,
358 Font const & running_font,
359 string & alien_script,
360 Layout const & style,
363 unsigned int & column);
370 unsigned int & column);
376 unsigned int & column);
382 unsigned int & column);
385 void validate(LaTeXFeatures & features) const;
387 /// Checks if the paragraph contains only text and no inset or font change.
388 bool onlyText(Buffer const & buf, Font const & outerfont,
389 pos_type initial) const;
391 /// a vector of speller skip positions
392 typedef vector<FontSpan> SkipPositions;
393 typedef SkipPositions::const_iterator SkipPositionsIterator;
395 void appendSkipPosition(SkipPositions & skips, pos_type const pos) const;
397 Language * getSpellLanguage(pos_type const from) const;
399 Language * locateSpellRange(pos_type & from, pos_type & to,
400 SkipPositions & skips) const;
402 bool hasSpellerChange() const
404 SpellChecker::ChangeNumber speller_change_number = 0;
405 if (theSpellChecker())
406 speller_change_number = theSpellChecker()->changeNumber();
407 return speller_change_number > speller_state_.currentChangeNumber();
410 bool ignoreWord(docstring const & word) const ;
412 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
414 pos_type textsize = owner_->size();
415 // check for sane arguments
416 if (to <= from || from >= textsize)
418 FontSpan fp = FontSpan(from, to - 1);
419 speller_state_.setRange(fp, state);
422 void requestSpellCheck(pos_type pos)
425 speller_state_.needsCompleteRefresh(speller_state_.currentChangeNumber());
427 speller_state_.needsRefresh(pos);
430 void readySpellCheck()
432 speller_state_.needsRefresh(-1);
435 bool needsSpellCheck() const
437 return speller_state_.needsRefresh();
440 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
442 speller_state_.refreshRange(first, last);
444 last = owner_->size();
447 pos_type endpos = last;
448 owner_->locateWord(first, endpos, WHOLE_WORD);
451 owner_->locateWord(last, endpos, WHOLE_WORD);
456 int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
460 while (it != et && it->first < start) {
461 int skip = it->last - it->first + 1;
469 void markMisspelledWords(pos_type const & first, pos_type const & last,
470 SpellChecker::Result result,
471 docstring const & word,
472 SkipPositions const & skips);
474 InsetCode ownerCode() const
476 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
479 /// Which Paragraph owns us?
483 Inset const * inset_owner_;
492 ParagraphParameters params_;
494 /// for recording and looking up changes
498 InsetList insetlist_;
501 pos_type begin_of_body_;
503 typedef docstring TextContainer;
507 typedef set<docstring> Words;
508 typedef map<string, Words> LangWordsMap;
512 Layout const * layout_;
514 SpellCheckerState speller_state_;
518 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
519 : owner_(owner), inset_owner_(0), id_(-1), begin_of_body_(0), layout_(&layout)
526 int Paragraph::Private::make_id()
528 // The id is unique per session across buffers because it is used in
529 // LFUN_PARAGRAPH_GOTO to switch to a different buffer, for instance in the
532 static atomic_uint next_id(0);
537 Paragraph::Private::Private(Private const & p, Paragraph * owner)
538 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
540 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
541 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
544 requestSpellCheck(p.text_.size());
548 Paragraph::Private::Private(Private const & p, Paragraph * owner,
549 pos_type beg, pos_type end)
550 : owner_(owner), inset_owner_(p.inset_owner_), id_(make_id()),
551 params_(p.params_), changes_(p.changes_),
552 insetlist_(p.insetlist_, beg, end),
553 begin_of_body_(p.begin_of_body_), words_(p.words_),
556 if (beg >= pos_type(p.text_.size()))
558 text_ = p.text_.substr(beg, end - beg);
560 FontList::const_iterator fcit = fontlist_.begin();
561 FontList::const_iterator fend = fontlist_.end();
562 for (; fcit != fend; ++fcit) {
563 if (fcit->pos() < beg)
565 if (fcit->pos() >= end) {
566 // Add last entry in the fontlist_.
567 fontlist_.set(text_.size() - 1, fcit->font());
570 // Add a new entry in the fontlist_.
571 fontlist_.set(fcit->pos() - beg, fcit->font());
573 requestSpellCheck(p.text_.size());
577 void Paragraph::addChangesToToc(DocIterator const & cdit, Buffer const & buf,
578 bool output_active, TocBackend & backend) const
580 d->changes_.addToToc(cdit, buf, output_active, backend);
584 void Paragraph::addChangesToBuffer(Buffer const & buf) const
586 d->changes_.updateBuffer(buf);
590 bool Paragraph::isChangeUpdateRequired() const
592 return d->changes_.isUpdateRequired();
596 bool Paragraph::isDeleted(pos_type start, pos_type end) const
598 LASSERT(start >= 0 && start <= size(), return false);
599 LASSERT(end > start && end <= size() + 1, return false);
601 return d->changes_.isDeleted(start, end);
605 bool Paragraph::isChanged(pos_type start, pos_type end) const
607 LASSERT(start >= 0 && start <= size(), return false);
608 LASSERT(end > start && end <= size() + 1, return false);
610 return d->changes_.isChanged(start, end);
614 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
616 // keep the logic here in sync with the logic of eraseChars()
620 Change const & change = d->changes_.lookup(size());
621 return change.inserted() && change.currentAuthor();
625 void Paragraph::setChange(Change const & change)
627 // beware of the imaginary end-of-par character!
628 d->changes_.set(change, 0, size() + 1);
631 * Propagate the change recursively - but not in case of DELETED!
633 * Imagine that your co-author makes changes in an existing inset. He
634 * sends your document to you and you come to the conclusion that the
635 * inset should go completely. If you erase it, LyX must not delete all
636 * text within the inset. Otherwise, the change tracked insertions of
637 * your co-author get lost and there is no way to restore them later.
639 * Conclusion: An inset's content should remain untouched if you delete it
642 if (!change.deleted()) {
643 for (pos_type pos = 0; pos < size(); ++pos) {
644 if (Inset * inset = getInset(pos))
645 inset->setChange(change);
651 void Paragraph::setChange(pos_type pos, Change const & change)
653 LASSERT(pos >= 0 && pos <= size(), return);
654 d->changes_.set(change, pos);
656 // see comment in setChange(Change const &) above
657 if (!change.deleted() && pos < size())
658 if (Inset * inset = getInset(pos))
659 inset->setChange(change);
663 Change const & Paragraph::lookupChange(pos_type pos) const
665 LBUFERR(pos >= 0 && pos <= size());
666 return d->changes_.lookup(pos);
670 void Paragraph::acceptChanges(pos_type start, pos_type end)
672 LASSERT(start >= 0 && start <= size(), return);
673 LASSERT(end > start && end <= size() + 1, return);
675 for (pos_type pos = start; pos < end; ++pos) {
676 switch (lookupChange(pos).type) {
677 case Change::UNCHANGED:
678 // accept changes in nested inset
679 if (Inset * inset = getInset(pos))
680 inset->acceptChanges();
683 case Change::INSERTED:
684 d->changes_.set(Change(Change::UNCHANGED), pos);
685 // also accept changes in nested inset
686 if (Inset * inset = getInset(pos))
687 inset->acceptChanges();
690 case Change::DELETED:
691 // Suppress access to non-existent
692 // "end-of-paragraph char"
694 eraseChar(pos, false);
705 void Paragraph::rejectChanges(pos_type start, pos_type end)
707 LASSERT(start >= 0 && start <= size(), return);
708 LASSERT(end > start && end <= size() + 1, return);
710 for (pos_type pos = start; pos < end; ++pos) {
711 switch (lookupChange(pos).type) {
712 case Change::UNCHANGED:
713 // reject changes in nested inset
714 if (Inset * inset = getInset(pos))
715 inset->rejectChanges();
718 case Change::INSERTED:
719 // Suppress access to non-existent
720 // "end-of-paragraph char"
722 eraseChar(pos, false);
728 case Change::DELETED:
729 d->changes_.set(Change(Change::UNCHANGED), pos);
731 // Do NOT reject changes within a deleted inset!
732 // There may be insertions of a co-author inside of it!
740 void Paragraph::Private::insertChar(pos_type pos, char_type c,
741 Change const & change)
743 LASSERT(pos >= 0 && pos <= int(text_.size()), return);
746 changes_.insert(change, pos);
748 // This is actually very common when parsing buffers (and
749 // maybe inserting ascii text)
750 if (pos == pos_type(text_.size())) {
751 // when appending characters, no need to update tables
753 // but we want spell checking
754 requestSpellCheck(pos);
758 text_.insert(text_.begin() + pos, c);
760 // Update the font table.
761 fontlist_.increasePosAfterPos(pos);
764 insetlist_.increasePosAfterPos(pos);
766 // Update list of misspelled positions
767 speller_state_.increasePosAfterPos(pos);
771 bool Paragraph::insertInset(pos_type pos, Inset * inset,
772 Font const & font, Change const & change)
774 LASSERT(inset, return false);
775 LASSERT(pos >= 0 && pos <= size(), return false);
777 // Paragraph::insertInset() can be used in cut/copy/paste operation where
778 // d->inset_owner_ is not set yet.
779 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
782 d->insertChar(pos, META_INSET, change);
783 LASSERT(d->text_[pos] == META_INSET, return false);
785 // Add a new entry in the insetlist_.
786 d->insetlist_.insert(inset, pos);
788 // Some insets require run of spell checker
789 requestSpellCheck(pos);
795 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
797 LASSERT(pos >= 0 && pos <= size(), return false);
799 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
802 Change change = d->changes_.lookup(pos);
804 // set the character to DELETED if
805 // a) it was previously unchanged or
806 // b) it was inserted by a co-author
808 if (!change.changed() ||
809 (change.inserted() && !change.currentAuthor())) {
810 setChange(pos, Change(Change::DELETED));
811 // request run of spell checker
812 requestSpellCheck(pos);
816 if (change.deleted())
820 // Don't physically access the imaginary end-of-paragraph character.
821 // eraseChar() can only mark it as DELETED. A physical deletion of
822 // end-of-par must be handled externally.
828 d->changes_.erase(pos);
830 // if it is an inset, delete the inset entry
831 if (d->text_[pos] == META_INSET)
832 d->insetlist_.erase(pos);
834 d->text_.erase(d->text_.begin() + pos);
836 // Update the fontlist_
837 d->fontlist_.erase(pos);
839 // Update the insetlist_
840 d->insetlist_.decreasePosAfterPos(pos);
842 // Update list of misspelled positions
843 d->speller_state_.decreasePosAfterPos(pos);
844 d->speller_state_.refreshLast(size());
850 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
852 LASSERT(start >= 0 && start <= size(), return 0);
853 LASSERT(end >= start && end <= size() + 1, return 0);
856 for (pos_type count = end - start; count; --count) {
857 if (!eraseChar(i, trackChanges))
863 // Handle combining characters
864 int Paragraph::Private::latexSurrogatePair(BufferParams const & bparams,
865 otexstream & os, char_type c, char_type next,
866 OutputParams const & runparams)
868 // Writing next here may circumvent a possible font change between
869 // c and next. Since next is only output if it forms a surrogate pair
870 // with c we can ignore this:
871 // A font change inside a surrogate pair does not make sense and is
872 // hopefully impossible to input.
873 // FIXME: change tracking
874 // Is this correct WRT change tracking?
875 Encoding const & encoding = *(runparams.encoding);
876 docstring latex1 = encoding.latexChar(next).first;
877 if (runparams.inIPA) {
878 string const tipashortcut = Encodings::TIPAShortcut(next);
879 if (!tipashortcut.empty()) {
880 latex1 = from_ascii(tipashortcut);
883 docstring latex2 = encoding.latexChar(c).first;
885 if (bparams.useNonTeXFonts || docstring(1, next) == latex1) {
886 // Encoding supports the combination:
887 // output as is (combining char after base char).
888 os << latex2 << latex1;
889 return latex1.length() + latex2.length();
892 os << latex1 << "{" << latex2 << "}";
893 return latex1.length() + latex2.length() + 2;
897 bool Paragraph::Private::simpleTeXBlanks(BufferParams const & bparams,
898 OutputParams const & runparams,
901 unsigned int & column,
903 Layout const & style)
905 if (style.pass_thru || runparams.pass_thru)
908 if (i + 1 < int(text_.size())) {
909 char_type next = text_[i + 1];
910 if (Encodings::isCombiningChar(next)) {
911 // This space has an accent, so we must always output it.
912 column += latexSurrogatePair(bparams, os, ' ', next, runparams) - 1;
917 if (runparams.linelen > 0
918 && column > runparams.linelen
920 && text_[i - 1] != ' '
921 && (i + 1 < int(text_.size()))
922 // same in FreeSpacing mode
923 && !owner_->isFreeSpacing()
924 // In typewriter mode, we want to avoid
925 // ! . ? : at the end of a line
926 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
927 && (text_[i - 1] == '.'
928 || text_[i - 1] == '?'
929 || text_[i - 1] == ':'
930 || text_[i - 1] == '!'))) {
932 os.texrow().start(owner_->id(), i + 1);
934 } else if (style.free_spacing) {
943 void Paragraph::Private::latexInset(BufferParams const & bparams,
945 OutputParams & runparams,
948 Font const & outerfont,
950 Change & running_change,
951 Layout const & style,
953 unsigned int & column)
955 Inset * inset = owner_->getInset(i);
958 if (style.pass_thru) {
959 odocstringstream ods;
960 inset->plaintext(ods, runparams);
965 // FIXME: move this to InsetNewline::latex
966 if (inset->lyxCode() == NEWLINE_CODE || inset->lyxCode() == SEPARATOR_CODE) {
967 // newlines are handled differently here than
968 // the default in simpleTeXSpecialChars().
969 if (!style.newline_allowed) {
973 bool needPar = false;
974 column += running_font.latexWriteEndChanges(
975 os, bparams, runparams,
976 basefont, basefont, needPar);
980 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
983 basefont = owner_->getLayoutFont(bparams, outerfont);
984 running_font = basefont;
986 if (runparams.moving_arg)
990 os.texrow().start(owner_->id(), i + 1);
994 if (owner_->isDeleted(i)) {
995 if( ++runparams.inDeletedInset == 1)
996 runparams.changeOfDeletedInset = owner_->lookupChange(i);
999 if (inset->canTrackChanges()) {
1000 column += Changes::latexMarkChange(os, bparams, running_change,
1001 Change(Change::UNCHANGED), runparams);
1002 running_change = Change(Change::UNCHANGED);
1006 odocstream::pos_type const len = os.os().tellp();
1008 if (inset->forceLTR()
1009 && running_font.isRightToLeft()
1010 // ERT is an exception, it should be output with no
1011 // decorations at all
1012 && inset->lyxCode() != ERT_CODE) {
1013 if (runparams.use_polyglossia) {
1015 } else if (running_font.language()->lang() == "farsi"
1016 || running_font.language()->lang() == "arabic_arabi")
1017 os << "\\textLR{" << termcmd;
1023 // FIXME: Bug: we can have an empty font change here!
1024 // if there has just been a font change, we are going to close it
1025 // right now, which means stupid latex code like \textsf{}. AFAIK,
1026 // this does not harm dvi output. A minor bug, thus (JMarc)
1028 // Some insets cannot be inside a font change command.
1029 // However, even such insets *can* be placed in \L or \R
1030 // or their equivalents (for RTL language switches), so we don't
1031 // close the language in those cases.
1032 // ArabTeX, though, cannot handle this special behavior, it seems.
1033 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
1034 || running_font.language()->lang() == "arabic_arabtex";
1035 if (open_font && !inset->inheritFont()) {
1036 bool needPar = false;
1037 bool closeLanguage = arabtex
1038 || basefont.isRightToLeft() == running_font.isRightToLeft();
1039 unsigned int count = running_font.latexWriteEndChanges(os,
1040 bparams, runparams, basefont, basefont,
1041 needPar, closeLanguage);
1043 // if any font properties were closed, update the running_font,
1044 // making sure, however, to leave the language as it was
1046 // FIXME: probably a better way to keep track of the old
1047 // language, than copying the entire font?
1048 Font const copy_font(running_font);
1049 basefont = owner_->getLayoutFont(bparams, outerfont);
1050 running_font = basefont;
1052 running_font.setLanguage(copy_font.language());
1053 // leave font open if language is still open
1054 open_font = (running_font.language() == basefont.language());
1056 runparams.local_font = &basefont;
1060 size_t const previous_row_count = os.texrow().rows();
1063 runparams.lastid = id_;
1064 runparams.lastpos = i;
1065 inset->latex(os, runparams);
1066 } catch (EncodingException & e) {
1067 // add location information and throw again.
1076 if (os.texrow().rows() > previous_row_count) {
1077 os.texrow().start(owner_->id(), i + 1);
1080 column += (unsigned int)(os.os().tellp() - len);
1083 if (owner_->isDeleted(i))
1084 --runparams.inDeletedInset;
1088 void Paragraph::Private::latexSpecialChar(otexstream & os,
1089 BufferParams const & bparams,
1090 OutputParams const & runparams,
1091 Font const & running_font,
1092 string & alien_script,
1093 Layout const & style,
1096 unsigned int & column)
1098 char_type const c = owner_->getUChar(bparams, runparams, i);
1100 if (style.pass_thru || runparams.pass_thru
1101 || contains(style.pass_thru_chars, c)
1102 || contains(runparams.pass_thru_chars, c)) {
1104 Encoding const * const enc = runparams.encoding;
1105 if (enc && !enc->encodable(c))
1106 throw EncodingException(c);
1112 // TIPA uses its own T3 encoding
1113 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1115 // If T1 font encoding is used, use the special
1116 // characters it provides.
1117 // NOTE: Some languages reset the font encoding internally to a
1118 // non-standard font encoding. If we are using such a language,
1119 // we do not output special T1 chars.
1120 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1121 && !runparams.isFullUnicode() && bparams.main_font_encoding() == "T1"
1122 && latexSpecialT1(c, os, i, column))
1124 // NOTE: "fontspec" (non-TeX fonts) sets the font encoding to "TU" (untill 2017 "EU1" or "EU2")
1125 else if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1126 && runparams.isFullUnicode() && latexSpecialTU(c, os, i, column))
1129 // Otherwise, we use what LaTeX provides us.
1132 os << "\\textbackslash" << termcmd;
1136 os << "\\textless" << termcmd;
1140 os << "\\textgreater" << termcmd;
1144 os << "\\textbar" << termcmd;
1149 if (i + 1 < static_cast<pos_type>(text_.size()) &&
1150 (end_pos == -1 || i + 1 < end_pos) &&
1151 text_[i+1] == '-') {
1152 // Prevent "--" becoming an en dash and "---" an em dash.
1153 // (Within \ttfamily, "---" is merged to en dash + hyphen.)
1159 os << "\\textquotedbl" << termcmd;
1164 case '%': case '#': case '{':
1172 os << "\\textasciitilde" << termcmd;
1177 os << "\\textasciicircum" << termcmd;
1184 // avoid being mistaken for optional arguments
1192 // Blanks are printed before font switching.
1193 // Sure? I am not! (try nice-latex)
1194 // I am sure it's correct. LyX might be smarter
1195 // in the future, but for now, nothing wrong is
1201 // XeTeX's dash behaviour is determined via a global setting
1202 if (bparams.use_dash_ligatures
1203 && owner_->getFontSettings(bparams, i).fontInfo().family() != TYPEWRITER_FAMILY
1205 // TODO #10961: && not in inset Flex Code
1206 // TODO #10961: && not in layout LyXCode
1207 && (!bparams.useNonTeXFonts || runparams.flavor != OutputParams::XETEX)) {
1224 Encoding const & encoding = *(runparams.encoding);
1225 char_type next = '\0';
1226 if (i + 1 < int(text_.size())) {
1227 next = text_[i + 1];
1228 if (Encodings::isCombiningChar(next)) {
1229 column += latexSurrogatePair(bparams, os, c, next, runparams) - 1;
1234 pair<docstring, bool> latex = encoding.latexChar(c);
1235 docstring nextlatex;
1236 bool nexttipas = false;
1237 string nexttipashortcut;
1238 if (next != '\0' && next != META_INSET && !encoding.encodable(next)) {
1239 nextlatex = encoding.latexChar(next).first;
1240 if (runparams.inIPA) {
1241 nexttipashortcut = Encodings::TIPAShortcut(next);
1242 nexttipas = !nexttipashortcut.empty();
1246 if (runparams.inIPA) {
1247 string const tipashortcut = Encodings::TIPAShortcut(c);
1248 if (!tipashortcut.empty()) {
1249 latex.first = from_ascii(tipashortcut);
1250 latex.second = false;
1254 // eventually close "script wrapper" command (see `Paragraph::latex`)
1255 if (!alien_script.empty()
1256 && alien_script != Encodings::isKnownScriptChar(next)) {
1257 column += latex.first.length();
1258 alien_script.clear();
1259 os << latex.first << "}";
1263 && ((!prefixIs(nextlatex, '\\')
1264 && !prefixIs(nextlatex, '{')
1265 && !prefixIs(nextlatex, '}'))
1267 && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1269 // Prevent eating of a following space or command corruption by
1270 // following characters
1271 if (next == ' ' || next == '\0') {
1272 column += latex.first.length() + 1;
1273 os << latex.first << "{}";
1275 column += latex.first.length();
1276 os << latex.first << " ";
1279 column += latex.first.length() - 1;
1287 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1288 pos_type i, unsigned int & column)
1294 // In T1 encoding, these characters exist
1295 // but we should avoid ligatures
1296 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1298 os << "\\textcompwordmark" << termcmd;
1305 // soul.sty breaks with \char`\"
1306 os << "\\textquotedbl" << termcmd;
1315 bool Paragraph::Private::latexSpecialTU(char_type const c, otexstream & os,
1316 pos_type i, unsigned int & column)
1318 // TU encoding is currently on par with T1.
1319 return latexSpecialT1(c, os, i, column);
1323 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1324 pos_type /*i*/, unsigned int & column)
1334 os << "\\textvertline" << termcmd;
1343 void Paragraph::Private::validate(LaTeXFeatures & features) const
1345 if (layout_->inpreamble && inset_owner_) {
1346 // FIXME: Using a string stream here circumvents the encoding
1347 // switching machinery of odocstream. Therefore the
1348 // output is wrong if this paragraph contains content
1349 // that needs to switch encoding.
1350 Buffer const & buf = inset_owner_->buffer();
1351 otexstringstream os;
1352 os << layout_->preamble();
1353 size_t const length = os.length();
1354 TeXOnePar(buf, *inset_owner_->getText(int(buf.getParFromID(owner_->id()).idx())),
1355 buf.getParFromID(owner_->id()).pit(), os,
1356 features.runparams(), string(), 0, -1, true);
1357 if (os.length() > length)
1358 features.addPreambleSnippet(os.release(), true);
1361 if (features.runparams().flavor == OutputParams::HTML
1362 && layout_->htmltitle()) {
1363 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1366 // check the params.
1367 if (!params_.spacing().isDefault())
1368 features.require("setspace");
1371 features.useLayout(layout_->name());
1374 fontlist_.validate(features);
1376 // then the indentation
1377 if (!params_.leftIndent().zero())
1378 features.require("ParagraphLeftIndent");
1381 InsetList::const_iterator icit = insetlist_.begin();
1382 InsetList::const_iterator iend = insetlist_.end();
1383 for (; icit != iend; ++icit) {
1385 features.inDeletedInset(owner_->isDeleted(icit->pos));
1386 if (icit->inset->lyxCode() == FOOT_CODE) {
1387 // FIXME: an item inset would make things much easier.
1388 if ((layout_->latextype == LATEX_LIST_ENVIRONMENT
1389 || (layout_->latextype == LATEX_ITEM_ENVIRONMENT
1390 && layout_->margintype == MARGIN_FIRST_DYNAMIC))
1391 && (icit->pos < begin_of_body_
1392 || (icit->pos == begin_of_body_
1393 && (icit->pos == 0 || text_[icit->pos - 1] != ' '))))
1394 features.saveNoteEnv("description");
1396 icit->inset->validate(features);
1397 features.inDeletedInset(false);
1398 if (layout_->needprotect &&
1399 icit->inset->lyxCode() == FOOT_CODE)
1400 features.require("NeedLyXFootnoteCode");
1404 // then the contents
1405 BufferParams const bp = features.runparams().is_child
1406 ? features.buffer().masterParams() : features.buffer().params();
1407 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1408 char_type c = text_[i];
1409 CharInfo const & ci = Encodings::unicodeCharInfo(c);
1411 if (features.runparams().isFullUnicode() && bp.useNonTeXFonts)
1412 features.require("textquotedblp");
1413 else if (bp.main_font_encoding() != "T1"
1414 || ((&owner_->getFontSettings(bp, i))->language()->internalFontEncoding()))
1415 features.require("textquotedbl");
1416 } else if (ci.textfeature() && contains(ci.textpreamble(), '=')) {
1417 // features that depend on the font or input encoding
1418 string feats = ci.textpreamble();
1419 string fontenc = (&owner_->getFontSettings(bp, i))->language()->fontenc(bp);
1420 if (fontenc.empty())
1421 fontenc = features.runparams().main_fontenc;
1422 while (!feats.empty()) {
1424 feats = split(feats, feat, ',');
1425 if (contains(feat, "!=")) {
1426 // a feature that is required except for the spcified
1427 // font or input encodings
1429 string const contexts = ltrim(split(feat, realfeature, '!'), "=");
1430 // multiple encodings are separated by semicolon
1431 vector<string> context = getVectorFromString(contexts, ";");
1432 // require feature if the context matches neither current font
1433 // nor input encoding
1434 if (std::find(context.begin(), context.end(), fontenc) == context.end()
1435 && std::find(context.begin(), context.end(),
1436 features.runparams().encoding->name()) == context.end())
1437 features.require(realfeature);
1438 } else if (contains(feat, '=')) {
1439 // a feature that is required only for the spcified
1440 // font or input encodings
1442 string const contexts = split(feat, realfeature, '=');
1443 // multiple encodings are separated by semicolon
1444 vector<string> context = getVectorFromString(contexts, ";");
1445 // require feature if the context matches either current font
1446 // or input encoding
1447 if (std::find(context.begin(), context.end(), fontenc) != context.end()
1448 || std::find(context.begin(), context.end(),
1449 features.runparams().encoding->name()) != context.end())
1450 features.require(realfeature);
1453 } else if (!bp.use_dash_ligatures
1454 && (c == 0x2013 || c == 0x2014)
1455 && bp.useNonTeXFonts
1456 && features.runparams().flavor == OutputParams::XETEX)
1457 // XeTeX's dash behaviour is determined via a global setting
1458 features.require("xetexdashbreakstate");
1459 BufferEncodings::validate(c, features);
1463 /////////////////////////////////////////////////////////////////////
1467 /////////////////////////////////////////////////////////////////////
1470 Layout const emptyParagraphLayout;
1473 Paragraph::Paragraph()
1474 : d(new Paragraph::Private(this, emptyParagraphLayout))
1481 Paragraph::Paragraph(Paragraph const & par)
1482 : itemdepth(par.itemdepth),
1483 d(new Paragraph::Private(*par.d, this))
1489 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1490 : itemdepth(par.itemdepth),
1491 d(new Paragraph::Private(*par.d, this, beg, end))
1497 Paragraph & Paragraph::operator=(Paragraph const & par)
1499 // needed as we will destroy the private part before copying it
1501 itemdepth = par.itemdepth;
1505 d = new Private(*par.d, this);
1512 Paragraph::~Paragraph()
1521 // this shall be called just before every "os << ..." action.
1522 void flushString(ostream & os, docstring & s)
1531 void Paragraph::write(ostream & os, BufferParams const & bparams,
1532 depth_type & dth) const
1534 // The beginning or end of a deeper (i.e. nested) area?
1535 if (dth != d->params_.depth()) {
1536 if (d->params_.depth() > dth) {
1537 while (d->params_.depth() > dth) {
1538 os << "\n\\begin_deeper";
1542 while (d->params_.depth() < dth) {
1543 os << "\n\\end_deeper";
1549 // First write the layout
1550 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1552 d->params_.write(os);
1554 Font font1(inherit_font, bparams.language);
1556 Change running_change = Change(Change::UNCHANGED);
1558 // this string is used as a buffer to avoid repetitive calls
1559 // to to_utf8(), which turn out to be expensive (JMarc)
1560 docstring write_buffer;
1563 for (pos_type i = 0; i <= size(); ++i) {
1565 Change const & change = lookupChange(i);
1566 if (change != running_change)
1567 flushString(os, write_buffer);
1568 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1569 running_change = change;
1574 // Write font changes
1575 Font font2 = getFontSettings(bparams, i);
1576 if (font2 != font1) {
1577 flushString(os, write_buffer);
1578 font2.lyxWriteChanges(font1, os);
1583 char_type const c = d->text_[i];
1586 if (Inset const * inset = getInset(i)) {
1587 flushString(os, write_buffer);
1588 if (inset->directWrite()) {
1589 // international char, let it write
1590 // code directly so it's shorter in
1596 os << "\\begin_inset ";
1598 os << "\n\\end_inset\n\n";
1601 // FIXME This can be removed again once the mystery
1602 // crash has been resolved.
1607 flushString(os, write_buffer);
1608 os << "\n\\backslash\n";
1612 flushString(os, write_buffer);
1613 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1620 if ((column > 70 && c == ' ')
1622 flushString(os, write_buffer);
1626 // this check is to amend a bug. LyX sometimes
1627 // inserts '\0' this could cause problems.
1629 write_buffer.push_back(c);
1631 LYXERR0("NUL char in structure.");
1637 flushString(os, write_buffer);
1638 os << "\n\\end_layout\n";
1639 // FIXME This can be removed again once the mystery
1640 // crash has been resolved.
1645 void Paragraph::validate(LaTeXFeatures & features) const
1647 d->validate(features);
1648 bool fragile = features.runparams().moving_arg;
1649 fragile |= layout().needprotect;
1650 if (inInset().getLayout().isNeedProtect())
1652 if (needsCProtection(fragile))
1653 features.require("cprotect");
1657 void Paragraph::insert(pos_type start, docstring const & str,
1658 Font const & font, Change const & change)
1660 for (size_t i = 0, n = str.size(); i != n ; ++i)
1661 insertChar(start + i, str[i], font, change);
1665 void Paragraph::appendChar(char_type c, Font const & font,
1666 Change const & change)
1669 d->changes_.insert(change, d->text_.size());
1670 // when appending characters, no need to update tables
1671 d->text_.push_back(c);
1672 setFont(d->text_.size() - 1, font);
1673 d->requestSpellCheck(d->text_.size() - 1);
1677 void Paragraph::appendString(docstring const & s, Font const & font,
1678 Change const & change)
1680 pos_type end = s.size();
1681 size_t oldsize = d->text_.size();
1682 size_t newsize = oldsize + end;
1683 size_t capacity = d->text_.capacity();
1684 if (newsize >= capacity)
1685 d->text_.reserve(max(capacity + 100, newsize));
1687 // when appending characters, no need to update tables
1690 // FIXME: Optimize this!
1691 for (size_t i = oldsize; i != newsize; ++i) {
1693 d->changes_.insert(change, i);
1694 d->requestSpellCheck(i);
1696 d->fontlist_.set(oldsize, font);
1697 d->fontlist_.set(newsize - 1, font);
1701 void Paragraph::insertChar(pos_type pos, char_type c,
1704 d->insertChar(pos, c, Change(trackChanges ?
1705 Change::INSERTED : Change::UNCHANGED));
1709 void Paragraph::insertChar(pos_type pos, char_type c,
1710 Font const & font, bool trackChanges)
1712 d->insertChar(pos, c, Change(trackChanges ?
1713 Change::INSERTED : Change::UNCHANGED));
1718 void Paragraph::insertChar(pos_type pos, char_type c,
1719 Font const & font, Change const & change)
1721 d->insertChar(pos, c, change);
1726 void Paragraph::resetFonts(Font const & font)
1728 d->fontlist_.clear();
1729 d->fontlist_.set(0, font);
1730 d->fontlist_.set(d->text_.size() - 1, font);
1733 // Gets uninstantiated font setting at position.
1734 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1738 LYXERR0("pos: " << pos << " size: " << size());
1742 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1743 if (cit != d->fontlist_.end())
1746 if (pos == size() && !empty())
1747 return getFontSettings(bparams, pos - 1);
1749 // Optimisation: avoid a full font instantiation if there is no
1750 // language change from previous call.
1751 static Font previous_font;
1752 static Language const * previous_lang = 0;
1753 Language const * lang = getParLanguage(bparams);
1754 if (lang != previous_lang) {
1755 previous_lang = lang;
1756 previous_font = Font(inherit_font, lang);
1758 return previous_font;
1762 FontSpan Paragraph::fontSpan(pos_type pos) const
1764 LBUFERR(pos <= size());
1767 return FontSpan(pos, pos);
1770 FontList::const_iterator cit = d->fontlist_.begin();
1771 FontList::const_iterator end = d->fontlist_.end();
1772 for (; cit != end; ++cit) {
1773 if (cit->pos() >= pos) {
1774 if (pos >= beginOfBody())
1775 return FontSpan(max(start, beginOfBody()),
1778 return FontSpan(start,
1779 min(beginOfBody() - 1,
1782 start = cit->pos() + 1;
1785 // This should not happen, but if so, we take no chances.
1786 LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1787 LASSERT(false, return FontSpan(pos, pos));
1791 // Gets uninstantiated font setting at position 0
1792 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1794 if (!empty() && !d->fontlist_.empty())
1795 return d->fontlist_.begin()->font();
1797 // Optimisation: avoid a full font instantiation if there is no
1798 // language change from previous call.
1799 static Font previous_font;
1800 static Language const * previous_lang = 0;
1801 if (bparams.language != previous_lang) {
1802 previous_lang = bparams.language;
1803 previous_font = Font(inherit_font, bparams.language);
1806 return previous_font;
1810 // Gets the fully instantiated font at a given position in a paragraph
1811 // This is basically the same function as Text::GetFont() in text2.cpp.
1812 // The difference is that this one is used for generating the LaTeX file,
1813 // and thus cosmetic "improvements" are disallowed: This has to deliver
1814 // the true picture of the buffer. (Asger)
1815 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1816 Font const & outerfont) const
1820 Font font = getFontSettings(bparams, pos);
1822 pos_type const body_pos = beginOfBody();
1823 FontInfo & fi = font.fontInfo();
1825 fi.realize(d->layout_->labelfont);
1827 fi.realize(d->layout_->font);
1829 fi.realize(outerfont.fontInfo());
1830 fi.realize(bparams.getFont().fontInfo());
1836 Font const Paragraph::getLabelFont
1837 (BufferParams const & bparams, Font const & outerfont) const
1839 FontInfo tmpfont = d->layout_->labelfont;
1840 tmpfont.realize(outerfont.fontInfo());
1841 tmpfont.realize(bparams.getFont().fontInfo());
1842 return Font(tmpfont, getParLanguage(bparams));
1846 Font const Paragraph::getLayoutFont
1847 (BufferParams const & bparams, Font const & outerfont) const
1849 FontInfo tmpfont = d->layout_->font;
1850 tmpfont.realize(outerfont.fontInfo());
1851 tmpfont.realize(bparams.getFont().fontInfo());
1852 return Font(tmpfont, getParLanguage(bparams));
1856 char_type Paragraph::getUChar(BufferParams const & bparams,
1857 OutputParams const & rp,
1860 char_type c = d->text_[pos];
1862 // Return unchanged character in LTR languages
1863 // or if we use poylglossia/bidi.
1864 if (rp.use_polyglossia || !getFontSettings(bparams, pos).isRightToLeft())
1867 // Without polyglossia/bidi, we need to account for some special cases.
1868 // FIXME This needs to be audited!
1870 // * The input is as expected for all delimiters
1871 // => checked for Hebrew!
1872 // * The output matches the display in the LyX workarea
1873 // => checked for Hebrew!
1874 // * The special cases below are really necessary
1875 // => checked for Hebrew!
1876 // * In arabic_arabi, brackets are transformed to Arabic
1877 // Ornate Parentheses. Is this is really wanted?
1879 string const & lang = getFontSettings(bparams, pos).language()->lang();
1882 // 1. In the following languages, parentheses need to be reversed.
1883 bool const reverseparens = lang == "hebrew";
1885 // 2. In the following languages, brackets don't need to be reversed.
1886 bool const reversebrackets = lang != "arabic_arabtex"
1887 && lang != "arabic_arabi"
1890 // Now swap delimiters if needed.
1901 if (reversebrackets)
1905 if (reversebrackets)
1926 void Paragraph::setFont(pos_type pos, Font const & font)
1928 LASSERT(pos <= size(), return);
1930 // First, reduce font against layout/label font
1931 // Update: The setCharFont() routine in text2.cpp already
1932 // reduces font, so we don't need to do that here. (Asger)
1934 d->fontlist_.set(pos, font);
1938 void Paragraph::makeSameLayout(Paragraph const & par)
1940 d->layout_ = par.d->layout_;
1941 d->params_ = par.d->params_;
1945 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1947 if (isFreeSpacing())
1953 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1954 if (eraseChar(pos, trackChanges))
1960 return count > 0 || pos > 0;
1964 bool Paragraph::hasSameLayout(Paragraph const & par) const
1966 return par.d->layout_ == d->layout_
1967 && d->params_.sameLayout(par.d->params_);
1971 depth_type Paragraph::getDepth() const
1973 return d->params_.depth();
1977 depth_type Paragraph::getMaxDepthAfter() const
1979 if (d->layout_->isEnvironment())
1980 return d->params_.depth() + 1;
1982 return d->params_.depth();
1986 LyXAlignment Paragraph::getAlign() const
1988 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1989 return d->layout_->align;
1991 return d->params_.align();
1995 docstring const & Paragraph::labelString() const
1997 return d->params_.labelString();
2001 // the next two functions are for the manual labels
2002 docstring const Paragraph::getLabelWidthString() const
2004 if (d->layout_->margintype == MARGIN_MANUAL
2005 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2006 return d->params_.labelWidthString();
2008 return _("Senseless with this layout!");
2012 void Paragraph::setLabelWidthString(docstring const & s)
2014 d->params_.labelWidthString(s);
2018 docstring Paragraph::expandLabel(Layout const & layout,
2019 BufferParams const & bparams) const
2021 return expandParagraphLabel(layout, bparams, true);
2025 docstring Paragraph::expandDocBookLabel(Layout const & layout,
2026 BufferParams const & bparams) const
2028 return expandParagraphLabel(layout, bparams, false);
2032 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2033 BufferParams const & bparams, bool process_appendix) const
2035 DocumentClass const & tclass = bparams.documentClass();
2036 string const & lang = getParLanguage(bparams)->code();
2037 bool const in_appendix = process_appendix && d->params_.appendix();
2038 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2040 if (fmt.empty() && !layout.counter.empty())
2041 return tclass.counters().theCounter(layout.counter, lang);
2043 // handle 'inherited level parts' in 'fmt',
2044 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2045 size_t const i = fmt.find('@', 0);
2046 if (i != docstring::npos) {
2047 size_t const j = fmt.find('@', i + 1);
2048 if (j != docstring::npos) {
2049 docstring parent(fmt, i + 1, j - i - 1);
2050 docstring label = from_ascii("??");
2051 if (tclass.hasLayout(parent))
2052 label = expandParagraphLabel(tclass[parent], bparams,
2054 fmt = docstring(fmt, 0, i) + label
2055 + docstring(fmt, j + 1, docstring::npos);
2059 return tclass.counters().counterLabel(fmt, lang);
2063 void Paragraph::applyLayout(Layout const & new_layout)
2065 d->layout_ = &new_layout;
2066 LyXAlignment const oldAlign = d->params_.align();
2068 if (!(oldAlign & d->layout_->alignpossible)) {
2069 frontend::Alert::warning(_("Alignment not permitted"),
2070 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2071 d->params_.align(LYX_ALIGN_LAYOUT);
2076 pos_type Paragraph::beginOfBody() const
2078 return d->begin_of_body_;
2082 void Paragraph::setBeginOfBody()
2084 if (d->layout_->labeltype != LABEL_MANUAL) {
2085 d->begin_of_body_ = 0;
2089 // Unroll the first two cycles of the loop
2090 // and remember the previous character to
2091 // remove unnecessary getChar() calls
2093 pos_type end = size();
2094 if (i < end && !(isNewline(i) || isEnvSeparator(i))) {
2097 char_type previous_char = d->text_[i];
2098 if (!(isNewline(i) || isEnvSeparator(i))) {
2100 while (i < end && previous_char != ' ') {
2101 char_type temp = d->text_[i];
2102 if (isNewline(i) || isEnvSeparator(i))
2105 previous_char = temp;
2111 d->begin_of_body_ = i;
2115 bool Paragraph::allowParagraphCustomization() const
2117 return inInset().allowParagraphCustomization();
2121 bool Paragraph::usePlainLayout() const
2123 return inInset().usePlainLayout();
2127 bool Paragraph::isPassThru() const
2129 return inInset().isPassThru() || d->layout_->pass_thru;
2134 // paragraphs inside floats need different alignment tags to avoid
2137 bool noTrivlistCentering(InsetCode code)
2139 return code == FLOAT_CODE
2140 || code == WRAP_CODE
2141 || code == CELL_CODE;
2145 string correction(string const & orig)
2147 if (orig == "flushleft")
2148 return "raggedright";
2149 if (orig == "flushright")
2150 return "raggedleft";
2151 if (orig == "center")
2157 bool corrected_env(otexstream & os, string const & suffix, string const & env,
2158 InsetCode code, bool const lastpar, int & col)
2160 string macro = suffix + "{";
2161 if (noTrivlistCentering(code)) {
2163 // the last paragraph in non-trivlist-aligned
2164 // context is special (to avoid unwanted whitespace)
2165 if (suffix == "\\begin") {
2166 macro = "\\" + correction(env) + "{}";
2167 os << from_ascii(macro);
2168 col += macro.size();
2173 macro += correction(env);
2177 if (suffix == "\\par\\end") {
2181 os << from_ascii(macro);
2182 col += macro.size();
2183 if (suffix == "\\begin") {
2193 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2194 otexstream & os, OutputParams const & runparams) const
2199 (bparams.paragraph_separation == BufferParams::ParagraphIndentSeparation) ?
2200 (layout_->toggle_indent != ITOGGLE_NEVER) :
2201 (layout_->toggle_indent == ITOGGLE_ALWAYS);
2203 if (canindent && params_.noindent() && !layout_->pass_thru) {
2204 os << "\\noindent ";
2208 LyXAlignment const curAlign = params_.align();
2210 if (curAlign == layout_->align)
2214 case LYX_ALIGN_NONE:
2215 case LYX_ALIGN_BLOCK:
2216 case LYX_ALIGN_LAYOUT:
2217 case LYX_ALIGN_SPECIAL:
2218 case LYX_ALIGN_DECIMAL:
2220 case LYX_ALIGN_LEFT:
2221 case LYX_ALIGN_RIGHT:
2222 case LYX_ALIGN_CENTER:
2223 if (runparams.moving_arg) {
2230 string const begin_tag = "\\begin";
2231 InsetCode code = ownerCode();
2232 bool const lastpar = runparams.isLastPar;
2233 // RTL in classic (PDF)LaTeX (without the Bidi package)
2234 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2235 && !runparams.use_polyglossia;
2238 case LYX_ALIGN_NONE:
2239 case LYX_ALIGN_BLOCK:
2240 case LYX_ALIGN_LAYOUT:
2241 case LYX_ALIGN_SPECIAL:
2242 case LYX_ALIGN_DECIMAL:
2244 case LYX_ALIGN_LEFT: {
2246 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2247 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2249 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2251 } case LYX_ALIGN_RIGHT: {
2253 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2254 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2256 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2258 } case LYX_ALIGN_CENTER: {
2259 corrected_env(os, begin_tag, "center", code, lastpar, column);
2268 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2269 otexstream & os, OutputParams const & runparams) const
2271 LyXAlignment const curAlign = params_.align();
2273 if (curAlign == layout_->align)
2277 case LYX_ALIGN_NONE:
2278 case LYX_ALIGN_BLOCK:
2279 case LYX_ALIGN_LAYOUT:
2280 case LYX_ALIGN_SPECIAL:
2281 case LYX_ALIGN_DECIMAL:
2283 case LYX_ALIGN_LEFT:
2284 case LYX_ALIGN_RIGHT:
2285 case LYX_ALIGN_CENTER:
2286 if (runparams.moving_arg)
2291 bool output = false;
2293 string const end_tag = "\\par\\end";
2294 InsetCode code = ownerCode();
2295 bool const lastpar = runparams.isLastPar;
2296 // RTL in classic (PDF)LaTeX (without the Bidi package)
2297 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2298 && !runparams.use_polyglossia;
2301 case LYX_ALIGN_NONE:
2302 case LYX_ALIGN_BLOCK:
2303 case LYX_ALIGN_LAYOUT:
2304 case LYX_ALIGN_SPECIAL:
2305 case LYX_ALIGN_DECIMAL:
2307 case LYX_ALIGN_LEFT: {
2309 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2310 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2312 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2314 } case LYX_ALIGN_RIGHT: {
2316 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2317 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2319 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2321 } case LYX_ALIGN_CENTER: {
2322 corrected_env(os, end_tag, "center", code, lastpar, col);
2327 return output || lastpar;
2331 // This one spits out the text of the paragraph
2332 void Paragraph::latex(BufferParams const & bparams,
2333 Font const & outerfont,
2335 OutputParams const & runparams,
2336 int start_pos, int end_pos, bool force) const
2338 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2340 // FIXME This check should not be needed. Perhaps issue an
2341 // error if it triggers.
2342 Layout const & style = inInset().forcePlainLayout() ?
2343 bparams.documentClass().plainLayout() : *d->layout_;
2345 if (!force && style.inpreamble)
2348 bool const allowcust = allowParagraphCustomization();
2350 // Current base font for all inherited font changes, without any
2351 // change caused by an individual character, except for the language:
2352 // It is set to the language of the first character.
2353 // As long as we are in the label, this font is the base font of the
2354 // label. Before the first body character it is set to the base font
2358 // If there is an open font-encoding changing command (script wrapper),
2359 // alien_script is set to its name
2360 string alien_script;
2363 // Maybe we have to create a optional argument.
2364 pos_type body_pos = beginOfBody();
2365 unsigned int column = 0;
2368 // the optional argument is kept in curly brackets in
2369 // case it contains a ']'
2370 // This is not strictly needed, but if this is changed it
2371 // would be a file format change, and tex2lyx would need
2372 // to be adjusted, since it unconditionally removes the
2373 // braces when it parses \item.
2376 basefont = getLabelFont(bparams, outerfont);
2378 basefont = getLayoutFont(bparams, outerfont);
2381 // Which font is currently active?
2382 Font running_font(basefont);
2383 // Do we have an open font change?
2384 bool open_font = false;
2386 Change runningChange = Change(Change::UNCHANGED);
2388 Encoding const * const prev_encoding = runparams.encoding;
2390 os.texrow().start(id(), 0);
2392 // if the paragraph is empty, the loop will not be entered at all
2394 // For InTitle commands, we have already opened a group
2395 // in output_latex::TeXOnePar.
2396 if (style.isCommand() && !style.intitle) {
2400 if (!style.leftdelim().empty()) {
2401 os << style.leftdelim();
2402 column += style.leftdelim().size();
2405 column += d->startTeXParParams(bparams, os, runparams);
2408 // Whether a \par can be issued for insets typeset inline with text.
2409 // Yes if greater than 0. This has to be static.
2410 THREAD_LOCAL_STATIC int parInline = 0;
2412 for (pos_type i = 0; i < size(); ++i) {
2413 // First char in paragraph or after label?
2414 if (i == body_pos) {
2417 bool needPar = false;
2418 column += running_font.latexWriteEndChanges(
2419 os, bparams, runparams,
2420 basefont, basefont, needPar);
2423 basefont = getLayoutFont(bparams, outerfont);
2424 running_font = basefont;
2426 column += Changes::latexMarkChange(os, bparams,
2427 runningChange, Change(Change::UNCHANGED),
2429 runningChange = Change(Change::UNCHANGED);
2434 // For InTitle commands, we have already opened a group
2435 // in output_latex::TeXOnePar.
2436 if (style.isCommand() && !style.intitle) {
2441 if (!style.leftdelim().empty()) {
2442 os << style.leftdelim();
2443 column += style.leftdelim().size();
2447 column += d->startTeXParParams(bparams, os,
2451 runparams.wasDisplayMath = runparams.inDisplayMath;
2452 runparams.inDisplayMath = false;
2453 bool deleted_display_math = false;
2454 Change const & change = runparams.inDeletedInset
2455 ? runparams.changeOfDeletedInset : lookupChange(i);
2457 // Check whether a display math inset follows
2458 if (d->text_[i] == META_INSET
2459 && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2460 InsetMath const * im = getInset(i)->asInsetMath();
2461 if (im && im->asHullInset()
2462 && im->asHullInset()->outerDisplay()) {
2463 runparams.inDisplayMath = true;
2464 // runparams.inDeletedInset will be set by
2465 // latexInset later, but we need this info
2466 // before it is called. On the other hand, we
2467 // cannot set it here because it is a counter.
2468 deleted_display_math = isDeleted(i);
2470 if (bparams.output_changes && deleted_display_math
2471 && runningChange == change
2472 && change.type == Change::DELETED
2473 && !os.afterParbreak()) {
2474 // A display math in the same paragraph follows.
2475 // We have to close and then reopen \lyxdeleted,
2476 // otherwise the math will be shifted up.
2477 OutputParams rp = runparams;
2479 bool needPar = false;
2480 column += running_font.latexWriteEndChanges(
2481 os, bparams, rp, basefont,
2485 basefont = getLayoutFont(bparams, outerfont);
2486 running_font = basefont;
2487 column += Changes::latexMarkChange(os, bparams,
2488 Change(Change::INSERTED), change, rp);
2492 if (bparams.output_changes && runningChange != change) {
2493 if (!alien_script.empty()) {
2496 alien_script.clear();
2499 bool needPar = false;
2500 column += running_font.latexWriteEndChanges(
2501 os, bparams, runparams,
2502 basefont, basefont, needPar);
2505 basefont = getLayoutFont(bparams, outerfont);
2506 running_font = basefont;
2507 column += Changes::latexMarkChange(os, bparams, runningChange,
2509 runningChange = change;
2512 // do not output text which is marked deleted
2513 // if change tracking output is disabled
2514 if (!bparams.output_changes && change.deleted()) {
2520 // Fully instantiated font
2521 Font const current_font = getFont(bparams, i, outerfont);
2523 Font const last_font = running_font;
2525 // Do we need to close the previous font?
2527 (current_font != running_font ||
2528 current_font.language() != running_font.language()))
2530 // ensure there is no open script-wrapper
2531 if (!alien_script.empty()) {
2534 alien_script.clear();
2536 bool needPar = false;
2537 column += running_font.latexWriteEndChanges(
2538 os, bparams, runparams, basefont,
2539 (i == body_pos-1) ? basefont : current_font,
2541 running_font = basefont;
2545 string const running_lang = runparams.use_polyglossia ?
2546 running_font.language()->polyglossia() : running_font.language()->babel();
2547 // close babel's font environment before opening CJK.
2548 string const lang_end_command = runparams.use_polyglossia ?
2549 "\\end{$$lang}" : lyxrc.language_command_end;
2550 bool const using_begin_end = runparams.use_polyglossia ||
2551 !lang_end_command.empty();
2552 if (!running_lang.empty() &&
2553 (!using_begin_end || running_lang == openLanguageName()) &&
2554 current_font.language()->encoding()->package() == Encoding::CJK) {
2555 string end_tag = subst(lang_end_command,
2558 os << from_ascii(end_tag);
2559 column += end_tag.length();
2560 if (using_begin_end)
2564 // Switch file encoding if necessary (and allowed)
2565 if (!runparams.pass_thru && !style.pass_thru &&
2566 runparams.encoding->package() != Encoding::none &&
2567 current_font.language()->encoding()->package() != Encoding::none) {
2568 pair<bool, int> const enc_switch =
2569 switchEncoding(os.os(), bparams, runparams,
2570 *(current_font.language()->encoding()));
2571 if (enc_switch.first) {
2572 column += enc_switch.second;
2573 runparams.encoding = current_font.language()->encoding();
2577 char_type const c = d->text_[i];
2579 // A display math inset inside an ulem command will be output
2580 // as a box of width \linewidth, so we have to either disable
2581 // indentation if the inset starts a paragraph, or start a new
2582 // line to accommodate such box. This has to be done before
2583 // writing any font changing commands.
2584 if (runparams.inDisplayMath && !deleted_display_math
2585 && runparams.inulemcmd) {
2586 if (os.afterParbreak())
2592 // Do we need to change font?
2593 if ((current_font != running_font ||
2594 current_font.language() != running_font.language()) &&
2597 odocstringstream ods;
2598 column += current_font.latexWriteStartChanges(ods, bparams,
2599 runparams, basefont,
2601 // Check again for display math in ulem commands as a
2602 // font change may also occur just before a math inset.
2603 if (runparams.inDisplayMath && !deleted_display_math
2604 && runparams.inulemcmd) {
2605 if (os.afterParbreak())
2610 running_font = current_font;
2612 docstring fontchange = ods.str();
2613 // check whether the fontchange ends with a \\textcolor
2614 // modifier and the text starts with a space (bug 4473)
2615 docstring const last_modifier = rsplit(fontchange, '\\');
2616 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2617 os << fontchange << from_ascii("{}");
2618 // check if the fontchange ends with a trailing blank
2619 // (like "\small " (see bug 3382)
2620 else if (suffixIs(fontchange, ' ') && c == ' ')
2621 os << fontchange.substr(0, fontchange.size() - 1)
2622 << from_ascii("{}");
2627 // FIXME: think about end_pos implementation...
2628 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2629 // FIXME: integrate this case in latexSpecialChar
2630 // Do not print the separation of the optional argument
2631 // if style.pass_thru is false. This works because
2632 // latexSpecialChar ignores spaces if
2633 // style.pass_thru is false.
2634 if (i != body_pos - 1) {
2635 if (d->simpleTeXBlanks(bparams, runparams, os,
2636 i, column, current_font, style)) {
2637 // A surrogate pair was output. We
2638 // must not call latexSpecialChar
2639 // in this iteration, since it would output
2640 // the combining character again.
2647 OutputParams rp = runparams;
2648 rp.free_spacing = style.free_spacing;
2649 rp.local_font = ¤t_font;
2650 rp.intitle = style.intitle;
2652 // Two major modes: LaTeX or plain
2653 // Handle here those cases common to both modes
2654 // and then split to handle the two modes separately.
2655 if (c == META_INSET) {
2656 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2657 // Greyedout notes and, in general, all insets
2658 // with InsetLayout::isDisplay() == false,
2659 // are typeset inline with the text. So, we
2660 // can add a \par to the last paragraph of
2661 // such insets only if nothing else follows.
2662 bool incremented = false;
2663 Inset const * inset = getInset(i);
2664 InsetText const * textinset = inset
2665 ? inset->asInsetText()
2667 if (i + 1 == size() && textinset
2668 && !inset->getLayout().isDisplay()) {
2669 ParagraphList const & pars =
2670 textinset->text().paragraphs();
2671 pit_type const pit = pars.size() - 1;
2672 Font const lastfont =
2673 pit < 0 || pars[pit].empty()
2674 ? pars[pit].getLayoutFont(
2677 : pars[pit].getFont(bparams,
2678 pars[pit].size() - 1,
2680 if (lastfont.fontInfo().size() !=
2681 basefont.fontInfo().size()) {
2686 d->latexInset(bparams, os, rp, running_font,
2687 basefont, outerfont, open_font,
2688 runningChange, style, i, column);
2692 } else if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2693 if (!bparams.useNonTeXFonts)
2694 script = Encodings::isKnownScriptChar(c);
2695 if (script != alien_script) {
2696 if (!alien_script.empty()) {
2698 alien_script.clear();
2700 string fontenc = running_font.language()->fontenc(bparams);
2702 && !Encodings::fontencSupportsScript(fontenc, script)) {
2703 column += script.length() + 2;
2704 os << "\\" << script << "{";
2705 alien_script = script;
2709 d->latexSpecialChar(os, bparams, rp, running_font,
2710 alien_script, style, i, end_pos, column);
2711 } catch (EncodingException & e) {
2712 if (runparams.dryrun) {
2713 os << "<" << _("LyX Warning: ")
2714 << _("uncodable character") << " '";
2718 // add location information and throw again.
2726 // Set the encoding to that returned from latexSpecialChar (see
2727 // comment for encoding member in OutputParams.h)
2728 runparams.encoding = rp.encoding;
2730 // Also carry on the info on a closed ulem command for insets
2731 // such as Note that do not produce any output, so that no
2732 // command is ever executed but its opening was recorded.
2733 runparams.inulemcmd = rp.inulemcmd;
2735 // And finally, pass the post_macros upstream
2736 runparams.post_macro = rp.post_macro;
2739 // Close wrapper for alien script
2740 if (!alien_script.empty()) {
2742 alien_script.clear();
2745 // If we have an open font definition, we have to close it
2747 // Make sure that \\par is done with the font of the last
2748 // character if this has another size as the default.
2749 // This is necessary because LaTeX (and LyX on the screen)
2750 // calculates the space between the baselines according
2751 // to this font. (Matthias)
2753 // We must not change the font for the last paragraph
2754 // of non-multipar insets, tabular cells or commands,
2755 // since this produces unwanted whitespace.
2757 Font const font = empty()
2758 ? getLayoutFont(bparams, outerfont)
2759 : getFont(bparams, size() - 1, outerfont);
2761 InsetText const * textinset = inInset().asInsetText();
2763 bool const maintext = textinset
2764 ? textinset->text().isMainText()
2767 size_t const numpars = textinset
2768 ? textinset->text().paragraphs().size()
2771 bool needPar = false;
2773 if (style.resfont.size() != font.fontInfo().size()
2774 && (!runparams.isLastPar || maintext
2775 || (numpars > 1 && d->ownerCode() != CELL_CODE
2776 && (inInset().getLayout().isDisplay()
2778 && !style.isCommand()) {
2781 #ifdef FIXED_LANGUAGE_END_DETECTION
2783 running_font.latexWriteEndChanges(os, bparams,
2784 runparams, basefont,
2785 next_->getFont(bparams, 0, outerfont),
2788 running_font.latexWriteEndChanges(os, bparams,
2789 runparams, basefont, basefont, needPar);
2792 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2793 //FIXME: there as we start another \selectlanguage with the next paragraph if
2794 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2795 running_font.latexWriteEndChanges(os, bparams, runparams,
2796 basefont, basefont, needPar);
2799 // The \par could not be inserted at the same nesting
2800 // level of the font size change, so do it now.
2801 os << "{\\" << font.latexSize() << "\\par}";
2805 column += Changes::latexMarkChange(os, bparams, runningChange,
2806 Change(Change::UNCHANGED), runparams);
2808 // Needed if there is an optional argument but no contents.
2809 if (body_pos > 0 && body_pos == size()) {
2813 if (!style.rightdelim().empty()) {
2814 os << style.rightdelim();
2815 column += style.rightdelim().size();
2818 if (allowcust && d->endTeXParParams(bparams, os, runparams)
2819 && runparams.encoding != prev_encoding) {
2820 runparams.encoding = prev_encoding;
2821 os << setEncoding(prev_encoding->iconvName());
2824 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2828 bool Paragraph::emptyTag() const
2830 for (pos_type i = 0; i < size(); ++i) {
2831 if (Inset const * inset = getInset(i)) {
2832 InsetCode lyx_code = inset->lyxCode();
2833 // FIXME testing like that is wrong. What is
2835 if (lyx_code != TOC_CODE &&
2836 lyx_code != INCLUDE_CODE &&
2837 lyx_code != GRAPHICS_CODE &&
2838 lyx_code != ERT_CODE &&
2839 lyx_code != LISTINGS_CODE &&
2840 lyx_code != FLOAT_CODE &&
2841 lyx_code != TABULAR_CODE) {
2845 char_type c = d->text_[i];
2846 if (c != ' ' && c != '\t')
2854 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2857 for (pos_type i = 0; i < size(); ++i) {
2858 if (Inset const * inset = getInset(i)) {
2859 InsetCode lyx_code = inset->lyxCode();
2860 if (lyx_code == LABEL_CODE) {
2861 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2862 docstring const & id = il->getParam("name");
2863 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2871 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2875 for (i = 0; i < size(); ++i) {
2876 if (Inset const * inset = getInset(i)) {
2877 inset->docbook(os, runparams);
2879 char_type c = d->text_[i];
2882 os << sgml::escapeChar(c);
2889 pos_type Paragraph::firstWordLyXHTML(XHTMLStream & xs, OutputParams const & runparams)
2893 for (i = 0; i < size(); ++i) {
2894 if (Inset const * inset = getInset(i)) {
2895 inset->xhtml(xs, runparams);
2897 char_type c = d->text_[i];
2907 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2910 pos_type size = text_.size();
2911 for (pos_type i = initial; i < size; ++i) {
2912 Font font = owner_->getFont(buf.params(), i, outerfont);
2913 if (text_[i] == META_INSET)
2915 if (i != initial && font != font_old)
2924 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2926 OutputParams const & runparams,
2927 Font const & outerfont,
2928 pos_type initial) const
2930 bool emph_flag = false;
2932 Layout const & style = *d->layout_;
2934 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2936 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2939 // parsing main loop
2940 for (pos_type i = initial; i < size(); ++i) {
2941 Font font = getFont(buf.params(), i, outerfont);
2943 // handle <emphasis> tag
2944 if (font_old.emph() != font.fontInfo().emph()) {
2945 if (font.fontInfo().emph() == FONT_ON) {
2948 } else if (i != initial) {
2949 os << "</emphasis>";
2954 if (Inset const * inset = getInset(i)) {
2955 inset->docbook(os, runparams);
2957 char_type c = d->text_[i];
2959 if (style.pass_thru)
2962 os << sgml::escapeChar(c);
2964 font_old = font.fontInfo();
2968 os << "</emphasis>";
2971 if (style.free_spacing)
2973 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2979 void doFontSwitch(vector<html::FontTag> & tagsToOpen,
2980 vector<html::EndFontTag> & tagsToClose,
2981 bool & flag, FontState curstate, html::FontTypes type)
2983 if (curstate == FONT_ON) {
2984 tagsToOpen.push_back(html::FontTag(type));
2987 tagsToClose.push_back(html::EndFontTag(type));
2994 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2996 OutputParams const & runparams,
2997 Font const & outerfont,
2998 bool start_paragraph, bool close_paragraph,
2999 pos_type initial) const
3003 // track whether we have opened these tags
3004 bool emph_flag = false;
3005 bool bold_flag = false;
3006 bool noun_flag = false;
3007 bool ubar_flag = false;
3008 bool dbar_flag = false;
3009 bool sout_flag = false;
3010 bool xout_flag = false;
3011 bool wave_flag = false;
3013 bool shap_flag = false;
3015 bool faml_flag = false;
3017 bool size_flag = false;
3019 Layout const & style = *d->layout_;
3021 if (start_paragraph)
3022 xs.startDivision(allowEmpty());
3025 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3027 FontShape curr_fs = INHERIT_SHAPE;
3028 FontFamily curr_fam = INHERIT_FAMILY;
3029 FontSize curr_size = FONT_SIZE_INHERIT;
3031 string const default_family =
3032 buf.masterBuffer()->params().fonts_default_family;
3034 vector<html::FontTag> tagsToOpen;
3035 vector<html::EndFontTag> tagsToClose;
3037 // parsing main loop
3038 for (pos_type i = initial; i < size(); ++i) {
3039 // let's not show deleted material in the output
3043 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3046 FontState curstate = font.fontInfo().emph();
3047 if (font_old.emph() != curstate)
3048 doFontSwitch(tagsToOpen, tagsToClose, emph_flag, curstate, html::FT_EMPH);
3051 curstate = font.fontInfo().noun();
3052 if (font_old.noun() != curstate)
3053 doFontSwitch(tagsToOpen, tagsToClose, noun_flag, curstate, html::FT_NOUN);
3056 curstate = font.fontInfo().underbar();
3057 if (font_old.underbar() != curstate)
3058 doFontSwitch(tagsToOpen, tagsToClose, ubar_flag, curstate, html::FT_UBAR);
3061 curstate = font.fontInfo().strikeout();
3062 if (font_old.strikeout() != curstate)
3063 doFontSwitch(tagsToOpen, tagsToClose, sout_flag, curstate, html::FT_SOUT);
3066 curstate = font.fontInfo().xout();
3067 if (font_old.xout() != curstate)
3068 doFontSwitch(tagsToOpen, tagsToClose, xout_flag, curstate, html::FT_XOUT);
3071 curstate = font.fontInfo().uuline();
3072 if (font_old.uuline() != curstate)
3073 doFontSwitch(tagsToOpen, tagsToClose, dbar_flag, curstate, html::FT_DBAR);
3076 curstate = font.fontInfo().uwave();
3077 if (font_old.uwave() != curstate)
3078 doFontSwitch(tagsToOpen, tagsToClose, wave_flag, curstate, html::FT_WAVE);
3081 // a little hackish, but allows us to reuse what we have.
3082 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3083 if (font_old.series() != font.fontInfo().series())
3084 doFontSwitch(tagsToOpen, tagsToClose, bold_flag, curstate, html::FT_BOLD);
3087 curr_fs = font.fontInfo().shape();
3088 FontShape old_fs = font_old.shape();
3089 if (old_fs != curr_fs) {
3093 tagsToClose.push_back(html::EndFontTag(html::FT_ITALIC));
3096 tagsToClose.push_back(html::EndFontTag(html::FT_SLANTED));
3098 case SMALLCAPS_SHAPE:
3099 tagsToClose.push_back(html::EndFontTag(html::FT_SMALLCAPS));
3105 // the other tags are for internal use
3113 tagsToOpen.push_back(html::FontTag(html::FT_ITALIC));
3117 tagsToOpen.push_back(html::FontTag(html::FT_SLANTED));
3120 case SMALLCAPS_SHAPE:
3121 tagsToOpen.push_back(html::FontTag(html::FT_SMALLCAPS));
3128 // the other tags are for internal use
3135 curr_fam = font.fontInfo().family();
3136 FontFamily old_fam = font_old.family();
3137 if (old_fam != curr_fam) {
3141 tagsToClose.push_back(html::EndFontTag(html::FT_ROMAN));
3144 tagsToClose.push_back(html::EndFontTag(html::FT_SANS));
3146 case TYPEWRITER_FAMILY:
3147 tagsToClose.push_back(html::EndFontTag(html::FT_TYPE));
3149 case INHERIT_FAMILY:
3152 // the other tags are for internal use
3160 // we will treat a "default" font family as roman, since we have
3161 // no other idea what to do.
3162 if (default_family != "rmdefault" && default_family != "default") {
3163 tagsToOpen.push_back(html::FontTag(html::FT_ROMAN));
3168 if (default_family != "sfdefault") {
3169 tagsToOpen.push_back(html::FontTag(html::FT_SANS));
3173 case TYPEWRITER_FAMILY:
3174 if (default_family != "ttdefault") {
3175 tagsToOpen.push_back(html::FontTag(html::FT_TYPE));
3179 case INHERIT_FAMILY:
3182 // the other tags are for internal use
3189 curr_size = font.fontInfo().size();
3190 FontSize old_size = font_old.size();
3191 if (old_size != curr_size) {
3194 case FONT_SIZE_TINY:
3195 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_TINY));
3197 case FONT_SIZE_SCRIPT:
3198 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_SCRIPT));
3200 case FONT_SIZE_FOOTNOTE:
3201 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_FOOTNOTE));
3203 case FONT_SIZE_SMALL:
3204 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_SMALL));
3206 case FONT_SIZE_LARGE:
3207 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGE));
3209 case FONT_SIZE_LARGER:
3210 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGER));
3212 case FONT_SIZE_LARGEST:
3213 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGEST));
3215 case FONT_SIZE_HUGE:
3216 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_HUGE));
3218 case FONT_SIZE_HUGER:
3219 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_HUGER));
3221 case FONT_SIZE_INCREASE:
3222 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_INCREASE));
3224 case FONT_SIZE_DECREASE:
3225 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_DECREASE));
3227 case FONT_SIZE_INHERIT:
3228 case FONT_SIZE_NORMAL:
3231 // the other tags are for internal use
3237 switch (curr_size) {
3238 case FONT_SIZE_TINY:
3239 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_TINY));
3242 case FONT_SIZE_SCRIPT:
3243 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_SCRIPT));
3246 case FONT_SIZE_FOOTNOTE:
3247 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_FOOTNOTE));
3250 case FONT_SIZE_SMALL:
3251 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_SMALL));
3254 case FONT_SIZE_LARGE:
3255 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGE));
3258 case FONT_SIZE_LARGER:
3259 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGER));
3262 case FONT_SIZE_LARGEST:
3263 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGEST));
3266 case FONT_SIZE_HUGE:
3267 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_HUGE));
3270 case FONT_SIZE_HUGER:
3271 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_HUGER));
3274 case FONT_SIZE_INCREASE:
3275 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_INCREASE));
3278 case FONT_SIZE_DECREASE:
3279 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_DECREASE));
3282 case FONT_SIZE_NORMAL:
3283 case FONT_SIZE_INHERIT:
3286 // the other tags are for internal use
3293 // Other such tags? What about the other text ranges?
3295 vector<html::EndFontTag>::const_iterator cit = tagsToClose.begin();
3296 vector<html::EndFontTag>::const_iterator cen = tagsToClose.end();
3297 for (; cit != cen; ++cit)
3300 vector<html::FontTag>::const_iterator sit = tagsToOpen.begin();
3301 vector<html::FontTag>::const_iterator sen = tagsToOpen.end();
3302 for (; sit != sen; ++sit)
3305 tagsToClose.clear();
3308 Inset const * inset = getInset(i);
3310 if (!runparams.for_toc || inset->isInToc()) {
3311 OutputParams np = runparams;
3312 np.local_font = &font;
3313 // If the paragraph has size 1, then we are in the "special
3314 // case" where we do not output the containing paragraph info
3315 if (!inset->getLayout().htmlisblock() && size() != 1)
3316 np.html_in_par = true;
3317 retval += inset->xhtml(xs, np);
3320 char_type c = getUChar(buf.masterBuffer()->params(),
3322 if (c == ' ' && (style.free_spacing || runparams.free_spacing))
3323 xs << XHTMLStream::ESCAPE_NONE << " ";
3327 font_old = font.fontInfo();
3331 // I'm worried about what happens if a branch, say, is itself
3332 // wrapped in some font stuff. I think that will not work.
3334 if (close_paragraph)
3341 bool Paragraph::isHfill(pos_type pos) const
3343 Inset const * inset = getInset(pos);
3344 return inset && inset->isHfill();
3348 bool Paragraph::isNewline(pos_type pos) const
3350 // U+2028 LINE SEPARATOR
3351 // U+2029 PARAGRAPH SEPARATOR
3352 char_type const c = d->text_[pos];
3353 if (c == 0x2028 || c == 0x2029)
3355 Inset const * inset = getInset(pos);
3356 return inset && inset->lyxCode() == NEWLINE_CODE;
3360 bool Paragraph::isEnvSeparator(pos_type pos) const
3362 Inset const * inset = getInset(pos);
3363 return inset && inset->lyxCode() == SEPARATOR_CODE;
3367 bool Paragraph::isLineSeparator(pos_type pos) const
3369 char_type const c = d->text_[pos];
3370 if (isLineSeparatorChar(c))
3372 Inset const * inset = getInset(pos);
3373 return inset && inset->isLineSeparator();
3377 bool Paragraph::isWordSeparator(pos_type pos) const
3381 if (Inset const * inset = getInset(pos))
3382 return !inset->isLetter();
3383 // if we have a hard hyphen (no en- or emdash) or apostrophe
3384 // we pass this to the spell checker
3385 // FIXME: this method is subject to change, visit
3386 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
3387 // to get an impression how complex this is.
3388 if (isHardHyphenOrApostrophe(pos))
3390 char_type const c = d->text_[pos];
3391 // We want to pass the escape chars to the spellchecker
3392 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
3393 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
3397 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
3399 pos_type const psize = size();
3402 char_type const c = d->text_[pos];
3403 if (c != '-' && c != '\'')
3405 int nextpos = pos + 1;
3406 int prevpos = pos > 0 ? pos - 1 : 0;
3407 if ((nextpos == psize || isSpace(nextpos))
3408 && (pos == 0 || isSpace(prevpos)))
3414 bool Paragraph::needsCProtection(bool const fragile) const
3416 // first check the layout of the paragraph, but only in insets
3417 InsetText const * textinset = inInset().asInsetText();
3418 bool const maintext = textinset
3419 ? textinset->text().isMainText()
3422 if (!maintext && layout().needcprotect) {
3423 // Environments need cprotection regardless the content
3424 if (layout().latextype == LATEX_ENVIRONMENT)
3427 // Commands need cprotection if they contain specific chars
3428 int const nchars_escape = 9;
3429 static char_type const chars_escape[nchars_escape] = {
3430 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
3432 docstring const pars = asString();
3433 for (int k = 0; k < nchars_escape; k++) {
3434 if (contains(pars, chars_escape[k]))
3439 // now check whether we have insets that need cprotection
3440 pos_type size = pos_type(d->text_.size());
3441 for (pos_type i = 0; i < size; ++i) {
3444 Inset const * ins = getInset(i);
3445 if (ins->needsCProtection(maintext, fragile))
3447 if (ins->getLayout().latextype() == InsetLayout::ENVIRONMENT)
3448 // Environments need cprotection regardless the content
3450 // Now check math environments
3451 InsetMath const * im = getInset(i)->asInsetMath();
3452 if (!im || im->cell(0).empty())
3454 switch(im->cell(0)[0]->lyxCode()) {
3455 case MATH_AMSARRAY_CODE:
3456 case MATH_SUBSTACK_CODE:
3458 case MATH_XYMATRIX_CODE:
3459 // these need cprotection
3470 FontSpan const & Paragraph::getSpellRange(pos_type pos) const
3472 return d->speller_state_.getRange(pos);
3476 bool Paragraph::isChar(pos_type pos) const
3478 if (Inset const * inset = getInset(pos))
3479 return inset->isChar();
3480 char_type const c = d->text_[pos];
3481 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
3485 bool Paragraph::isSpace(pos_type pos) const
3487 if (Inset const * inset = getInset(pos))
3488 return inset->isSpace();
3489 char_type const c = d->text_[pos];
3490 return lyx::isSpace(c);
3495 Paragraph::getParLanguage(BufferParams const & bparams) const
3498 return getFirstFontSettings(bparams).language();
3499 // FIXME: we should check the prev par as well (Lgb)
3500 return bparams.language;
3504 bool Paragraph::isRTL(BufferParams const & bparams) const
3506 return getParLanguage(bparams)->rightToLeft()
3507 && !inInset().getLayout().forceLTR();
3511 void Paragraph::changeLanguage(BufferParams const & bparams,
3512 Language const * from, Language const * to)
3514 // change language including dummy font change at the end
3515 for (pos_type i = 0; i <= size(); ++i) {
3516 Font font = getFontSettings(bparams, i);
3517 if (font.language() == from) {
3518 font.setLanguage(to);
3520 d->requestSpellCheck(i);
3526 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
3528 Language const * doc_language = bparams.language;
3529 for (auto const & f : d->fontlist_)
3530 if (f.font().language() != ignore_language &&
3531 f.font().language() != latex_language &&
3532 f.font().language() != doc_language)
3538 void Paragraph::getLanguages(std::set<Language const *> & langs) const
3540 for (auto const & f : d->fontlist_) {
3541 Language const * lang = f.font().language();
3542 if (lang != ignore_language &&
3543 lang != latex_language)
3549 docstring Paragraph::asString(int options) const
3551 return asString(0, size(), options);
3555 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
3557 odocstringstream os;
3560 && options & AS_STR_LABEL
3561 && !d->params_.labelString().empty())
3562 os << d->params_.labelString() << ' ';
3564 for (pos_type i = beg; i < end; ++i) {
3565 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
3567 char_type const c = d->text_[i];
3568 if (isPrintable(c) || c == '\t'
3569 || (c == '\n' && (options & AS_STR_NEWLINES)))
3571 else if (c == META_INSET && (options & AS_STR_INSETS)) {
3572 if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
3573 LASSERT(runparams != 0, return docstring());
3574 getInset(i)->plaintext(os, *runparams);
3576 getInset(i)->toString(os);
3585 void Paragraph::forOutliner(docstring & os, size_t const maxlen,
3586 bool const shorten, bool const label) const
3588 size_t tmplen = shorten ? maxlen + 1 : maxlen;
3589 if (label && !labelString().empty())
3590 os += labelString() + ' ';
3591 if (!layout().isTocCaption())
3593 for (pos_type i = 0; i < size() && os.length() < tmplen; ++i) {
3596 char_type const c = d->text_[i];
3599 else if (c == META_INSET)
3600 getInset(i)->forOutliner(os, tmplen, false);
3603 Text::shortenForOutliner(os, maxlen);
3607 void Paragraph::setInsetOwner(Inset const * inset)
3609 d->inset_owner_ = inset;
3613 int Paragraph::id() const
3619 void Paragraph::setId(int id)
3625 Layout const & Paragraph::layout() const
3631 void Paragraph::setLayout(Layout const & layout)
3633 d->layout_ = &layout;
3637 void Paragraph::setDefaultLayout(DocumentClass const & tc)
3639 setLayout(tc.defaultLayout());
3643 void Paragraph::setPlainLayout(DocumentClass const & tc)
3645 setLayout(tc.plainLayout());
3649 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
3651 if (usePlainLayout())
3652 setPlainLayout(tclass);
3654 setDefaultLayout(tclass);
3658 Inset const & Paragraph::inInset() const
3660 LBUFERR(d->inset_owner_);
3661 return *d->inset_owner_;
3665 ParagraphParameters & Paragraph::params()
3671 ParagraphParameters const & Paragraph::params() const
3677 bool Paragraph::isFreeSpacing() const
3679 if (d->layout_->free_spacing)
3681 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
3685 bool Paragraph::allowEmpty() const
3687 if (d->layout_->keepempty)
3689 return d->inset_owner_ && d->inset_owner_->allowEmpty();
3693 bool Paragraph::brokenBiblio() const
3695 // There is a problem if there is no bibitem at position 0 in
3696 // paragraphs that need one, if there is another bibitem in the
3697 // paragraph or if this paragraph is not supposed to have
3698 // a bibitem inset at all.
3699 return ((d->layout_->labeltype == LABEL_BIBLIO
3700 && (d->insetlist_.find(BIBITEM_CODE) != 0
3701 || d->insetlist_.find(BIBITEM_CODE, 1) > 0))
3702 || (d->layout_->labeltype != LABEL_BIBLIO
3703 && d->insetlist_.find(BIBITEM_CODE) != -1));
3707 int Paragraph::fixBiblio(Buffer const & buffer)
3709 // FIXME: when there was already an inset at 0, the return value is 1,
3710 // which does not tell whether another inset has been remove; the
3711 // cursor cannot be correctly updated.
3713 bool const track_changes = buffer.params().track_changes;
3714 int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
3716 // The case where paragraph is not BIBLIO
3717 if (d->layout_->labeltype != LABEL_BIBLIO) {
3718 if (bibitem_pos == -1)
3719 // No InsetBibitem => OK
3721 // There is an InsetBibitem: remove it!
3722 d->insetlist_.release(bibitem_pos);
3723 eraseChar(bibitem_pos, track_changes);
3724 return (bibitem_pos == 0) ? -1 : -bibitem_pos;
3727 bool const hasbibitem0 = bibitem_pos == 0;
3729 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
3730 // There was an InsetBibitem at pos 0,
3731 // and no other one => OK
3732 if (bibitem_pos == -1)
3734 // there is a bibitem at the 0 position, but since
3735 // there is a second one, we copy the second on the
3736 // first. We're assuming there are at most two of
3737 // these, which there should be.
3738 // FIXME: why does it make sense to do that rather
3739 // than keep the first? (JMarc)
3740 Inset * inset = releaseInset(bibitem_pos);
3741 d->insetlist_.begin()->inset = inset;
3742 return -bibitem_pos;
3745 // We need to create an inset at the beginning
3746 Inset * inset = nullptr;
3747 if (bibitem_pos > 0) {
3748 // there was one somewhere in the paragraph, let's move it
3749 inset = d->insetlist_.release(bibitem_pos);
3750 eraseChar(bibitem_pos, track_changes);
3753 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
3754 InsetCommandParams(BIBITEM_CODE));
3756 Font font(inherit_font, buffer.params().language);
3757 insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
3758 : Change::UNCHANGED));
3760 // This is needed to get the counters right
3761 buffer.updateBuffer();
3766 void Paragraph::checkAuthors(AuthorList const & authorList)
3768 d->changes_.checkAuthors(authorList);
3772 bool Paragraph::isChanged(pos_type pos) const
3774 return lookupChange(pos).changed();
3778 bool Paragraph::isInserted(pos_type pos) const
3780 return lookupChange(pos).inserted();
3784 bool Paragraph::isDeleted(pos_type pos) const
3786 return lookupChange(pos).deleted();
3790 InsetList const & Paragraph::insetList() const
3792 return d->insetlist_;
3796 void Paragraph::setInsetBuffers(Buffer & b)
3798 d->insetlist_.setBuffer(b);
3802 void Paragraph::resetBuffer()
3804 d->insetlist_.resetBuffer();
3808 Inset * Paragraph::releaseInset(pos_type pos)
3810 Inset * inset = d->insetlist_.release(pos);
3811 /// does not honour change tracking!
3812 eraseChar(pos, false);
3817 Inset * Paragraph::getInset(pos_type pos)
3819 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3820 ? d->insetlist_.get(pos) : 0;
3824 Inset const * Paragraph::getInset(pos_type pos) const
3826 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3827 ? d->insetlist_.get(pos) : 0;
3831 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
3832 pos_type & right, TextCase action)
3834 // process sequences of modified characters; in change
3835 // tracking mode, this approach results in much better
3836 // usability than changing case on a char-by-char basis
3837 // We also need to track the current font, since font
3838 // changes within sequences can occur.
3839 vector<pair<char_type, Font> > changes;
3841 bool const trackChanges = bparams.track_changes;
3843 bool capitalize = true;
3845 for (; pos < right; ++pos) {
3846 char_type oldChar = d->text_[pos];
3847 char_type newChar = oldChar;
3849 // ignore insets and don't play with deleted text!
3850 if (oldChar != META_INSET && !isDeleted(pos)) {
3852 case text_lowercase:
3853 newChar = lowercase(oldChar);
3855 case text_capitalization:
3857 newChar = uppercase(oldChar);
3861 case text_uppercase:
3862 newChar = uppercase(oldChar);
3867 if (isWordSeparator(pos) || isDeleted(pos)) {
3868 // permit capitalization again
3872 if (oldChar != newChar) {
3873 changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
3874 if (pos != right - 1)
3876 // step behind the changing area
3880 int erasePos = pos - changes.size();
3881 for (size_t i = 0; i < changes.size(); i++) {
3882 insertChar(pos, changes[i].first,
3885 if (!eraseChar(erasePos, trackChanges)) {
3888 ++right; // expand selection
3896 int Paragraph::find(docstring const & str, bool cs, bool mw,
3897 pos_type start_pos, bool del) const
3899 pos_type pos = start_pos;
3900 int const strsize = str.length();
3902 pos_type const parsize = d->text_.size();
3903 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
3904 // Ignore "invisible" letters such as ligature breaks
3905 // and hyphenation chars while searching
3906 while (pos < parsize - 1 && isInset(pos)) {
3907 odocstringstream os;
3908 getInset(pos)->toString(os);
3909 if (!getInset(pos)->isLetter() || !os.str().empty())
3913 if (cs && str[i] != d->text_[pos])
3915 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
3917 if (!del && isDeleted(pos))
3924 // if necessary, check whether string matches word
3926 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
3929 && !isWordSeparator(pos))
3933 return pos - start_pos;
3937 char_type Paragraph::getChar(pos_type pos) const
3939 return d->text_[pos];
3943 pos_type Paragraph::size() const
3945 return d->text_.size();
3949 bool Paragraph::empty() const
3951 return d->text_.empty();
3955 bool Paragraph::isInset(pos_type pos) const
3957 return d->text_[pos] == META_INSET;
3961 bool Paragraph::isSeparator(pos_type pos) const
3963 //FIXME: Are we sure this can be the only separator?
3964 return d->text_[pos] == ' ';
3968 void Paragraph::deregisterWords()
3970 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3971 Private::LangWordsMap::const_iterator ite = d->words_.end();
3972 for (; itl != ite; ++itl) {
3973 WordList & wl = theWordList(itl->first);
3974 Private::Words::const_iterator it = (itl->second).begin();
3975 Private::Words::const_iterator et = (itl->second).end();
3976 for (; it != et; ++it)
3983 void Paragraph::locateWord(pos_type & from, pos_type & to,
3984 word_location const loc) const
3987 case WHOLE_WORD_STRICT:
3988 if (from == 0 || from == size()
3989 || isWordSeparator(from)
3990 || isWordSeparator(from - 1)) {
3997 // If we are already at the beginning of a word, do nothing
3998 if (!from || isWordSeparator(from - 1))
4003 // always move the cursor to the beginning of previous word
4004 while (from && !isWordSeparator(from - 1))
4008 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
4011 // no need to move the 'from' cursor
4015 while (to < size() && !isWordSeparator(to))
4020 void Paragraph::collectWords()
4022 for (pos_type pos = 0; pos < size(); ++pos) {
4023 if (isWordSeparator(pos))
4025 pos_type from = pos;
4026 locateWord(from, pos, WHOLE_WORD);
4027 // Work around MSVC warning: The statement
4028 // if (pos < from + lyxrc.completion_minlength)
4029 // triggers a signed vs. unsigned warning.
4030 // I don't know why this happens, it could be a MSVC bug, or
4031 // related to LLP64 (windows) vs. LP64 (unix) programming
4032 // model, or the C++ standard might be ambigous in the section
4033 // defining the "usual arithmetic conversions". However, using
4034 // a temporary variable is safe and works on all compilers.
4035 pos_type const endpos = from + lyxrc.completion_minlength;
4038 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
4039 if (cit == d->fontlist_.end())
4041 Language const * lang = cit->font().language();
4042 docstring const word = asString(from, pos, AS_STR_NONE);
4043 d->words_[lang->lang()].insert(word);
4048 void Paragraph::registerWords()
4050 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4051 Private::LangWordsMap::const_iterator ite = d->words_.end();
4052 for (; itl != ite; ++itl) {
4053 WordList & wl = theWordList(itl->first);
4054 Private::Words::const_iterator it = (itl->second).begin();
4055 Private::Words::const_iterator et = (itl->second).end();
4056 for (; it != et; ++it)
4062 void Paragraph::updateWords()
4070 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
4072 SkipPositionsIterator begin = skips.begin();
4073 SkipPositions::iterator end = skips.end();
4074 if (pos > 0 && begin < end) {
4076 if (end->last == pos - 1) {
4081 skips.insert(end, FontSpan(pos, pos));
4085 Language * Paragraph::Private::locateSpellRange(
4086 pos_type & from, pos_type & to,
4087 SkipPositions & skips) const
4089 // skip leading white space
4090 while (from < to && owner_->isWordSeparator(from))
4092 // don't check empty range
4095 // get current language
4096 Language * lang = getSpellLanguage(from);
4097 pos_type last = from;
4098 bool samelang = true;
4099 bool sameinset = true;
4100 while (last < to && samelang && sameinset) {
4101 // hop to end of word
4102 while (last < to && !owner_->isWordSeparator(last)) {
4103 if (owner_->getInset(last)) {
4104 appendSkipPosition(skips, last);
4105 } else if (owner_->isDeleted(last)) {
4106 appendSkipPosition(skips, last);
4110 // hop to next word while checking for insets
4111 while (sameinset && last < to && owner_->isWordSeparator(last)) {
4112 if (Inset const * inset = owner_->getInset(last))
4113 sameinset = inset->isChar() && inset->isLetter();
4114 if (sameinset && owner_->isDeleted(last)) {
4115 appendSkipPosition(skips, last);
4120 if (sameinset && last < to) {
4121 // now check for language change
4122 samelang = lang == getSpellLanguage(last);
4125 // if language change detected backstep is needed
4133 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
4136 const_cast<Language *>(owner_->getFontSettings(
4137 inset_owner_->buffer().params(), from).language());
4138 if (lang == inset_owner_->buffer().params().language
4139 && !lyxrc.spellchecker_alt_lang.empty()) {
4141 string const lang_variety =
4142 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
4143 lang->setCode(lang_code);
4144 lang->setVariety(lang_variety);
4150 void Paragraph::requestSpellCheck(pos_type pos)
4152 d->requestSpellCheck(pos);
4156 bool Paragraph::needsSpellCheck() const
4158 SpellChecker::ChangeNumber speller_change_number = 0;
4159 if (theSpellChecker())
4160 speller_change_number = theSpellChecker()->changeNumber();
4161 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
4162 d->speller_state_.needsCompleteRefresh(speller_change_number);
4164 return d->needsSpellCheck();
4168 bool Paragraph::Private::ignoreWord(docstring const & word) const
4170 // Ignore words with digits
4171 // FIXME: make this customizable
4172 // (note that some checkers ignore words with digits by default)
4173 docstring::const_iterator cit = word.begin();
4174 docstring::const_iterator const end = word.end();
4175 for (; cit != end; ++cit) {
4176 if (isNumber((*cit)))
4183 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
4184 WordLangTuple & wl, docstring_list & suggestions,
4185 bool do_suggestion, bool check_learned) const
4187 SpellChecker::Result result = SpellChecker::WORD_OK;
4188 SpellChecker * speller = theSpellChecker();
4192 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
4195 locateWord(from, to, WHOLE_WORD);
4196 if (from == to || from >= size())
4199 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4200 Language * lang = d->getSpellLanguage(from);
4202 if (getFontSettings(d->inset_owner_->buffer().params(), from).fontInfo().nospellcheck() == FONT_ON)
4205 wl = WordLangTuple(word, lang);
4210 if (needsSpellCheck() || check_learned) {
4212 if (!d->ignoreWord(word)) {
4213 bool const trailing_dot = to < size() && d->text_[to] == '.';
4214 result = speller->check(wl);
4215 if (SpellChecker::misspelled(result) && trailing_dot) {
4216 wl = WordLangTuple(word.append(from_ascii(".")), lang);
4217 result = speller->check(wl);
4218 if (!SpellChecker::misspelled(result)) {
4219 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
4221 from << ".." << to << "]");
4223 // spell check with dot appended failed too
4224 // restore original word/lang value
4225 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4226 wl = WordLangTuple(word, lang);
4230 if (!SpellChecker::misspelled(result)) {
4231 // area up to the begin of the next word is not misspelled
4232 while (end < size() && isWordSeparator(end))
4235 d->setMisspelled(from, end, result);
4237 result = d->speller_state_.getState(from);
4241 suggestions.clear();
4243 if (SpellChecker::misspelled(result)) {
4244 LYXERR(Debug::GUI, "misspelled word: \"" <<
4246 from << ".." << to << "]");
4248 speller->suggest(wl, suggestions);
4254 void Paragraph::anonymize()
4256 // This is a very crude anonymization for now
4257 for (char_type & c : d->text_)
4258 if (isLetterChar(c) || isNumber(c))
4263 void Paragraph::Private::markMisspelledWords(
4264 pos_type const & first, pos_type const & last,
4265 SpellChecker::Result result,
4266 docstring const & word,
4267 SkipPositions const & skips)
4269 if (!SpellChecker::misspelled(result)) {
4270 setMisspelled(first, last, SpellChecker::WORD_OK);
4274 SpellChecker * speller = theSpellChecker();
4275 // locate and enumerate the error positions
4276 int nerrors = speller->numMisspelledWords();
4278 SkipPositionsIterator it = skips.begin();
4279 SkipPositionsIterator et = skips.end();
4280 for (int index = 0; index < nerrors; ++index) {
4283 speller->misspelledWord(index, wstart, wlen);
4284 /// should not happen if speller supports range checks
4285 if (!wlen) continue;
4286 docstring const misspelled = word.substr(wstart, wlen);
4287 wstart += first + numskipped;
4288 if (snext < wstart) {
4289 /// mark the range of correct spelling
4290 numskipped += countSkips(it, et, wstart);
4291 setMisspelled(snext,
4292 wstart - 1, SpellChecker::WORD_OK);
4294 snext = wstart + wlen;
4295 numskipped += countSkips(it, et, snext);
4296 /// mark the range of misspelling
4297 setMisspelled(wstart, snext, result);
4298 LYXERR(Debug::GUI, "misspelled word: \"" <<
4299 misspelled << "\" [" <<
4300 wstart << ".." << (snext-1) << "]");
4303 if (snext <= last) {
4304 /// mark the range of correct spelling at end
4305 setMisspelled(snext, last, SpellChecker::WORD_OK);
4310 void Paragraph::spellCheck() const
4312 SpellChecker * speller = theSpellChecker();
4313 if (!speller || empty() ||!needsSpellCheck())
4317 d->rangeOfSpellCheck(start, endpos);
4318 if (speller->canCheckParagraph()) {
4319 // loop until we leave the range
4320 for (pos_type first = start; first < endpos; ) {
4321 pos_type last = endpos;
4322 Private::SkipPositions skips;
4323 Language * lang = d->locateSpellRange(first, last, skips);
4324 if (first >= endpos)
4326 // start the spell checker on the unit of meaning
4327 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
4328 WordLangTuple wl = WordLangTuple(word, lang);
4329 SpellChecker::Result result = word.size() ?
4330 speller->check(wl) : SpellChecker::WORD_OK;
4331 d->markMisspelledWords(first, last, result, word, skips);
4335 static docstring_list suggestions;
4336 pos_type to = endpos;
4337 while (start < endpos) {
4339 spellCheck(start, to, wl, suggestions, false);
4343 d->readySpellCheck();
4347 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
4349 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
4350 if (result || pos <= 0 || pos > size())
4352 if (check_boundary && (pos == size() || isWordSeparator(pos)))
4353 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
4358 string Paragraph::magicLabel() const
4361 ss << "magicparlabel-" << id();