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(otexstream & os, char_type c, char_type next,
318 OutputParams const &);
320 /// Output a space in appropriate formatting (or a surrogate pair
321 /// if the next character is a combining character).
322 /// \return whether a surrogate pair was output.
323 bool simpleTeXBlanks(OutputParams const &,
326 unsigned int & column,
328 Layout const & style);
330 /// Output consecutive unicode chars, belonging to the same script as
331 /// specified by the latex macro \p ltx, to \p os starting from \p i.
332 /// \return the number of characters written.
333 int writeScriptChars(OutputParams const &, otexstream & os,
334 docstring const & ltx,
335 Change const &, Encoding const &,
336 std::string const, pos_type & i);
338 /// This could go to ParagraphParameters if we want to.
339 int startTeXParParams(BufferParams const &, otexstream &,
340 OutputParams const &) const;
342 /// This could go to ParagraphParameters if we want to.
343 bool endTeXParParams(BufferParams const &, otexstream &,
344 OutputParams const &) const;
347 void latexInset(BufferParams const &,
352 Font const & outerfont,
354 Change & running_change,
355 Layout const & style,
357 unsigned int & column);
360 void latexSpecialChar(
362 BufferParams const & bparams,
363 OutputParams const & runparams,
364 Font const & running_font,
365 Change const & running_change,
366 Layout const & style,
369 unsigned int & column);
376 unsigned int & column);
382 unsigned int & column);
388 unsigned int & column);
391 void validate(LaTeXFeatures & features) const;
393 /// Checks if the paragraph contains only text and no inset or font change.
394 bool onlyText(Buffer const & buf, Font const & outerfont,
395 pos_type initial) const;
397 /// a vector of speller skip positions
398 typedef vector<FontSpan> SkipPositions;
399 typedef SkipPositions::const_iterator SkipPositionsIterator;
401 void appendSkipPosition(SkipPositions & skips, pos_type const pos) const;
403 Language * getSpellLanguage(pos_type const from) const;
405 Language * locateSpellRange(pos_type & from, pos_type & to,
406 SkipPositions & skips) const;
408 bool hasSpellerChange() const
410 SpellChecker::ChangeNumber speller_change_number = 0;
411 if (theSpellChecker())
412 speller_change_number = theSpellChecker()->changeNumber();
413 return speller_change_number > speller_state_.currentChangeNumber();
416 bool ignoreWord(docstring const & word) const ;
418 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
420 pos_type textsize = owner_->size();
421 // check for sane arguments
422 if (to <= from || from >= textsize)
424 FontSpan fp = FontSpan(from, to - 1);
425 speller_state_.setRange(fp, state);
428 void requestSpellCheck(pos_type pos)
431 speller_state_.needsCompleteRefresh(speller_state_.currentChangeNumber());
433 speller_state_.needsRefresh(pos);
436 void readySpellCheck()
438 speller_state_.needsRefresh(-1);
441 bool needsSpellCheck() const
443 return speller_state_.needsRefresh();
446 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
448 speller_state_.refreshRange(first, last);
450 last = owner_->size();
453 pos_type endpos = last;
454 owner_->locateWord(first, endpos, WHOLE_WORD);
457 owner_->locateWord(last, endpos, WHOLE_WORD);
462 int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
466 while (it != et && it->first < start) {
467 int skip = it->last - it->first + 1;
475 void markMisspelledWords(pos_type const & first, pos_type const & last,
476 SpellChecker::Result result,
477 docstring const & word,
478 SkipPositions const & skips);
480 InsetCode ownerCode() const
482 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
485 /// Which Paragraph owns us?
489 Inset const * inset_owner_;
498 ParagraphParameters params_;
500 /// for recording and looking up changes
504 InsetList insetlist_;
507 pos_type begin_of_body_;
509 typedef docstring TextContainer;
513 typedef set<docstring> Words;
514 typedef map<string, Words> LangWordsMap;
518 Layout const * layout_;
520 SpellCheckerState speller_state_;
524 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
525 : owner_(owner), inset_owner_(0), id_(-1), begin_of_body_(0), layout_(&layout)
532 int Paragraph::Private::make_id()
534 // The id is unique per session across buffers because it is used in
535 // LFUN_PARAGRAPH_GOTO to switch to a different buffer, for instance in the
538 static atomic_uint next_id(0);
543 Paragraph::Private::Private(Private const & p, Paragraph * owner)
544 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
546 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
547 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
550 requestSpellCheck(p.text_.size());
554 Paragraph::Private::Private(Private const & p, Paragraph * owner,
555 pos_type beg, pos_type end)
556 : owner_(owner), inset_owner_(p.inset_owner_), id_(make_id()),
557 params_(p.params_), changes_(p.changes_),
558 insetlist_(p.insetlist_, beg, end),
559 begin_of_body_(p.begin_of_body_), words_(p.words_),
562 if (beg >= pos_type(p.text_.size()))
564 text_ = p.text_.substr(beg, end - beg);
566 FontList::const_iterator fcit = fontlist_.begin();
567 FontList::const_iterator fend = fontlist_.end();
568 for (; fcit != fend; ++fcit) {
569 if (fcit->pos() < beg)
571 if (fcit->pos() >= end) {
572 // Add last entry in the fontlist_.
573 fontlist_.set(text_.size() - 1, fcit->font());
576 // Add a new entry in the fontlist_.
577 fontlist_.set(fcit->pos() - beg, fcit->font());
579 requestSpellCheck(p.text_.size());
583 void Paragraph::addChangesToToc(DocIterator const & cdit, Buffer const & buf,
584 bool output_active, TocBackend & backend) const
586 d->changes_.addToToc(cdit, buf, output_active, backend);
590 void Paragraph::addChangesToBuffer(Buffer const & buf) const
592 d->changes_.updateBuffer(buf);
596 bool Paragraph::isChangeUpdateRequired() const
598 return d->changes_.isUpdateRequired();
602 bool Paragraph::isDeleted(pos_type start, pos_type end) const
604 LASSERT(start >= 0 && start <= size(), return false);
605 LASSERT(end > start && end <= size() + 1, return false);
607 return d->changes_.isDeleted(start, end);
611 bool Paragraph::isChanged(pos_type start, pos_type end) const
613 LASSERT(start >= 0 && start <= size(), return false);
614 LASSERT(end > start && end <= size() + 1, return false);
616 return d->changes_.isChanged(start, end);
620 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
622 // keep the logic here in sync with the logic of eraseChars()
626 Change const & change = d->changes_.lookup(size());
627 return change.inserted() && change.currentAuthor();
631 void Paragraph::setChange(Change const & change)
633 // beware of the imaginary end-of-par character!
634 d->changes_.set(change, 0, size() + 1);
637 * Propagate the change recursively - but not in case of DELETED!
639 * Imagine that your co-author makes changes in an existing inset. He
640 * sends your document to you and you come to the conclusion that the
641 * inset should go completely. If you erase it, LyX must not delete all
642 * text within the inset. Otherwise, the change tracked insertions of
643 * your co-author get lost and there is no way to restore them later.
645 * Conclusion: An inset's content should remain untouched if you delete it
648 if (!change.deleted()) {
649 for (pos_type pos = 0; pos < size(); ++pos) {
650 if (Inset * inset = getInset(pos))
651 inset->setChange(change);
657 void Paragraph::setChange(pos_type pos, Change const & change)
659 LASSERT(pos >= 0 && pos <= size(), return);
660 d->changes_.set(change, pos);
662 // see comment in setChange(Change const &) above
663 if (!change.deleted() && pos < size())
664 if (Inset * inset = getInset(pos))
665 inset->setChange(change);
669 Change const & Paragraph::lookupChange(pos_type pos) const
671 LBUFERR(pos >= 0 && pos <= size());
672 return d->changes_.lookup(pos);
676 void Paragraph::acceptChanges(pos_type start, pos_type end)
678 LASSERT(start >= 0 && start <= size(), return);
679 LASSERT(end > start && end <= size() + 1, return);
681 for (pos_type pos = start; pos < end; ++pos) {
682 switch (lookupChange(pos).type) {
683 case Change::UNCHANGED:
684 // accept changes in nested inset
685 if (Inset * inset = getInset(pos))
686 inset->acceptChanges();
689 case Change::INSERTED:
690 d->changes_.set(Change(Change::UNCHANGED), pos);
691 // also accept changes in nested inset
692 if (Inset * inset = getInset(pos))
693 inset->acceptChanges();
696 case Change::DELETED:
697 // Suppress access to non-existent
698 // "end-of-paragraph char"
700 eraseChar(pos, false);
711 void Paragraph::rejectChanges(pos_type start, pos_type end)
713 LASSERT(start >= 0 && start <= size(), return);
714 LASSERT(end > start && end <= size() + 1, return);
716 for (pos_type pos = start; pos < end; ++pos) {
717 switch (lookupChange(pos).type) {
718 case Change::UNCHANGED:
719 // reject changes in nested inset
720 if (Inset * inset = getInset(pos))
721 inset->rejectChanges();
724 case Change::INSERTED:
725 // Suppress access to non-existent
726 // "end-of-paragraph char"
728 eraseChar(pos, false);
734 case Change::DELETED:
735 d->changes_.set(Change(Change::UNCHANGED), pos);
737 // Do NOT reject changes within a deleted inset!
738 // There may be insertions of a co-author inside of it!
746 void Paragraph::Private::insertChar(pos_type pos, char_type c,
747 Change const & change)
749 LASSERT(pos >= 0 && pos <= int(text_.size()), return);
752 changes_.insert(change, pos);
754 // This is actually very common when parsing buffers (and
755 // maybe inserting ascii text)
756 if (pos == pos_type(text_.size())) {
757 // when appending characters, no need to update tables
759 // but we want spell checking
760 requestSpellCheck(pos);
764 text_.insert(text_.begin() + pos, c);
766 // Update the font table.
767 fontlist_.increasePosAfterPos(pos);
770 insetlist_.increasePosAfterPos(pos);
772 // Update list of misspelled positions
773 speller_state_.increasePosAfterPos(pos);
777 bool Paragraph::insertInset(pos_type pos, Inset * inset,
778 Font const & font, Change const & change)
780 LASSERT(inset, return false);
781 LASSERT(pos >= 0 && pos <= size(), return false);
783 // Paragraph::insertInset() can be used in cut/copy/paste operation where
784 // d->inset_owner_ is not set yet.
785 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
788 d->insertChar(pos, META_INSET, change);
789 LASSERT(d->text_[pos] == META_INSET, return false);
791 // Add a new entry in the insetlist_.
792 d->insetlist_.insert(inset, pos);
794 // Some insets require run of spell checker
795 requestSpellCheck(pos);
801 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
803 LASSERT(pos >= 0 && pos <= size(), return false);
805 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
808 Change change = d->changes_.lookup(pos);
810 // set the character to DELETED if
811 // a) it was previously unchanged or
812 // b) it was inserted by a co-author
814 if (!change.changed() ||
815 (change.inserted() && !change.currentAuthor())) {
816 setChange(pos, Change(Change::DELETED));
817 // request run of spell checker
818 requestSpellCheck(pos);
822 if (change.deleted())
826 // Don't physically access the imaginary end-of-paragraph character.
827 // eraseChar() can only mark it as DELETED. A physical deletion of
828 // end-of-par must be handled externally.
834 d->changes_.erase(pos);
836 // if it is an inset, delete the inset entry
837 if (d->text_[pos] == META_INSET)
838 d->insetlist_.erase(pos);
840 d->text_.erase(d->text_.begin() + pos);
842 // Update the fontlist_
843 d->fontlist_.erase(pos);
845 // Update the insetlist_
846 d->insetlist_.decreasePosAfterPos(pos);
848 // Update list of misspelled positions
849 d->speller_state_.decreasePosAfterPos(pos);
850 d->speller_state_.refreshLast(size());
856 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
858 LASSERT(start >= 0 && start <= size(), return 0);
859 LASSERT(end >= start && end <= size() + 1, return 0);
862 for (pos_type count = end - start; count; --count) {
863 if (!eraseChar(i, trackChanges))
870 int Paragraph::Private::latexSurrogatePair(otexstream & os, char_type c,
871 char_type next, OutputParams const & runparams)
873 // Writing next here may circumvent a possible font change between
874 // c and next. Since next is only output if it forms a surrogate pair
875 // with c we can ignore this:
876 // A font change inside a surrogate pair does not make sense and is
877 // hopefully impossible to input.
878 // FIXME: change tracking
879 // Is this correct WRT change tracking?
880 Encoding const & encoding = *(runparams.encoding);
881 docstring latex1 = encoding.latexChar(next).first;
882 if (runparams.inIPA) {
883 string const tipashortcut = Encodings::TIPAShortcut(next);
884 if (!tipashortcut.empty()) {
885 latex1 = from_ascii(tipashortcut);
888 docstring latex2 = encoding.latexChar(c).first;
890 if (docstring(1, next) == latex1) {
891 // The encoding supports the combination:
892 // output as is (combining char after base char).
893 os << latex2 << latex1;
894 return latex1.length() + latex2.length();
897 // Handle combining characters in "script" context (i.e., \textgreek and \textcyrillic)
898 docstring::size_type const brace1 = latex2.find_first_of(from_ascii("{"));
899 docstring::size_type const brace2 = latex2.find_last_of(from_ascii("}"));
900 string script = to_ascii(latex2.substr(1, brace1 - 1));
901 // "Script chars" need to embraced in \textcyrillic and \textgreek notwithstanding
902 // whether they are encodable or not (it only depends on the font encoding)
903 if (!runparams.isFullUnicode())
904 // This will get us a script value to deal with below
905 Encodings::isKnownScriptChar(c, script);
909 if (runparams.local_font)
910 fontenc = runparams.local_font->language()->fontenc();
912 fontenc = runparams.main_fontenc;
913 docstring scriptmacro;
915 if (script == "textgreek" || script == "textcyrillic") {
916 // We separate the script macro (\text[greek|cyr]) from the rest,
917 // since we need to include the combining char in it (#6463).
918 // This is "the rest":
921 latex2 = latex2.substr(pos, length);
922 // We only need the script macro with non-native font encodings
923 if (Encodings::needsScriptWrapper(script, fontenc)) {
924 scriptmacro = from_ascii("\\" + script + "{");
925 cb = from_ascii("}");
931 // polutonikogreek does not play nice with brackets
932 if (!runparams.local_font
933 || runparams.local_font->language()->lang() != "polutonikogreek") {
934 lb = from_ascii("{");
935 rb = from_ascii("}");
938 os << scriptmacro << latex1 << lb << latex2 << rb << cb;
939 return latex1.length() + latex2.length() + lb.length() + rb.length() + cb.length();
943 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
946 unsigned int & column,
948 Layout const & style)
950 if (style.pass_thru || runparams.pass_thru)
953 if (i + 1 < int(text_.size())) {
954 char_type next = text_[i + 1];
955 if (Encodings::isCombiningChar(next)) {
956 // This space has an accent, so we must always output it.
957 column += latexSurrogatePair(os, ' ', next, runparams) - 1;
962 if (runparams.linelen > 0
963 && column > runparams.linelen
965 && text_[i - 1] != ' '
966 && (i + 1 < int(text_.size()))
967 // same in FreeSpacing mode
968 && !owner_->isFreeSpacing()
969 // In typewriter mode, we want to avoid
970 // ! . ? : at the end of a line
971 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
972 && (text_[i - 1] == '.'
973 || text_[i - 1] == '?'
974 || text_[i - 1] == ':'
975 || text_[i - 1] == '!'))) {
977 os.texrow().start(owner_->id(), i + 1);
979 } else if (style.free_spacing) {
988 int Paragraph::Private::writeScriptChars(OutputParams const & runparams,
990 docstring const & ltx,
991 Change const & runningChange,
992 Encoding const & encoding,
993 string const fontenc,
996 // FIXME: modifying i here is not very nice...
998 // We only arrive here when character text_[i] could not be translated
999 // into the current latex encoding (or its latex translation has been forced,)
1000 // and it belongs to a known script.
1001 // Parameter ltx contains the latex translation of text_[i] as specified
1002 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
1003 // The latex macro name "textXXX" specifies the script to which text_[i]
1004 // belongs and we use it in order to check whether characters from the
1005 // same script immediately follow, such that we can collect them in a
1006 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
1007 // for the first char but only "<spec>" for all subsequent chars.
1008 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
1009 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
1010 string script = to_ascii(ltx.substr(1, brace1 - 1));
1012 int length = brace2;
1013 bool closing_brace = true;
1014 if (!Encodings::needsScriptWrapper(script, fontenc)) {
1015 // Correct font encoding is being used, so we can avoid \text[greek|cyr].
1018 closing_brace = false;
1020 os << ltx.substr(pos, length);
1021 int size = text_.size();
1022 while (i + 1 < size) {
1023 char_type const next = text_[i + 1];
1024 // Stop here if next character belongs to another script
1025 // or there is a change in change tracking status.
1026 if (!Encodings::isKnownScriptChar(next, script) ||
1027 runningChange != owner_->lookupChange(i + 1))
1031 FontList::const_iterator cit = fontlist_.begin();
1032 FontList::const_iterator end = fontlist_.end();
1033 for (; cit != end; ++cit) {
1034 if (cit->pos() >= i && !found) {
1035 prev_font = cit->font();
1038 if (cit->pos() >= i + 1)
1041 // Stop here if there is a font attribute or encoding change.
1042 if (found && cit != end && prev_font != cit->font())
1045 // Check whether we have a combining pair
1046 char_type next_next = '\0';
1048 next_next = text_[i + 2];
1049 if (Encodings::isCombiningChar(next_next)) {
1050 length += latexSurrogatePair(os, next, next_next, runparams) - 1;
1056 docstring const latex = encoding.latexChar(next).first;
1057 docstring::size_type const b1 =
1058 latex.find_first_of(from_ascii("{"));
1059 docstring::size_type const b2 =
1060 latex.find_last_of(from_ascii("}"));
1061 int const len = b2 - b1 - 1;
1062 os << latex.substr(b1 + 1, len);
1066 if (closing_brace) {
1074 void Paragraph::Private::latexInset(BufferParams const & bparams,
1076 OutputParams & runparams,
1077 Font & running_font,
1079 Font const & outerfont,
1081 Change & running_change,
1082 Layout const & style,
1084 unsigned int & column)
1086 Inset * inset = owner_->getInset(i);
1089 if (style.pass_thru) {
1090 odocstringstream ods;
1091 inset->plaintext(ods, runparams);
1096 // FIXME: move this to InsetNewline::latex
1097 if (inset->lyxCode() == NEWLINE_CODE || inset->lyxCode() == SEPARATOR_CODE) {
1098 // newlines are handled differently here than
1099 // the default in simpleTeXSpecialChars().
1100 if (!style.newline_allowed) {
1104 bool needPar = false;
1105 column += running_font.latexWriteEndChanges(
1106 os, bparams, runparams,
1107 basefont, basefont, needPar);
1111 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
1114 basefont = owner_->getLayoutFont(bparams, outerfont);
1115 running_font = basefont;
1117 if (runparams.moving_arg)
1121 os.texrow().start(owner_->id(), i + 1);
1125 if (owner_->isDeleted(i)) {
1126 if( ++runparams.inDeletedInset == 1)
1127 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1130 if (inset->canTrackChanges()) {
1131 column += Changes::latexMarkChange(os, bparams, running_change,
1132 Change(Change::UNCHANGED), runparams);
1133 running_change = Change(Change::UNCHANGED);
1137 odocstream::pos_type const len = os.os().tellp();
1139 if (inset->forceLTR()
1140 && !runparams.use_polyglossia
1141 && running_font.isRightToLeft()
1142 // ERT is an exception, it should be output with no
1143 // decorations at all
1144 && inset->lyxCode() != ERT_CODE) {
1145 if (running_font.language()->lang() == "farsi")
1146 os << "\\beginL" << termcmd;
1152 // FIXME: Bug: we can have an empty font change here!
1153 // if there has just been a font change, we are going to close it
1154 // right now, which means stupid latex code like \textsf{}. AFAIK,
1155 // this does not harm dvi output. A minor bug, thus (JMarc)
1157 // Some insets cannot be inside a font change command.
1158 // However, even such insets *can* be placed in \L or \R
1159 // or their equivalents (for RTL language switches), so we don't
1160 // close the language in those cases.
1161 // ArabTeX, though, cannot handle this special behavior, it seems.
1162 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
1163 || running_font.language()->lang() == "arabic_arabtex";
1164 if (open_font && !inset->inheritFont()) {
1165 bool needPar = false;
1166 bool closeLanguage = arabtex
1167 || basefont.isRightToLeft() == running_font.isRightToLeft();
1168 unsigned int count = running_font.latexWriteEndChanges(os,
1169 bparams, runparams, basefont, basefont,
1170 needPar, closeLanguage);
1172 // if any font properties were closed, update the running_font,
1173 // making sure, however, to leave the language as it was
1175 // FIXME: probably a better way to keep track of the old
1176 // language, than copying the entire font?
1177 Font const copy_font(running_font);
1178 basefont = owner_->getLayoutFont(bparams, outerfont);
1179 running_font = basefont;
1181 running_font.setLanguage(copy_font.language());
1182 // leave font open if language is still open
1183 open_font = (running_font.language() == basefont.language());
1185 runparams.local_font = &basefont;
1189 size_t const previous_row_count = os.texrow().rows();
1192 runparams.lastid = id_;
1193 runparams.lastpos = i;
1194 inset->latex(os, runparams);
1195 } catch (EncodingException & e) {
1196 // add location information and throw again.
1203 if (running_font.language()->lang() == "farsi")
1204 os << "\\endL" << termcmd;
1209 if (os.texrow().rows() > previous_row_count) {
1210 os.texrow().start(owner_->id(), i + 1);
1213 column += (unsigned int)(os.os().tellp() - len);
1216 if (owner_->isDeleted(i))
1217 --runparams.inDeletedInset;
1221 void Paragraph::Private::latexSpecialChar(otexstream & os,
1222 BufferParams const & bparams,
1223 OutputParams const & runparams,
1224 Font const & running_font,
1225 Change const & running_change,
1226 Layout const & style,
1229 unsigned int & column)
1231 // With polyglossia, brackets and stuff need not be reversed
1232 // in RTL scripts (see bug #8251)
1233 char_type const c = (runparams.use_polyglossia) ?
1234 owner_->getUChar(bparams, i) : text_[i];
1236 if (style.pass_thru || runparams.pass_thru
1237 || contains(style.pass_thru_chars, c)
1238 || contains(runparams.pass_thru_chars, c)) {
1240 Encoding const * const enc = runparams.encoding;
1241 if (enc && !enc->encodable(c))
1242 throw EncodingException(c);
1248 // TIPA uses its own T3 encoding
1249 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1251 // If T1 font encoding is used, use the special
1252 // characters it provides.
1253 // NOTE: Some languages reset the font encoding internally to a
1254 // non-standard font encoding. If we are using such a language,
1255 // we do not output special T1 chars.
1256 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1257 && !runparams.isFullUnicode() && bparams.main_font_encoding() == "T1"
1258 && latexSpecialT1(c, os, i, column))
1260 // NOTE: XeTeX and LuaTeX use EU1/2 (pre 2017) or TU (as of 2017) encoding
1261 else if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1262 && runparams.isFullUnicode() && latexSpecialTU(c, os, i, column))
1265 // Otherwise, we use what LaTeX provides us.
1268 os << "\\textbackslash" << termcmd;
1272 os << "\\textless" << termcmd;
1276 os << "\\textgreater" << termcmd;
1280 os << "\\textbar" << termcmd;
1285 if (i + 1 < static_cast<pos_type>(text_.size()) &&
1286 (end_pos == -1 || i + 1 < end_pos) &&
1287 text_[i+1] == '-') {
1288 // Prevent "--" becoming an en dash and "---" an em dash.
1289 // (Within \ttfamily, "---" is merged to en dash + hyphen.)
1295 os << "\\textquotedbl" << termcmd;
1300 case '%': case '#': case '{':
1308 os << "\\textasciitilde" << termcmd;
1313 os << "\\textasciicircum" << termcmd;
1320 // avoid being mistaken for optional arguments
1328 // Blanks are printed before font switching.
1329 // Sure? I am not! (try nice-latex)
1330 // I am sure it's correct. LyX might be smarter
1331 // in the future, but for now, nothing wrong is
1337 // XeTeX's dash behaviour is determined via a global setting
1338 if (bparams.use_dash_ligatures
1339 && owner_->getFontSettings(bparams, i).fontInfo().family() != TYPEWRITER_FAMILY
1341 // TODO #10961: && not in inset Flex Code
1342 // TODO #10961: && not in layout LyXCode
1343 && (!bparams.useNonTeXFonts || runparams.flavor != OutputParams::XETEX)) {
1360 Encoding const & encoding = *(runparams.encoding);
1361 char_type next = '\0';
1362 if (i + 1 < int(text_.size())) {
1363 next = text_[i + 1];
1364 if (Encodings::isCombiningChar(next)) {
1365 column += latexSurrogatePair(os, c, next, runparams) - 1;
1371 pair<docstring, bool> latex = encoding.latexChar(c);
1372 docstring nextlatex;
1373 bool nexttipas = false;
1374 string nexttipashortcut;
1375 if (next != '\0' && next != META_INSET && encoding.encodable(next)) {
1376 nextlatex = encoding.latexChar(next).first;
1377 if (runparams.inIPA) {
1378 nexttipashortcut = Encodings::TIPAShortcut(next);
1379 nexttipas = !nexttipashortcut.empty();
1383 if (runparams.inIPA) {
1384 string const tipashortcut = Encodings::TIPAShortcut(c);
1385 if (!tipashortcut.empty()) {
1386 latex.first = from_ascii(tipashortcut);
1387 latex.second = false;
1392 if (running_font.language()->lang() == bparams.language->lang())
1393 fontenc = runparams.main_fontenc;
1395 fontenc = running_font.language()->fontenc();
1396 // "Script chars" need to embraced in \textcyrillic and \textgreek notwithstanding
1397 // whether they are encodable or not (it only depends on the font encoding)
1398 if (!runparams.isFullUnicode() && Encodings::isKnownScriptChar(c, script)) {
1399 docstring const wrapper = from_ascii("\\" + script + "{");
1400 docstring ltx = latex.first;
1401 if (!prefixIs(ltx, wrapper))
1402 ltx = wrapper + latex.first + from_ascii("}");
1403 column += writeScriptChars(runparams, os, ltx, running_change,
1404 encoding, fontenc, i) - 1;
1405 } else if (latex.second
1406 && ((!prefixIs(nextlatex, '\\')
1407 && !prefixIs(nextlatex, '{')
1408 && !prefixIs(nextlatex, '}'))
1410 && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1412 // Prevent eating of a following
1413 // space or command corruption by
1414 // following characters
1415 if (next == ' ' || next == '\0') {
1416 column += latex.first.length() + 1;
1417 os << latex.first << "{}";
1419 column += latex.first.length();
1420 os << latex.first << " ";
1423 column += latex.first.length() - 1;
1431 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1432 pos_type i, unsigned int & column)
1438 // In T1 encoding, these characters exist
1439 // but we should avoid ligatures
1440 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1442 os << "\\textcompwordmark" << termcmd;
1449 // soul.sty breaks with \char`\"
1450 os << "\\textquotedbl" << termcmd;
1459 bool Paragraph::Private::latexSpecialTU(char_type const c, otexstream & os,
1460 pos_type i, unsigned int & column)
1462 // TU encoding is currently on par with T1.
1463 return latexSpecialT1(c, os, i, column);
1467 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1468 pos_type /*i*/, unsigned int & column)
1478 os << "\\textvertline" << termcmd;
1487 void Paragraph::Private::validate(LaTeXFeatures & features) const
1489 if (layout_->inpreamble && inset_owner_) {
1490 // FIXME: Using a string stream here circumvents the encoding
1491 // switching machinery of odocstream. Therefore the
1492 // output is wrong if this paragraph contains content
1493 // that needs to switch encoding.
1494 Buffer const & buf = inset_owner_->buffer();
1495 otexstringstream os;
1496 os << layout_->preamble();
1497 size_t const length = os.length();
1498 TeXOnePar(buf, buf.text(), buf.getParFromID(owner_->id()).pit(), os,
1499 features.runparams(), string(), 0, -1, true);
1500 if (os.length() > length)
1501 features.addPreambleSnippet(os.release(), true);
1504 if (features.runparams().flavor == OutputParams::HTML
1505 && layout_->htmltitle()) {
1506 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1509 // check the params.
1510 if (!params_.spacing().isDefault())
1511 features.require("setspace");
1514 features.useLayout(layout_->name());
1517 fontlist_.validate(features);
1519 // then the indentation
1520 if (!params_.leftIndent().zero())
1521 features.require("ParagraphLeftIndent");
1524 InsetList::const_iterator icit = insetlist_.begin();
1525 InsetList::const_iterator iend = insetlist_.end();
1526 for (; icit != iend; ++icit) {
1528 features.inDeletedInset(owner_->isDeleted(icit->pos));
1529 if (icit->inset->lyxCode() == FOOT_CODE) {
1530 // FIXME: an item inset would make things much easier.
1531 if ((layout_->latextype == LATEX_LIST_ENVIRONMENT
1532 || (layout_->latextype == LATEX_ITEM_ENVIRONMENT
1533 && layout_->margintype == MARGIN_FIRST_DYNAMIC))
1534 && (icit->pos < begin_of_body_
1535 || (icit->pos == begin_of_body_
1536 && (icit->pos == 0 || text_[icit->pos - 1] != ' '))))
1537 features.saveNoteEnv("description");
1539 icit->inset->validate(features);
1540 features.inDeletedInset(false);
1541 if (layout_->needprotect &&
1542 icit->inset->lyxCode() == FOOT_CODE)
1543 features.require("NeedLyXFootnoteCode");
1547 // then the contents
1548 BufferParams const bp = features.runparams().is_child
1549 ? features.buffer().masterParams() : features.buffer().params();
1550 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1551 char_type c = text_[i];
1553 if (features.runparams().isFullUnicode() && bp.useNonTeXFonts)
1554 features.require("textquotedblp");
1555 else if (bp.main_font_encoding() != "T1"
1556 || ((&owner_->getFontSettings(bp, i))->language()->internalFontEncoding()))
1557 features.require("textquotedbl");
1559 if (!bp.use_dash_ligatures
1560 && (c == 0x2013 || c == 0x2014)
1561 && bp.useNonTeXFonts
1562 && features.runparams().flavor == OutputParams::XETEX)
1563 // XeTeX's dash behaviour is determined via a global setting
1564 features.require("xetexdashbreakstate");
1565 BufferEncodings::validate(c, features);
1569 /////////////////////////////////////////////////////////////////////
1573 /////////////////////////////////////////////////////////////////////
1576 Layout const emptyParagraphLayout;
1579 Paragraph::Paragraph()
1580 : d(new Paragraph::Private(this, emptyParagraphLayout))
1587 Paragraph::Paragraph(Paragraph const & par)
1588 : itemdepth(par.itemdepth),
1589 d(new Paragraph::Private(*par.d, this))
1595 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1596 : itemdepth(par.itemdepth),
1597 d(new Paragraph::Private(*par.d, this, beg, end))
1603 Paragraph & Paragraph::operator=(Paragraph const & par)
1605 // needed as we will destroy the private part before copying it
1607 itemdepth = par.itemdepth;
1611 d = new Private(*par.d, this);
1618 Paragraph::~Paragraph()
1627 // this shall be called just before every "os << ..." action.
1628 void flushString(ostream & os, docstring & s)
1637 void Paragraph::write(ostream & os, BufferParams const & bparams,
1638 depth_type & dth) const
1640 // The beginning or end of a deeper (i.e. nested) area?
1641 if (dth != d->params_.depth()) {
1642 if (d->params_.depth() > dth) {
1643 while (d->params_.depth() > dth) {
1644 os << "\n\\begin_deeper";
1648 while (d->params_.depth() < dth) {
1649 os << "\n\\end_deeper";
1655 // First write the layout
1656 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1658 d->params_.write(os);
1660 Font font1(inherit_font, bparams.language);
1662 Change running_change = Change(Change::UNCHANGED);
1664 // this string is used as a buffer to avoid repetitive calls
1665 // to to_utf8(), which turn out to be expensive (JMarc)
1666 docstring write_buffer;
1669 for (pos_type i = 0; i <= size(); ++i) {
1671 Change const & change = lookupChange(i);
1672 if (change != running_change)
1673 flushString(os, write_buffer);
1674 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1675 running_change = change;
1680 // Write font changes
1681 Font font2 = getFontSettings(bparams, i);
1682 if (font2 != font1) {
1683 flushString(os, write_buffer);
1684 font2.lyxWriteChanges(font1, os);
1689 char_type const c = d->text_[i];
1692 if (Inset const * inset = getInset(i)) {
1693 flushString(os, write_buffer);
1694 if (inset->directWrite()) {
1695 // international char, let it write
1696 // code directly so it's shorter in
1702 os << "\\begin_inset ";
1704 os << "\n\\end_inset\n\n";
1707 // FIXME This can be removed again once the mystery
1708 // crash has been resolved.
1713 flushString(os, write_buffer);
1714 os << "\n\\backslash\n";
1718 flushString(os, write_buffer);
1719 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1726 if ((column > 70 && c == ' ')
1728 flushString(os, write_buffer);
1732 // this check is to amend a bug. LyX sometimes
1733 // inserts '\0' this could cause problems.
1735 write_buffer.push_back(c);
1737 LYXERR0("NUL char in structure.");
1743 flushString(os, write_buffer);
1744 os << "\n\\end_layout\n";
1745 // FIXME This can be removed again once the mystery
1746 // crash has been resolved.
1751 void Paragraph::validate(LaTeXFeatures & features) const
1753 d->validate(features);
1754 if (needsCProtection())
1755 features.require("cprotect");
1759 void Paragraph::insert(pos_type start, docstring const & str,
1760 Font const & font, Change const & change)
1762 for (size_t i = 0, n = str.size(); i != n ; ++i)
1763 insertChar(start + i, str[i], font, change);
1767 void Paragraph::appendChar(char_type c, Font const & font,
1768 Change const & change)
1771 d->changes_.insert(change, d->text_.size());
1772 // when appending characters, no need to update tables
1773 d->text_.push_back(c);
1774 setFont(d->text_.size() - 1, font);
1775 d->requestSpellCheck(d->text_.size() - 1);
1779 void Paragraph::appendString(docstring const & s, Font const & font,
1780 Change const & change)
1782 pos_type end = s.size();
1783 size_t oldsize = d->text_.size();
1784 size_t newsize = oldsize + end;
1785 size_t capacity = d->text_.capacity();
1786 if (newsize >= capacity)
1787 d->text_.reserve(max(capacity + 100, newsize));
1789 // when appending characters, no need to update tables
1792 // FIXME: Optimize this!
1793 for (size_t i = oldsize; i != newsize; ++i) {
1795 d->changes_.insert(change, i);
1796 d->requestSpellCheck(i);
1798 d->fontlist_.set(oldsize, font);
1799 d->fontlist_.set(newsize - 1, font);
1803 void Paragraph::insertChar(pos_type pos, char_type c,
1806 d->insertChar(pos, c, Change(trackChanges ?
1807 Change::INSERTED : Change::UNCHANGED));
1811 void Paragraph::insertChar(pos_type pos, char_type c,
1812 Font const & font, bool trackChanges)
1814 d->insertChar(pos, c, Change(trackChanges ?
1815 Change::INSERTED : Change::UNCHANGED));
1820 void Paragraph::insertChar(pos_type pos, char_type c,
1821 Font const & font, Change const & change)
1823 d->insertChar(pos, c, change);
1828 void Paragraph::resetFonts(Font const & font)
1830 d->fontlist_.clear();
1831 d->fontlist_.set(0, font);
1832 d->fontlist_.set(d->text_.size() - 1, font);
1835 // Gets uninstantiated font setting at position.
1836 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1840 LYXERR0("pos: " << pos << " size: " << size());
1844 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1845 if (cit != d->fontlist_.end())
1848 if (pos == size() && !empty())
1849 return getFontSettings(bparams, pos - 1);
1851 // Optimisation: avoid a full font instantiation if there is no
1852 // language change from previous call.
1853 static Font previous_font;
1854 static Language const * previous_lang = 0;
1855 Language const * lang = getParLanguage(bparams);
1856 if (lang != previous_lang) {
1857 previous_lang = lang;
1858 previous_font = Font(inherit_font, lang);
1860 return previous_font;
1864 FontSpan Paragraph::fontSpan(pos_type pos) const
1866 LBUFERR(pos <= size());
1869 return FontSpan(pos, pos);
1872 FontList::const_iterator cit = d->fontlist_.begin();
1873 FontList::const_iterator end = d->fontlist_.end();
1874 for (; cit != end; ++cit) {
1875 if (cit->pos() >= pos) {
1876 if (pos >= beginOfBody())
1877 return FontSpan(max(start, beginOfBody()),
1880 return FontSpan(start,
1881 min(beginOfBody() - 1,
1884 start = cit->pos() + 1;
1887 // This should not happen, but if so, we take no chances.
1888 LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1889 LASSERT(false, return FontSpan(pos, pos));
1893 // Gets uninstantiated font setting at position 0
1894 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1896 if (!empty() && !d->fontlist_.empty())
1897 return d->fontlist_.begin()->font();
1899 // Optimisation: avoid a full font instantiation if there is no
1900 // language change from previous call.
1901 static Font previous_font;
1902 static Language const * previous_lang = 0;
1903 if (bparams.language != previous_lang) {
1904 previous_lang = bparams.language;
1905 previous_font = Font(inherit_font, bparams.language);
1908 return previous_font;
1912 // Gets the fully instantiated font at a given position in a paragraph
1913 // This is basically the same function as Text::GetFont() in text2.cpp.
1914 // The difference is that this one is used for generating the LaTeX file,
1915 // and thus cosmetic "improvements" are disallowed: This has to deliver
1916 // the true picture of the buffer. (Asger)
1917 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1918 Font const & outerfont) const
1922 Font font = getFontSettings(bparams, pos);
1924 pos_type const body_pos = beginOfBody();
1925 FontInfo & fi = font.fontInfo();
1927 fi.realize(d->layout_->labelfont);
1929 fi.realize(d->layout_->font);
1931 fi.realize(outerfont.fontInfo());
1932 fi.realize(bparams.getFont().fontInfo());
1938 Font const Paragraph::getLabelFont
1939 (BufferParams const & bparams, Font const & outerfont) const
1941 FontInfo tmpfont = d->layout_->labelfont;
1942 tmpfont.realize(outerfont.fontInfo());
1943 tmpfont.realize(bparams.getFont().fontInfo());
1944 return Font(tmpfont, getParLanguage(bparams));
1948 Font const Paragraph::getLayoutFont
1949 (BufferParams const & bparams, Font const & outerfont) const
1951 FontInfo tmpfont = d->layout_->font;
1952 tmpfont.realize(outerfont.fontInfo());
1953 tmpfont.realize(bparams.getFont().fontInfo());
1954 return Font(tmpfont, getParLanguage(bparams));
1958 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1960 char_type c = d->text_[pos];
1961 if (!getFontSettings(bparams, pos).isRightToLeft())
1964 // FIXME: The arabic special casing is due to the difference of arabic
1965 // round brackets input introduced in r18599. Check if this should be
1966 // unified with Hebrew or at least if all bracket types should be
1967 // handled the same (file format change in either case).
1968 string const & lang = getFontSettings(bparams, pos).language()->lang();
1969 bool const arabic = lang == "arabic_arabtex" || lang == "arabic_arabi"
1974 uc = arabic ? c : ')';
1977 uc = arabic ? c : '(';
2003 void Paragraph::setFont(pos_type pos, Font const & font)
2005 LASSERT(pos <= size(), return);
2007 // First, reduce font against layout/label font
2008 // Update: The setCharFont() routine in text2.cpp already
2009 // reduces font, so we don't need to do that here. (Asger)
2011 d->fontlist_.set(pos, font);
2015 void Paragraph::makeSameLayout(Paragraph const & par)
2017 d->layout_ = par.d->layout_;
2018 d->params_ = par.d->params_;
2022 bool Paragraph::stripLeadingSpaces(bool trackChanges)
2024 if (isFreeSpacing())
2030 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
2031 if (eraseChar(pos, trackChanges))
2037 return count > 0 || pos > 0;
2041 bool Paragraph::hasSameLayout(Paragraph const & par) const
2043 return par.d->layout_ == d->layout_
2044 && d->params_.sameLayout(par.d->params_);
2048 depth_type Paragraph::getDepth() const
2050 return d->params_.depth();
2054 depth_type Paragraph::getMaxDepthAfter() const
2056 if (d->layout_->isEnvironment())
2057 return d->params_.depth() + 1;
2059 return d->params_.depth();
2063 LyXAlignment Paragraph::getAlign() const
2065 if (d->params_.align() == LYX_ALIGN_LAYOUT)
2066 return d->layout_->align;
2068 return d->params_.align();
2072 docstring const & Paragraph::labelString() const
2074 return d->params_.labelString();
2078 // the next two functions are for the manual labels
2079 docstring const Paragraph::getLabelWidthString() const
2081 if (d->layout_->margintype == MARGIN_MANUAL
2082 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2083 return d->params_.labelWidthString();
2085 return _("Senseless with this layout!");
2089 void Paragraph::setLabelWidthString(docstring const & s)
2091 d->params_.labelWidthString(s);
2095 docstring Paragraph::expandLabel(Layout const & layout,
2096 BufferParams const & bparams) const
2098 return expandParagraphLabel(layout, bparams, true);
2102 docstring Paragraph::expandDocBookLabel(Layout const & layout,
2103 BufferParams const & bparams) const
2105 return expandParagraphLabel(layout, bparams, false);
2109 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2110 BufferParams const & bparams, bool process_appendix) const
2112 DocumentClass const & tclass = bparams.documentClass();
2113 string const & lang = getParLanguage(bparams)->code();
2114 bool const in_appendix = process_appendix && d->params_.appendix();
2115 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2117 if (fmt.empty() && !layout.counter.empty())
2118 return tclass.counters().theCounter(layout.counter, lang);
2120 // handle 'inherited level parts' in 'fmt',
2121 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2122 size_t const i = fmt.find('@', 0);
2123 if (i != docstring::npos) {
2124 size_t const j = fmt.find('@', i + 1);
2125 if (j != docstring::npos) {
2126 docstring parent(fmt, i + 1, j - i - 1);
2127 docstring label = from_ascii("??");
2128 if (tclass.hasLayout(parent))
2129 label = expandParagraphLabel(tclass[parent], bparams,
2131 fmt = docstring(fmt, 0, i) + label
2132 + docstring(fmt, j + 1, docstring::npos);
2136 return tclass.counters().counterLabel(fmt, lang);
2140 void Paragraph::applyLayout(Layout const & new_layout)
2142 d->layout_ = &new_layout;
2143 LyXAlignment const oldAlign = d->params_.align();
2145 if (!(oldAlign & d->layout_->alignpossible)) {
2146 frontend::Alert::warning(_("Alignment not permitted"),
2147 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2148 d->params_.align(LYX_ALIGN_LAYOUT);
2153 pos_type Paragraph::beginOfBody() const
2155 return d->begin_of_body_;
2159 void Paragraph::setBeginOfBody()
2161 if (d->layout_->labeltype != LABEL_MANUAL) {
2162 d->begin_of_body_ = 0;
2166 // Unroll the first two cycles of the loop
2167 // and remember the previous character to
2168 // remove unnecessary getChar() calls
2170 pos_type end = size();
2171 if (i < end && !(isNewline(i) || isEnvSeparator(i))) {
2174 char_type previous_char = d->text_[i];
2175 if (!(isNewline(i) || isEnvSeparator(i))) {
2177 while (i < end && previous_char != ' ') {
2178 char_type temp = d->text_[i];
2179 if (isNewline(i) || isEnvSeparator(i))
2182 previous_char = temp;
2188 d->begin_of_body_ = i;
2192 bool Paragraph::allowParagraphCustomization() const
2194 return inInset().allowParagraphCustomization();
2198 bool Paragraph::usePlainLayout() const
2200 return inInset().usePlainLayout();
2204 bool Paragraph::isPassThru() const
2206 return inInset().isPassThru() || d->layout_->pass_thru;
2211 // paragraphs inside floats need different alignment tags to avoid
2214 bool noTrivlistCentering(InsetCode code)
2216 return code == FLOAT_CODE
2217 || code == WRAP_CODE
2218 || code == CELL_CODE;
2222 string correction(string const & orig)
2224 if (orig == "flushleft")
2225 return "raggedright";
2226 if (orig == "flushright")
2227 return "raggedleft";
2228 if (orig == "center")
2234 bool corrected_env(otexstream & os, string const & suffix, string const & env,
2235 InsetCode code, bool const lastpar, int & col)
2237 string macro = suffix + "{";
2238 if (noTrivlistCentering(code)) {
2240 // the last paragraph in non-trivlist-aligned
2241 // context is special (to avoid unwanted whitespace)
2242 if (suffix == "\\begin") {
2243 macro = "\\" + correction(env) + "{}";
2244 os << from_ascii(macro);
2245 col += macro.size();
2250 macro += correction(env);
2254 if (suffix == "\\par\\end") {
2258 os << from_ascii(macro);
2259 col += macro.size();
2260 if (suffix == "\\begin") {
2270 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2271 otexstream & os, OutputParams const & runparams) const
2276 (bparams.paragraph_separation == BufferParams::ParagraphIndentSeparation) ?
2277 (layout_->toggle_indent != ITOGGLE_NEVER) :
2278 (layout_->toggle_indent == ITOGGLE_ALWAYS);
2280 if (canindent && params_.noindent() && !layout_->pass_thru) {
2281 os << "\\noindent ";
2285 LyXAlignment const curAlign = params_.align();
2287 if (curAlign == layout_->align)
2291 case LYX_ALIGN_NONE:
2292 case LYX_ALIGN_BLOCK:
2293 case LYX_ALIGN_LAYOUT:
2294 case LYX_ALIGN_SPECIAL:
2295 case LYX_ALIGN_DECIMAL:
2297 case LYX_ALIGN_LEFT:
2298 case LYX_ALIGN_RIGHT:
2299 case LYX_ALIGN_CENTER:
2300 if (runparams.moving_arg) {
2307 string const begin_tag = "\\begin";
2308 InsetCode code = ownerCode();
2309 bool const lastpar = runparams.isLastPar;
2312 case LYX_ALIGN_NONE:
2313 case LYX_ALIGN_BLOCK:
2314 case LYX_ALIGN_LAYOUT:
2315 case LYX_ALIGN_SPECIAL:
2316 case LYX_ALIGN_DECIMAL:
2318 case LYX_ALIGN_LEFT: {
2319 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2320 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2322 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2324 } case LYX_ALIGN_RIGHT: {
2325 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2326 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2328 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2330 } case LYX_ALIGN_CENTER: {
2331 corrected_env(os, begin_tag, "center", code, lastpar, column);
2340 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2341 otexstream & os, OutputParams const & runparams) const
2343 LyXAlignment const curAlign = params_.align();
2345 if (curAlign == layout_->align)
2349 case LYX_ALIGN_NONE:
2350 case LYX_ALIGN_BLOCK:
2351 case LYX_ALIGN_LAYOUT:
2352 case LYX_ALIGN_SPECIAL:
2353 case LYX_ALIGN_DECIMAL:
2355 case LYX_ALIGN_LEFT:
2356 case LYX_ALIGN_RIGHT:
2357 case LYX_ALIGN_CENTER:
2358 if (runparams.moving_arg)
2363 bool output = false;
2365 string const end_tag = "\\par\\end";
2366 InsetCode code = ownerCode();
2367 bool const lastpar = runparams.isLastPar;
2370 case LYX_ALIGN_NONE:
2371 case LYX_ALIGN_BLOCK:
2372 case LYX_ALIGN_LAYOUT:
2373 case LYX_ALIGN_SPECIAL:
2374 case LYX_ALIGN_DECIMAL:
2376 case LYX_ALIGN_LEFT: {
2377 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2378 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2380 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2382 } case LYX_ALIGN_RIGHT: {
2383 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2384 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2386 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2388 } case LYX_ALIGN_CENTER: {
2389 corrected_env(os, end_tag, "center", code, lastpar, col);
2394 return output || lastpar;
2398 // This one spits out the text of the paragraph
2399 void Paragraph::latex(BufferParams const & bparams,
2400 Font const & outerfont,
2402 OutputParams const & runparams,
2403 int start_pos, int end_pos, bool force) const
2405 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2407 // FIXME This check should not be needed. Perhaps issue an
2408 // error if it triggers.
2409 Layout const & style = inInset().forcePlainLayout() ?
2410 bparams.documentClass().plainLayout() : *d->layout_;
2412 if (!force && style.inpreamble)
2415 bool const allowcust = allowParagraphCustomization();
2417 // Current base font for all inherited font changes, without any
2418 // change caused by an individual character, except for the language:
2419 // It is set to the language of the first character.
2420 // As long as we are in the label, this font is the base font of the
2421 // label. Before the first body character it is set to the base font
2425 // Maybe we have to create a optional argument.
2426 pos_type body_pos = beginOfBody();
2427 unsigned int column = 0;
2430 // the optional argument is kept in curly brackets in
2431 // case it contains a ']'
2432 // This is not strictly needed, but if this is changed it
2433 // would be a file format change, and tex2lyx would need
2434 // to be adjusted, since it unconditionally removes the
2435 // braces when it parses \item.
2438 basefont = getLabelFont(bparams, outerfont);
2440 basefont = getLayoutFont(bparams, outerfont);
2443 // Which font is currently active?
2444 Font running_font(basefont);
2445 // Do we have an open font change?
2446 bool open_font = false;
2448 Change runningChange = Change(Change::UNCHANGED);
2450 Encoding const * const prev_encoding = runparams.encoding;
2452 os.texrow().start(id(), 0);
2454 // if the paragraph is empty, the loop will not be entered at all
2456 // For InTitle commands, we have already opened a group
2457 // in output_latex::TeXOnePar.
2458 if (style.isCommand() && !style.intitle) {
2462 if (!style.leftdelim().empty()) {
2463 os << style.leftdelim();
2464 column += style.leftdelim().size();
2467 column += d->startTeXParParams(bparams, os, runparams);
2470 // Whether a \par can be issued for insets typeset inline with text.
2471 // Yes if greater than 0. This has to be static.
2472 THREAD_LOCAL_STATIC int parInline = 0;
2474 for (pos_type i = 0; i < size(); ++i) {
2475 // First char in paragraph or after label?
2476 if (i == body_pos) {
2479 bool needPar = false;
2480 column += running_font.latexWriteEndChanges(
2481 os, bparams, runparams,
2482 basefont, basefont, needPar);
2485 basefont = getLayoutFont(bparams, outerfont);
2486 running_font = basefont;
2488 column += Changes::latexMarkChange(os, bparams,
2489 runningChange, Change(Change::UNCHANGED),
2491 runningChange = Change(Change::UNCHANGED);
2496 // For InTitle commands, we have already opened a group
2497 // in output_latex::TeXOnePar.
2498 if (style.isCommand() && !style.intitle) {
2503 if (!style.leftdelim().empty()) {
2504 os << style.leftdelim();
2505 column += style.leftdelim().size();
2509 column += d->startTeXParParams(bparams, os,
2513 runparams.wasDisplayMath = runparams.inDisplayMath;
2514 runparams.inDisplayMath = false;
2515 bool deleted_display_math = false;
2516 Change const & change = runparams.inDeletedInset
2517 ? runparams.changeOfDeletedInset : lookupChange(i);
2519 // Check whether a display math inset follows
2520 if (d->text_[i] == META_INSET
2521 && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2522 InsetMath const * im = getInset(i)->asInsetMath();
2523 if (im && im->asHullInset()
2524 && im->asHullInset()->outerDisplay()) {
2525 runparams.inDisplayMath = true;
2526 // runparams.inDeletedInset will be set by
2527 // latexInset later, but we need this info
2528 // before it is called. On the other hand, we
2529 // cannot set it here because it is a counter.
2530 deleted_display_math = isDeleted(i);
2532 if (bparams.output_changes && deleted_display_math
2533 && runningChange == change
2534 && change.type == Change::DELETED
2535 && !os.afterParbreak()) {
2536 // A display math in the same paragraph follows.
2537 // We have to close and then reopen \lyxdeleted,
2538 // otherwise the math will be shifted up.
2539 OutputParams rp = runparams;
2541 bool needPar = false;
2542 column += running_font.latexWriteEndChanges(
2543 os, bparams, rp, basefont,
2547 basefont = getLayoutFont(bparams, outerfont);
2548 running_font = basefont;
2549 column += Changes::latexMarkChange(os, bparams,
2550 Change(Change::INSERTED), change, rp);
2554 if (bparams.output_changes && runningChange != change) {
2556 bool needPar = false;
2557 column += running_font.latexWriteEndChanges(
2558 os, bparams, runparams,
2559 basefont, basefont, needPar);
2562 basefont = getLayoutFont(bparams, outerfont);
2563 running_font = basefont;
2564 column += Changes::latexMarkChange(os, bparams, runningChange,
2566 runningChange = change;
2569 // do not output text which is marked deleted
2570 // if change tracking output is disabled
2571 if (!bparams.output_changes && change.deleted()) {
2577 // Fully instantiated font
2578 Font const current_font = getFont(bparams, i, outerfont);
2580 Font const last_font = running_font;
2582 // Do we need to close the previous font?
2584 (current_font != running_font ||
2585 current_font.language() != running_font.language()))
2587 bool needPar = false;
2588 column += running_font.latexWriteEndChanges(
2589 os, bparams, runparams, basefont,
2590 (i == body_pos-1) ? basefont : current_font,
2592 running_font = basefont;
2596 string const running_lang = runparams.use_polyglossia ?
2597 running_font.language()->polyglossia() : running_font.language()->babel();
2598 // close babel's font environment before opening CJK.
2599 string const lang_end_command = runparams.use_polyglossia ?
2600 "\\end{$$lang}" : lyxrc.language_command_end;
2601 bool const using_begin_end = runparams.use_polyglossia ||
2602 !lang_end_command.empty();
2603 if (!running_lang.empty() &&
2604 (!using_begin_end || running_lang == openLanguageName()) &&
2605 current_font.language()->encoding()->package() == Encoding::CJK) {
2606 string end_tag = subst(lang_end_command,
2609 os << from_ascii(end_tag);
2610 column += end_tag.length();
2611 if (using_begin_end)
2615 // Switch file encoding if necessary (and allowed)
2616 if (!runparams.pass_thru && !style.pass_thru &&
2617 runparams.encoding->package() != Encoding::none &&
2618 current_font.language()->encoding()->package() != Encoding::none) {
2619 pair<bool, int> const enc_switch =
2620 switchEncoding(os.os(), bparams, runparams,
2621 *(current_font.language()->encoding()));
2622 if (enc_switch.first) {
2623 column += enc_switch.second;
2624 runparams.encoding = current_font.language()->encoding();
2628 char_type const c = d->text_[i];
2630 // A display math inset inside an ulem command will be output
2631 // as a box of width \linewidth, so we have to either disable
2632 // indentation if the inset starts a paragraph, or start a new
2633 // line to accommodate such box. This has to be done before
2634 // writing any font changing commands.
2635 if (runparams.inDisplayMath && !deleted_display_math
2636 && runparams.inulemcmd) {
2637 if (os.afterParbreak())
2643 // Do we need to change font?
2644 if ((current_font != running_font ||
2645 current_font.language() != running_font.language()) &&
2648 odocstringstream ods;
2649 column += current_font.latexWriteStartChanges(ods, bparams,
2650 runparams, basefont,
2652 // Check again for display math in ulem commands as a
2653 // font change may also occur just before a math inset.
2654 if (runparams.inDisplayMath && !deleted_display_math
2655 && runparams.inulemcmd) {
2656 if (os.afterParbreak())
2661 running_font = current_font;
2663 docstring fontchange = ods.str();
2664 // check whether the fontchange ends with a \\textcolor
2665 // modifier and the text starts with a space (bug 4473)
2666 docstring const last_modifier = rsplit(fontchange, '\\');
2667 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2668 os << fontchange << from_ascii("{}");
2669 // check if the fontchange ends with a trailing blank
2670 // (like "\small " (see bug 3382)
2671 else if (suffixIs(fontchange, ' ') && c == ' ')
2672 os << fontchange.substr(0, fontchange.size() - 1)
2673 << from_ascii("{}");
2678 // FIXME: think about end_pos implementation...
2679 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2680 // FIXME: integrate this case in latexSpecialChar
2681 // Do not print the separation of the optional argument
2682 // if style.pass_thru is false. This works because
2683 // latexSpecialChar ignores spaces if
2684 // style.pass_thru is false.
2685 if (i != body_pos - 1) {
2686 if (d->simpleTeXBlanks(runparams, os,
2687 i, column, current_font, style)) {
2688 // A surrogate pair was output. We
2689 // must not call latexSpecialChar
2690 // in this iteration, since it would output
2691 // the combining character again.
2698 OutputParams rp = runparams;
2699 rp.free_spacing = style.free_spacing;
2700 rp.local_font = ¤t_font;
2701 rp.intitle = style.intitle;
2703 // Two major modes: LaTeX or plain
2704 // Handle here those cases common to both modes
2705 // and then split to handle the two modes separately.
2706 if (c == META_INSET) {
2707 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2708 // Greyedout notes and, in general, all insets
2709 // with InsetLayout::isDisplay() == false,
2710 // are typeset inline with the text. So, we
2711 // can add a \par to the last paragraph of
2712 // such insets only if nothing else follows.
2713 bool incremented = false;
2714 Inset const * inset = getInset(i);
2715 InsetText const * textinset = inset
2716 ? inset->asInsetText()
2718 if (i + 1 == size() && textinset
2719 && !inset->getLayout().isDisplay()) {
2720 ParagraphList const & pars =
2721 textinset->text().paragraphs();
2722 pit_type const pit = pars.size() - 1;
2723 Font const lastfont =
2724 pit < 0 || pars[pit].empty()
2725 ? pars[pit].getLayoutFont(
2728 : pars[pit].getFont(bparams,
2729 pars[pit].size() - 1,
2731 if (lastfont.fontInfo().size() !=
2732 basefont.fontInfo().size()) {
2737 d->latexInset(bparams, os, rp, running_font,
2738 basefont, outerfont, open_font,
2739 runningChange, style, i, column);
2743 } else if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2745 d->latexSpecialChar(os, bparams, rp,
2746 running_font, runningChange,
2747 style, i, end_pos, column);
2748 } catch (EncodingException & e) {
2749 if (runparams.dryrun) {
2750 os << "<" << _("LyX Warning: ")
2751 << _("uncodable character") << " '";
2755 // add location information and throw again.
2763 // Set the encoding to that returned from latexSpecialChar (see
2764 // comment for encoding member in OutputParams.h)
2765 runparams.encoding = rp.encoding;
2767 // Also carry on the info on a closed ulem command for insets
2768 // such as Note that do not produce any output, so that no
2769 // command is ever executed but its opening was recorded.
2770 runparams.inulemcmd = rp.inulemcmd;
2773 // If we have an open font definition, we have to close it
2775 // Make sure that \\par is done with the font of the last
2776 // character if this has another size as the default.
2777 // This is necessary because LaTeX (and LyX on the screen)
2778 // calculates the space between the baselines according
2779 // to this font. (Matthias)
2781 // We must not change the font for the last paragraph
2782 // of non-multipar insets, tabular cells or commands,
2783 // since this produces unwanted whitespace.
2785 Font const font = empty()
2786 ? getLayoutFont(bparams, outerfont)
2787 : getFont(bparams, size() - 1, outerfont);
2789 InsetText const * textinset = inInset().asInsetText();
2791 bool const maintext = textinset
2792 ? textinset->text().isMainText()
2795 size_t const numpars = textinset
2796 ? textinset->text().paragraphs().size()
2799 bool needPar = false;
2801 if (style.resfont.size() != font.fontInfo().size()
2802 && (!runparams.isLastPar || maintext
2803 || (numpars > 1 && d->ownerCode() != CELL_CODE
2804 && (inInset().getLayout().isDisplay()
2806 && !style.isCommand()) {
2809 #ifdef FIXED_LANGUAGE_END_DETECTION
2811 running_font.latexWriteEndChanges(os, bparams,
2812 runparams, basefont,
2813 next_->getFont(bparams, 0, outerfont),
2816 running_font.latexWriteEndChanges(os, bparams,
2817 runparams, basefont, basefont, needPar);
2820 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2821 //FIXME: there as we start another \selectlanguage with the next paragraph if
2822 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2823 running_font.latexWriteEndChanges(os, bparams, runparams,
2824 basefont, basefont, needPar);
2827 // The \par could not be inserted at the same nesting
2828 // level of the font size change, so do it now.
2829 os << "{\\" << font.latexSize() << "\\par}";
2833 column += Changes::latexMarkChange(os, bparams, runningChange,
2834 Change(Change::UNCHANGED), runparams);
2836 // Needed if there is an optional argument but no contents.
2837 if (body_pos > 0 && body_pos == size()) {
2841 if (!style.rightdelim().empty()) {
2842 os << style.rightdelim();
2843 column += style.rightdelim().size();
2846 if (allowcust && d->endTeXParParams(bparams, os, runparams)
2847 && runparams.encoding != prev_encoding) {
2848 runparams.encoding = prev_encoding;
2849 os << setEncoding(prev_encoding->iconvName());
2852 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2856 bool Paragraph::emptyTag() const
2858 for (pos_type i = 0; i < size(); ++i) {
2859 if (Inset const * inset = getInset(i)) {
2860 InsetCode lyx_code = inset->lyxCode();
2861 // FIXME testing like that is wrong. What is
2863 if (lyx_code != TOC_CODE &&
2864 lyx_code != INCLUDE_CODE &&
2865 lyx_code != GRAPHICS_CODE &&
2866 lyx_code != ERT_CODE &&
2867 lyx_code != LISTINGS_CODE &&
2868 lyx_code != FLOAT_CODE &&
2869 lyx_code != TABULAR_CODE) {
2873 char_type c = d->text_[i];
2874 if (c != ' ' && c != '\t')
2882 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2885 for (pos_type i = 0; i < size(); ++i) {
2886 if (Inset const * inset = getInset(i)) {
2887 InsetCode lyx_code = inset->lyxCode();
2888 if (lyx_code == LABEL_CODE) {
2889 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2890 docstring const & id = il->getParam("name");
2891 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2899 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2903 for (i = 0; i < size(); ++i) {
2904 if (Inset const * inset = getInset(i)) {
2905 inset->docbook(os, runparams);
2907 char_type c = d->text_[i];
2910 os << sgml::escapeChar(c);
2917 pos_type Paragraph::firstWordLyXHTML(XHTMLStream & xs, OutputParams const & runparams)
2921 for (i = 0; i < size(); ++i) {
2922 if (Inset const * inset = getInset(i)) {
2923 inset->xhtml(xs, runparams);
2925 char_type c = d->text_[i];
2935 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2938 pos_type size = text_.size();
2939 for (pos_type i = initial; i < size; ++i) {
2940 Font font = owner_->getFont(buf.params(), i, outerfont);
2941 if (text_[i] == META_INSET)
2943 if (i != initial && font != font_old)
2952 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2954 OutputParams const & runparams,
2955 Font const & outerfont,
2956 pos_type initial) const
2958 bool emph_flag = false;
2960 Layout const & style = *d->layout_;
2962 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2964 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2967 // parsing main loop
2968 for (pos_type i = initial; i < size(); ++i) {
2969 Font font = getFont(buf.params(), i, outerfont);
2971 // handle <emphasis> tag
2972 if (font_old.emph() != font.fontInfo().emph()) {
2973 if (font.fontInfo().emph() == FONT_ON) {
2976 } else if (i != initial) {
2977 os << "</emphasis>";
2982 if (Inset const * inset = getInset(i)) {
2983 inset->docbook(os, runparams);
2985 char_type c = d->text_[i];
2987 if (style.pass_thru)
2990 os << sgml::escapeChar(c);
2992 font_old = font.fontInfo();
2996 os << "</emphasis>";
2999 if (style.free_spacing)
3001 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
3007 void doFontSwitch(vector<html::FontTag> & tagsToOpen,
3008 vector<html::EndFontTag> & tagsToClose,
3009 bool & flag, FontState curstate, html::FontTypes type)
3011 if (curstate == FONT_ON) {
3012 tagsToOpen.push_back(html::FontTag(type));
3015 tagsToClose.push_back(html::EndFontTag(type));
3022 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
3024 OutputParams const & runparams,
3025 Font const & outerfont,
3026 bool start_paragraph, bool close_paragraph,
3027 pos_type initial) const
3031 // track whether we have opened these tags
3032 bool emph_flag = false;
3033 bool bold_flag = false;
3034 bool noun_flag = false;
3035 bool ubar_flag = false;
3036 bool dbar_flag = false;
3037 bool sout_flag = false;
3038 bool xout_flag = false;
3039 bool wave_flag = false;
3041 bool shap_flag = false;
3043 bool faml_flag = false;
3045 bool size_flag = false;
3047 Layout const & style = *d->layout_;
3049 if (start_paragraph)
3050 xs.startDivision(allowEmpty());
3053 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3055 FontShape curr_fs = INHERIT_SHAPE;
3056 FontFamily curr_fam = INHERIT_FAMILY;
3057 FontSize curr_size = FONT_SIZE_INHERIT;
3059 string const default_family =
3060 buf.masterBuffer()->params().fonts_default_family;
3062 vector<html::FontTag> tagsToOpen;
3063 vector<html::EndFontTag> tagsToClose;
3065 // parsing main loop
3066 for (pos_type i = initial; i < size(); ++i) {
3067 // let's not show deleted material in the output
3071 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3074 FontState curstate = font.fontInfo().emph();
3075 if (font_old.emph() != curstate)
3076 doFontSwitch(tagsToOpen, tagsToClose, emph_flag, curstate, html::FT_EMPH);
3079 curstate = font.fontInfo().noun();
3080 if (font_old.noun() != curstate)
3081 doFontSwitch(tagsToOpen, tagsToClose, noun_flag, curstate, html::FT_NOUN);
3084 curstate = font.fontInfo().underbar();
3085 if (font_old.underbar() != curstate)
3086 doFontSwitch(tagsToOpen, tagsToClose, ubar_flag, curstate, html::FT_UBAR);
3089 curstate = font.fontInfo().strikeout();
3090 if (font_old.strikeout() != curstate)
3091 doFontSwitch(tagsToOpen, tagsToClose, sout_flag, curstate, html::FT_SOUT);
3094 curstate = font.fontInfo().xout();
3095 if (font_old.xout() != curstate)
3096 doFontSwitch(tagsToOpen, tagsToClose, xout_flag, curstate, html::FT_XOUT);
3099 curstate = font.fontInfo().uuline();
3100 if (font_old.uuline() != curstate)
3101 doFontSwitch(tagsToOpen, tagsToClose, dbar_flag, curstate, html::FT_DBAR);
3104 curstate = font.fontInfo().uwave();
3105 if (font_old.uwave() != curstate)
3106 doFontSwitch(tagsToOpen, tagsToClose, wave_flag, curstate, html::FT_WAVE);
3109 // a little hackish, but allows us to reuse what we have.
3110 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3111 if (font_old.series() != font.fontInfo().series())
3112 doFontSwitch(tagsToOpen, tagsToClose, bold_flag, curstate, html::FT_BOLD);
3115 curr_fs = font.fontInfo().shape();
3116 FontShape old_fs = font_old.shape();
3117 if (old_fs != curr_fs) {
3121 tagsToClose.push_back(html::EndFontTag(html::FT_ITALIC));
3124 tagsToClose.push_back(html::EndFontTag(html::FT_SLANTED));
3126 case SMALLCAPS_SHAPE:
3127 tagsToClose.push_back(html::EndFontTag(html::FT_SMALLCAPS));
3133 // the other tags are for internal use
3141 tagsToOpen.push_back(html::FontTag(html::FT_ITALIC));
3145 tagsToOpen.push_back(html::FontTag(html::FT_SLANTED));
3148 case SMALLCAPS_SHAPE:
3149 tagsToOpen.push_back(html::FontTag(html::FT_SMALLCAPS));
3156 // the other tags are for internal use
3163 curr_fam = font.fontInfo().family();
3164 FontFamily old_fam = font_old.family();
3165 if (old_fam != curr_fam) {
3169 tagsToClose.push_back(html::EndFontTag(html::FT_ROMAN));
3172 tagsToClose.push_back(html::EndFontTag(html::FT_SANS));
3174 case TYPEWRITER_FAMILY:
3175 tagsToClose.push_back(html::EndFontTag(html::FT_TYPE));
3177 case INHERIT_FAMILY:
3180 // the other tags are for internal use
3188 // we will treat a "default" font family as roman, since we have
3189 // no other idea what to do.
3190 if (default_family != "rmdefault" && default_family != "default") {
3191 tagsToOpen.push_back(html::FontTag(html::FT_ROMAN));
3196 if (default_family != "sfdefault") {
3197 tagsToOpen.push_back(html::FontTag(html::FT_SANS));
3201 case TYPEWRITER_FAMILY:
3202 if (default_family != "ttdefault") {
3203 tagsToOpen.push_back(html::FontTag(html::FT_TYPE));
3207 case INHERIT_FAMILY:
3210 // the other tags are for internal use
3217 curr_size = font.fontInfo().size();
3218 FontSize old_size = font_old.size();
3219 if (old_size != curr_size) {
3222 case FONT_SIZE_TINY:
3223 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_TINY));
3225 case FONT_SIZE_SCRIPT:
3226 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_SCRIPT));
3228 case FONT_SIZE_FOOTNOTE:
3229 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_FOOTNOTE));
3231 case FONT_SIZE_SMALL:
3232 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_SMALL));
3234 case FONT_SIZE_LARGE:
3235 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGE));
3237 case FONT_SIZE_LARGER:
3238 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGER));
3240 case FONT_SIZE_LARGEST:
3241 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGEST));
3243 case FONT_SIZE_HUGE:
3244 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_HUGE));
3246 case FONT_SIZE_HUGER:
3247 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_HUGER));
3249 case FONT_SIZE_INCREASE:
3250 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_INCREASE));
3252 case FONT_SIZE_DECREASE:
3253 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_DECREASE));
3255 case FONT_SIZE_INHERIT:
3256 case FONT_SIZE_NORMAL:
3259 // the other tags are for internal use
3265 switch (curr_size) {
3266 case FONT_SIZE_TINY:
3267 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_TINY));
3270 case FONT_SIZE_SCRIPT:
3271 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_SCRIPT));
3274 case FONT_SIZE_FOOTNOTE:
3275 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_FOOTNOTE));
3278 case FONT_SIZE_SMALL:
3279 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_SMALL));
3282 case FONT_SIZE_LARGE:
3283 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGE));
3286 case FONT_SIZE_LARGER:
3287 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGER));
3290 case FONT_SIZE_LARGEST:
3291 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGEST));
3294 case FONT_SIZE_HUGE:
3295 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_HUGE));
3298 case FONT_SIZE_HUGER:
3299 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_HUGER));
3302 case FONT_SIZE_INCREASE:
3303 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_INCREASE));
3306 case FONT_SIZE_DECREASE:
3307 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_DECREASE));
3310 case FONT_SIZE_NORMAL:
3311 case FONT_SIZE_INHERIT:
3314 // the other tags are for internal use
3321 // Other such tags? What about the other text ranges?
3323 vector<html::EndFontTag>::const_iterator cit = tagsToClose.begin();
3324 vector<html::EndFontTag>::const_iterator cen = tagsToClose.end();
3325 for (; cit != cen; ++cit)
3328 vector<html::FontTag>::const_iterator sit = tagsToOpen.begin();
3329 vector<html::FontTag>::const_iterator sen = tagsToOpen.end();
3330 for (; sit != sen; ++sit)
3333 tagsToClose.clear();
3336 Inset const * inset = getInset(i);
3338 if (!runparams.for_toc || inset->isInToc()) {
3339 OutputParams np = runparams;
3340 np.local_font = &font;
3341 // If the paragraph has size 1, then we are in the "special
3342 // case" where we do not output the containing paragraph info
3343 if (!inset->getLayout().htmlisblock() && size() != 1)
3344 np.html_in_par = true;
3345 retval += inset->xhtml(xs, np);
3348 char_type c = getUChar(buf.masterBuffer()->params(), i);
3351 font_old = font.fontInfo();
3355 // I'm worried about what happens if a branch, say, is itself
3356 // wrapped in some font stuff. I think that will not work.
3358 if (close_paragraph)
3365 bool Paragraph::isHfill(pos_type pos) const
3367 Inset const * inset = getInset(pos);
3368 return inset && inset->isHfill();
3372 bool Paragraph::isNewline(pos_type pos) const
3374 // U+2028 LINE SEPARATOR
3375 // U+2029 PARAGRAPH SEPARATOR
3376 char_type const c = d->text_[pos];
3377 if (c == 0x2028 || c == 0x2029)
3379 Inset const * inset = getInset(pos);
3380 return inset && inset->lyxCode() == NEWLINE_CODE;
3384 bool Paragraph::isEnvSeparator(pos_type pos) const
3386 Inset const * inset = getInset(pos);
3387 return inset && inset->lyxCode() == SEPARATOR_CODE;
3391 bool Paragraph::isLineSeparator(pos_type pos) const
3393 char_type const c = d->text_[pos];
3394 if (isLineSeparatorChar(c))
3396 Inset const * inset = getInset(pos);
3397 return inset && inset->isLineSeparator();
3401 bool Paragraph::isWordSeparator(pos_type pos) const
3405 if (Inset const * inset = getInset(pos))
3406 return !inset->isLetter();
3407 // if we have a hard hyphen (no en- or emdash) or apostrophe
3408 // we pass this to the spell checker
3409 // FIXME: this method is subject to change, visit
3410 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
3411 // to get an impression how complex this is.
3412 if (isHardHyphenOrApostrophe(pos))
3414 char_type const c = d->text_[pos];
3415 // We want to pass the escape chars to the spellchecker
3416 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
3417 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
3421 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
3423 pos_type const psize = size();
3426 char_type const c = d->text_[pos];
3427 if (c != '-' && c != '\'')
3429 int nextpos = pos + 1;
3430 int prevpos = pos > 0 ? pos - 1 : 0;
3431 if ((nextpos == psize || isSpace(nextpos))
3432 && (pos == 0 || isSpace(prevpos)))
3438 bool Paragraph::needsCProtection() const
3440 // first check the layout of the paragraph
3441 if (layout().needcprotect) {
3442 // Environments need cprotection regardless the content
3443 if (layout().latextype == LATEX_ENVIRONMENT)
3446 // Commands need cprotection if they contain specific chars
3447 int const nchars_escape = 9;
3448 static char_type const chars_escape[nchars_escape] = {
3449 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
3451 docstring const pars = asString();
3452 for (int k = 0; k < nchars_escape; k++) {
3453 if (contains(pars, chars_escape[k]))
3458 // now check whether we have insets that need cprotection
3459 pos_type size = d->text_.size();
3460 for (pos_type i = 0; i < size; ++i)
3461 if (isInset(i) && getInset(i)->needsCProtection())
3468 FontSpan const & Paragraph::getSpellRange(pos_type pos) const
3470 return d->speller_state_.getRange(pos);
3474 bool Paragraph::isChar(pos_type pos) const
3476 if (Inset const * inset = getInset(pos))
3477 return inset->isChar();
3478 char_type const c = d->text_[pos];
3479 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
3483 bool Paragraph::isSpace(pos_type pos) const
3485 if (Inset const * inset = getInset(pos))
3486 return inset->isSpace();
3487 char_type const c = d->text_[pos];
3488 return lyx::isSpace(c);
3493 Paragraph::getParLanguage(BufferParams const & bparams) const
3496 return getFirstFontSettings(bparams).language();
3497 // FIXME: we should check the prev par as well (Lgb)
3498 return bparams.language;
3502 bool Paragraph::isRTL(BufferParams const & bparams) const
3504 return getParLanguage(bparams)->rightToLeft()
3505 && !inInset().getLayout().forceLTR();
3509 void Paragraph::changeLanguage(BufferParams const & bparams,
3510 Language const * from, Language const * to)
3512 // change language including dummy font change at the end
3513 for (pos_type i = 0; i <= size(); ++i) {
3514 Font font = getFontSettings(bparams, i);
3515 if (font.language() == from) {
3516 font.setLanguage(to);
3518 d->requestSpellCheck(i);
3524 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
3526 Language const * doc_language = bparams.language;
3527 for (auto const & f : d->fontlist_)
3528 if (f.font().language() != ignore_language &&
3529 f.font().language() != latex_language &&
3530 f.font().language() != doc_language)
3536 void Paragraph::getLanguages(std::set<Language const *> & langs) const
3538 for (auto const & f : d->fontlist_) {
3539 Language const * lang = f.font().language();
3540 if (lang != ignore_language &&
3541 lang != latex_language)
3547 docstring Paragraph::asString(int options) const
3549 return asString(0, size(), options);
3553 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
3555 odocstringstream os;
3558 && options & AS_STR_LABEL
3559 && !d->params_.labelString().empty())
3560 os << d->params_.labelString() << ' ';
3562 for (pos_type i = beg; i < end; ++i) {
3563 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
3565 char_type const c = d->text_[i];
3566 if (isPrintable(c) || c == '\t'
3567 || (c == '\n' && (options & AS_STR_NEWLINES)))
3569 else if (c == META_INSET && (options & AS_STR_INSETS)) {
3570 if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
3571 LASSERT(runparams != 0, return docstring());
3572 getInset(i)->plaintext(os, *runparams);
3574 getInset(i)->toString(os);
3583 void Paragraph::forOutliner(docstring & os, size_t const maxlen,
3584 bool const shorten, bool const label) const
3586 size_t tmplen = shorten ? maxlen + 1 : maxlen;
3587 if (label && !labelString().empty())
3588 os += labelString() + ' ';
3589 if (!layout().isTocCaption())
3591 for (pos_type i = 0; i < size() && os.length() < tmplen; ++i) {
3594 char_type const c = d->text_[i];
3597 else if (c == META_INSET)
3598 getInset(i)->forOutliner(os, tmplen, false);
3601 Text::shortenForOutliner(os, maxlen);
3605 void Paragraph::setInsetOwner(Inset const * inset)
3607 d->inset_owner_ = inset;
3611 int Paragraph::id() const
3617 void Paragraph::setId(int id)
3623 Layout const & Paragraph::layout() const
3629 void Paragraph::setLayout(Layout const & layout)
3631 d->layout_ = &layout;
3635 void Paragraph::setDefaultLayout(DocumentClass const & tc)
3637 setLayout(tc.defaultLayout());
3641 void Paragraph::setPlainLayout(DocumentClass const & tc)
3643 setLayout(tc.plainLayout());
3647 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
3649 if (usePlainLayout())
3650 setPlainLayout(tclass);
3652 setDefaultLayout(tclass);
3656 Inset const & Paragraph::inInset() const
3658 LBUFERR(d->inset_owner_);
3659 return *d->inset_owner_;
3663 ParagraphParameters & Paragraph::params()
3669 ParagraphParameters const & Paragraph::params() const
3675 bool Paragraph::isFreeSpacing() const
3677 if (d->layout_->free_spacing)
3679 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
3683 bool Paragraph::allowEmpty() const
3685 if (d->layout_->keepempty)
3687 return d->inset_owner_ && d->inset_owner_->allowEmpty();
3691 bool Paragraph::brokenBiblio() const
3693 // there is a problem if there is no bibitem at position 0 or
3694 // if there is another bibitem in the paragraph.
3695 return d->layout_->labeltype == LABEL_BIBLIO
3696 && (d->insetlist_.find(BIBITEM_CODE) != 0
3697 || d->insetlist_.find(BIBITEM_CODE, 1) > 0);
3701 int Paragraph::fixBiblio(Buffer const & buffer)
3703 // FIXME: What about the case where paragraph is not BIBLIO
3704 // but there is an InsetBibitem?
3705 // FIXME: when there was already an inset at 0, the return value is 1,
3706 // which does not tell whether another inset has been remove; the
3707 // cursor cannot be correctly updated.
3709 if (d->layout_->labeltype != LABEL_BIBLIO)
3712 bool const track_changes = buffer.params().track_changes;
3713 int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
3714 bool const hasbibitem0 = bibitem_pos == 0;
3717 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
3718 // There was an InsetBibitem at pos 0, and no other one => OK
3719 if (bibitem_pos == -1)
3721 // there is a bibitem at the 0 position, but since
3722 // there is a second one, we copy the second on the
3723 // first. We're assuming there are at most two of
3724 // these, which there should be.
3725 // FIXME: why does it make sense to do that rather
3726 // than keep the first? (JMarc)
3727 Inset * inset = releaseInset(bibitem_pos);
3728 d->insetlist_.begin()->inset = inset;
3729 return -bibitem_pos;
3732 // We need to create an inset at the beginning
3734 if (bibitem_pos > 0) {
3735 // there was one somewhere in the paragraph, let's move it
3736 inset = d->insetlist_.release(bibitem_pos);
3737 eraseChar(bibitem_pos, track_changes);
3740 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
3741 InsetCommandParams(BIBITEM_CODE));
3743 Font font(inherit_font, buffer.params().language);
3744 insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
3745 : Change::UNCHANGED));
3751 void Paragraph::checkAuthors(AuthorList const & authorList)
3753 d->changes_.checkAuthors(authorList);
3757 bool Paragraph::isChanged(pos_type pos) const
3759 return lookupChange(pos).changed();
3763 bool Paragraph::isInserted(pos_type pos) const
3765 return lookupChange(pos).inserted();
3769 bool Paragraph::isDeleted(pos_type pos) const
3771 return lookupChange(pos).deleted();
3775 InsetList const & Paragraph::insetList() const
3777 return d->insetlist_;
3781 void Paragraph::setInsetBuffers(Buffer & b)
3783 d->insetlist_.setBuffer(b);
3787 void Paragraph::resetBuffer()
3789 d->insetlist_.resetBuffer();
3793 Inset * Paragraph::releaseInset(pos_type pos)
3795 Inset * inset = d->insetlist_.release(pos);
3796 /// does not honour change tracking!
3797 eraseChar(pos, false);
3802 Inset * Paragraph::getInset(pos_type pos)
3804 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3805 ? d->insetlist_.get(pos) : 0;
3809 Inset const * Paragraph::getInset(pos_type pos) const
3811 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3812 ? d->insetlist_.get(pos) : 0;
3816 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
3817 pos_type & right, TextCase action)
3819 // process sequences of modified characters; in change
3820 // tracking mode, this approach results in much better
3821 // usability than changing case on a char-by-char basis
3822 // We also need to track the current font, since font
3823 // changes within sequences can occur.
3824 vector<pair<char_type, Font> > changes;
3826 bool const trackChanges = bparams.track_changes;
3828 bool capitalize = true;
3830 for (; pos < right; ++pos) {
3831 char_type oldChar = d->text_[pos];
3832 char_type newChar = oldChar;
3834 // ignore insets and don't play with deleted text!
3835 if (oldChar != META_INSET && !isDeleted(pos)) {
3837 case text_lowercase:
3838 newChar = lowercase(oldChar);
3840 case text_capitalization:
3842 newChar = uppercase(oldChar);
3846 case text_uppercase:
3847 newChar = uppercase(oldChar);
3852 if (isWordSeparator(pos) || isDeleted(pos)) {
3853 // permit capitalization again
3857 if (oldChar != newChar) {
3858 changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
3859 if (pos != right - 1)
3861 // step behind the changing area
3865 int erasePos = pos - changes.size();
3866 for (size_t i = 0; i < changes.size(); i++) {
3867 insertChar(pos, changes[i].first,
3870 if (!eraseChar(erasePos, trackChanges)) {
3873 ++right; // expand selection
3881 int Paragraph::find(docstring const & str, bool cs, bool mw,
3882 pos_type start_pos, bool del) const
3884 pos_type pos = start_pos;
3885 int const strsize = str.length();
3887 pos_type const parsize = d->text_.size();
3888 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
3889 // Ignore "invisible" letters such as ligature breaks
3890 // and hyphenation chars while searching
3891 while (pos < parsize - 1 && isInset(pos)) {
3892 odocstringstream os;
3893 getInset(pos)->toString(os);
3894 if (!getInset(pos)->isLetter() || !os.str().empty())
3898 if (cs && str[i] != d->text_[pos])
3900 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
3902 if (!del && isDeleted(pos))
3909 // if necessary, check whether string matches word
3911 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
3914 && !isWordSeparator(pos))
3918 return pos - start_pos;
3922 char_type Paragraph::getChar(pos_type pos) const
3924 return d->text_[pos];
3928 pos_type Paragraph::size() const
3930 return d->text_.size();
3934 bool Paragraph::empty() const
3936 return d->text_.empty();
3940 bool Paragraph::isInset(pos_type pos) const
3942 return d->text_[pos] == META_INSET;
3946 bool Paragraph::isSeparator(pos_type pos) const
3948 //FIXME: Are we sure this can be the only separator?
3949 return d->text_[pos] == ' ';
3953 void Paragraph::deregisterWords()
3955 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3956 Private::LangWordsMap::const_iterator ite = d->words_.end();
3957 for (; itl != ite; ++itl) {
3958 WordList & wl = theWordList(itl->first);
3959 Private::Words::const_iterator it = (itl->second).begin();
3960 Private::Words::const_iterator et = (itl->second).end();
3961 for (; it != et; ++it)
3968 void Paragraph::locateWord(pos_type & from, pos_type & to,
3969 word_location const loc) const
3972 case WHOLE_WORD_STRICT:
3973 if (from == 0 || from == size()
3974 || isWordSeparator(from)
3975 || isWordSeparator(from - 1)) {
3982 // If we are already at the beginning of a word, do nothing
3983 if (!from || isWordSeparator(from - 1))
3988 // always move the cursor to the beginning of previous word
3989 while (from && !isWordSeparator(from - 1))
3993 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3996 // no need to move the 'from' cursor
4000 while (to < size() && !isWordSeparator(to))
4005 void Paragraph::collectWords()
4007 for (pos_type pos = 0; pos < size(); ++pos) {
4008 if (isWordSeparator(pos))
4010 pos_type from = pos;
4011 locateWord(from, pos, WHOLE_WORD);
4012 // Work around MSVC warning: The statement
4013 // if (pos < from + lyxrc.completion_minlength)
4014 // triggers a signed vs. unsigned warning.
4015 // I don't know why this happens, it could be a MSVC bug, or
4016 // related to LLP64 (windows) vs. LP64 (unix) programming
4017 // model, or the C++ standard might be ambigous in the section
4018 // defining the "usual arithmetic conversions". However, using
4019 // a temporary variable is safe and works on all compilers.
4020 pos_type const endpos = from + lyxrc.completion_minlength;
4023 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
4024 if (cit == d->fontlist_.end())
4026 Language const * lang = cit->font().language();
4027 docstring const word = asString(from, pos, AS_STR_NONE);
4028 d->words_[lang->lang()].insert(word);
4033 void Paragraph::registerWords()
4035 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4036 Private::LangWordsMap::const_iterator ite = d->words_.end();
4037 for (; itl != ite; ++itl) {
4038 WordList & wl = theWordList(itl->first);
4039 Private::Words::const_iterator it = (itl->second).begin();
4040 Private::Words::const_iterator et = (itl->second).end();
4041 for (; it != et; ++it)
4047 void Paragraph::updateWords()
4055 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
4057 SkipPositionsIterator begin = skips.begin();
4058 SkipPositions::iterator end = skips.end();
4059 if (pos > 0 && begin < end) {
4061 if (end->last == pos - 1) {
4066 skips.insert(end, FontSpan(pos, pos));
4070 Language * Paragraph::Private::locateSpellRange(
4071 pos_type & from, pos_type & to,
4072 SkipPositions & skips) const
4074 // skip leading white space
4075 while (from < to && owner_->isWordSeparator(from))
4077 // don't check empty range
4080 // get current language
4081 Language * lang = getSpellLanguage(from);
4082 pos_type last = from;
4083 bool samelang = true;
4084 bool sameinset = true;
4085 while (last < to && samelang && sameinset) {
4086 // hop to end of word
4087 while (last < to && !owner_->isWordSeparator(last)) {
4088 if (owner_->getInset(last)) {
4089 appendSkipPosition(skips, last);
4090 } else if (owner_->isDeleted(last)) {
4091 appendSkipPosition(skips, last);
4095 // hop to next word while checking for insets
4096 while (sameinset && last < to && owner_->isWordSeparator(last)) {
4097 if (Inset const * inset = owner_->getInset(last))
4098 sameinset = inset->isChar() && inset->isLetter();
4099 if (sameinset && owner_->isDeleted(last)) {
4100 appendSkipPosition(skips, last);
4105 if (sameinset && last < to) {
4106 // now check for language change
4107 samelang = lang == getSpellLanguage(last);
4110 // if language change detected backstep is needed
4118 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
4121 const_cast<Language *>(owner_->getFontSettings(
4122 inset_owner_->buffer().params(), from).language());
4123 if (lang == inset_owner_->buffer().params().language
4124 && !lyxrc.spellchecker_alt_lang.empty()) {
4126 string const lang_variety =
4127 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
4128 lang->setCode(lang_code);
4129 lang->setVariety(lang_variety);
4135 void Paragraph::requestSpellCheck(pos_type pos)
4137 d->requestSpellCheck(pos);
4141 bool Paragraph::needsSpellCheck() const
4143 SpellChecker::ChangeNumber speller_change_number = 0;
4144 if (theSpellChecker())
4145 speller_change_number = theSpellChecker()->changeNumber();
4146 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
4147 d->speller_state_.needsCompleteRefresh(speller_change_number);
4149 return d->needsSpellCheck();
4153 bool Paragraph::Private::ignoreWord(docstring const & word) const
4155 // Ignore words with digits
4156 // FIXME: make this customizable
4157 // (note that some checkers ignore words with digits by default)
4158 docstring::const_iterator cit = word.begin();
4159 docstring::const_iterator const end = word.end();
4160 for (; cit != end; ++cit) {
4161 if (isNumber((*cit)))
4168 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
4169 WordLangTuple & wl, docstring_list & suggestions,
4170 bool do_suggestion, bool check_learned) const
4172 SpellChecker::Result result = SpellChecker::WORD_OK;
4173 SpellChecker * speller = theSpellChecker();
4177 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
4180 locateWord(from, to, WHOLE_WORD);
4181 if (from == to || from >= size())
4184 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4185 Language * lang = d->getSpellLanguage(from);
4187 wl = WordLangTuple(word, lang);
4192 if (needsSpellCheck() || check_learned) {
4194 if (!d->ignoreWord(word)) {
4195 bool const trailing_dot = to < size() && d->text_[to] == '.';
4196 result = speller->check(wl);
4197 if (SpellChecker::misspelled(result) && trailing_dot) {
4198 wl = WordLangTuple(word.append(from_ascii(".")), lang);
4199 result = speller->check(wl);
4200 if (!SpellChecker::misspelled(result)) {
4201 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
4203 from << ".." << to << "]");
4205 // spell check with dot appended failed too
4206 // restore original word/lang value
4207 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4208 wl = WordLangTuple(word, lang);
4212 if (!SpellChecker::misspelled(result)) {
4213 // area up to the begin of the next word is not misspelled
4214 while (end < size() && isWordSeparator(end))
4217 d->setMisspelled(from, end, result);
4219 result = d->speller_state_.getState(from);
4223 suggestions.clear();
4225 if (SpellChecker::misspelled(result)) {
4226 LYXERR(Debug::GUI, "misspelled word: \"" <<
4228 from << ".." << to << "]");
4230 speller->suggest(wl, suggestions);
4236 void Paragraph::anonymize()
4238 // This is a very crude anonymization for now
4239 for (char_type & c : d->text_)
4240 if (isLetterChar(c) || isNumber(c))
4245 void Paragraph::Private::markMisspelledWords(
4246 pos_type const & first, pos_type const & last,
4247 SpellChecker::Result result,
4248 docstring const & word,
4249 SkipPositions const & skips)
4251 if (!SpellChecker::misspelled(result)) {
4252 setMisspelled(first, last, SpellChecker::WORD_OK);
4256 SpellChecker * speller = theSpellChecker();
4257 // locate and enumerate the error positions
4258 int nerrors = speller->numMisspelledWords();
4260 SkipPositionsIterator it = skips.begin();
4261 SkipPositionsIterator et = skips.end();
4262 for (int index = 0; index < nerrors; ++index) {
4265 speller->misspelledWord(index, wstart, wlen);
4266 /// should not happen if speller supports range checks
4267 if (!wlen) continue;
4268 docstring const misspelled = word.substr(wstart, wlen);
4269 wstart += first + numskipped;
4270 if (snext < wstart) {
4271 /// mark the range of correct spelling
4272 numskipped += countSkips(it, et, wstart);
4273 setMisspelled(snext,
4274 wstart - 1, SpellChecker::WORD_OK);
4276 snext = wstart + wlen;
4277 numskipped += countSkips(it, et, snext);
4278 /// mark the range of misspelling
4279 setMisspelled(wstart, snext, result);
4280 LYXERR(Debug::GUI, "misspelled word: \"" <<
4281 misspelled << "\" [" <<
4282 wstart << ".." << (snext-1) << "]");
4285 if (snext <= last) {
4286 /// mark the range of correct spelling at end
4287 setMisspelled(snext, last, SpellChecker::WORD_OK);
4292 void Paragraph::spellCheck() const
4294 SpellChecker * speller = theSpellChecker();
4295 if (!speller || empty() ||!needsSpellCheck())
4299 d->rangeOfSpellCheck(start, endpos);
4300 if (speller->canCheckParagraph()) {
4301 // loop until we leave the range
4302 for (pos_type first = start; first < endpos; ) {
4303 pos_type last = endpos;
4304 Private::SkipPositions skips;
4305 Language * lang = d->locateSpellRange(first, last, skips);
4306 if (first >= endpos)
4308 // start the spell checker on the unit of meaning
4309 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
4310 WordLangTuple wl = WordLangTuple(word, lang);
4311 SpellChecker::Result result = word.size() ?
4312 speller->check(wl) : SpellChecker::WORD_OK;
4313 d->markMisspelledWords(first, last, result, word, skips);
4317 static docstring_list suggestions;
4318 pos_type to = endpos;
4319 while (start < endpos) {
4321 spellCheck(start, to, wl, suggestions, false);
4325 d->readySpellCheck();
4329 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
4331 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
4332 if (result || pos <= 0 || pos > size())
4334 if (check_boundary && (pos == size() || isWordSeparator(pos)))
4335 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
4340 string Paragraph::magicLabel() const
4343 ss << "magicparlabel-" << id();