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 "output_docbook.h"
41 #include "ParagraphParameters.h"
42 #include "SpellChecker.h"
44 #include "texstream.h"
45 #include "TextClass.h"
48 #include "WordLangTuple.h"
51 #include "frontends/alert.h"
53 #include "insets/InsetBibitem.h"
54 #include "insets/InsetLabel.h"
55 #include "insets/InsetSpecialChar.h"
56 #include "insets/InsetText.h"
58 #include "mathed/InsetMathHull.h"
60 #include "support/debug.h"
61 #include "support/docstring_list.h"
62 #include "support/ExceptionMessage.h"
63 #include "support/gettext.h"
64 #include "support/lassert.h"
65 #include "support/lstrings.h"
66 #include "support/textutils.h"
67 #include "output_docbook.h"
74 using namespace lyx::support;
76 // OSX clang, gcc < 4.8.0, and msvc < 2015 do not support C++11 thread_local
77 #if defined(__APPLE__) || (defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ < 8)
78 #define THREAD_LOCAL_STATIC static __thread
79 #elif defined(_MSC_VER) && (_MSC_VER < 1900)
80 #define THREAD_LOCAL_STATIC static __declspec(thread)
82 #define THREAD_LOCAL_STATIC thread_local static
89 /// Inset identifier (above 0x10ffff, for ucs-4)
90 char_type const META_INSET = 0x200001;
95 /////////////////////////////////////////////////////////////////////
99 /////////////////////////////////////////////////////////////////////
101 class SpellResultRange {
103 SpellResultRange(FontSpan range, SpellChecker::Result result)
104 : range_(range), result_(result)
107 FontSpan const & range() const { return range_; }
109 void range(FontSpan const & r) { range_ = r; }
111 SpellChecker::Result result() const { return result_; }
113 void result(SpellChecker::Result r) { result_ = r; }
115 bool contains(pos_type pos) const { return range_.contains(pos); }
117 bool covered(FontSpan const & r) const
119 // 1. first of new range inside current range or
120 // 2. last of new range inside current range or
121 // 3. first of current range inside new range or
122 // 4. last of current range inside new range
123 //FIXME: is this the same as !range_.intersect(r).empty() ?
124 return range_.contains(r.first) || range_.contains(r.last) ||
125 r.contains(range_.first) || r.contains(range_.last);
128 void shift(pos_type pos, int offset)
130 if (range_.first > pos) {
131 range_.first += offset;
132 range_.last += offset;
133 } else if (range_.last >= pos) {
134 range_.last += offset;
139 SpellChecker::Result result_ ;
143 /////////////////////////////////////////////////////////////////////
147 /////////////////////////////////////////////////////////////////////
149 class SpellCheckerState {
153 needs_refresh_ = true;
154 current_change_number_ = 0;
157 void setRange(FontSpan const & fp, SpellChecker::Result state)
160 RangesIterator et = ranges_.end();
161 RangesIterator it = ranges_.begin();
162 for (; it != et; ++it) {
163 if (!it->covered(fp))
164 result.push_back(SpellResultRange(it->range(), it->result()));
165 else if (state == SpellChecker::WORD_OK) {
166 // trim or split the current misspelled range
167 // store misspelled ranges only
168 FontSpan range = it->range();
169 if (fp.first > range.first) {
170 // misspelled area in front of WORD_OK
171 range.last = fp.first - 1;
172 result.push_back(SpellResultRange(range, it->result()));
175 if (fp.last < range.last) {
176 // misspelled area after WORD_OK range
177 range.first = fp.last + 1;
178 result.push_back(SpellResultRange(range, it->result()));
183 if (state != SpellChecker::WORD_OK)
184 ranges_.push_back(SpellResultRange(fp, state));
187 void increasePosAfterPos(pos_type pos)
189 correctRangesAfterPos(pos, 1);
193 void decreasePosAfterPos(pos_type pos)
195 correctRangesAfterPos(pos, -1);
199 void refreshLast(pos_type pos)
201 if (pos < refresh_.last)
205 SpellChecker::Result getState(pos_type pos) const
207 SpellChecker::Result result = SpellChecker::WORD_OK;
208 RangesIterator et = ranges_.end();
209 RangesIterator it = ranges_.begin();
210 for (; it != et; ++it) {
211 if(it->contains(pos)) {
218 FontSpan const & getRange(pos_type pos) const
220 /// empty span to indicate mismatch
221 static FontSpan empty_;
222 RangesIterator et = ranges_.end();
223 RangesIterator it = ranges_.begin();
224 for (; it != et; ++it) {
225 if(it->contains(pos)) {
232 bool needsRefresh() const
234 return needs_refresh_;
237 SpellChecker::ChangeNumber currentChangeNumber() const
239 return current_change_number_;
242 void refreshRange(pos_type & first, pos_type & last) const
244 first = refresh_.first;
245 last = refresh_.last;
248 void needsRefresh(pos_type pos)
250 if (needs_refresh_ && pos != -1) {
251 if (pos < refresh_.first)
252 refresh_.first = pos;
253 if (pos > refresh_.last)
255 } else if (pos != -1) {
256 // init request check for neighbour positions too
257 refresh_.first = pos > 0 ? pos - 1 : 0;
258 // no need for special end of paragraph check
259 refresh_.last = pos + 1;
261 needs_refresh_ = pos != -1;
264 void needsCompleteRefresh(SpellChecker::ChangeNumber change_number)
266 needs_refresh_ = true;
269 current_change_number_ = change_number;
272 typedef vector<SpellResultRange> Ranges;
273 typedef Ranges::const_iterator RangesIterator;
275 /// the area of the paragraph with pending spell check
278 /// spell state cache version number
279 SpellChecker::ChangeNumber current_change_number_;
282 void correctRangesAfterPos(pos_type pos, int offset)
284 RangesIterator et = ranges_.end();
285 Ranges::iterator it = ranges_.begin();
286 for (; it != et; ++it) {
287 it->shift(pos, offset);
293 /////////////////////////////////////////////////////////////////////
295 // Paragraph::Private
297 /////////////////////////////////////////////////////////////////////
299 class Paragraph::Private
301 // Enforce our own "copy" constructor
302 Private(Private const &) = delete;
303 Private & operator=(Private const &) = delete;
304 // Unique ID generator
305 static int make_id();
308 Private(Paragraph * owner, Layout const & layout);
309 /// "Copy constructor"
310 Private(Private const &, Paragraph * owner);
311 /// Copy constructor from \p beg to \p end
312 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
315 void insertChar(pos_type pos, char_type c, Change const & change);
317 /// Output the surrogate pair formed by \p c and \p next to \p os.
318 /// \return the number of characters written.
319 int latexSurrogatePair(BufferParams const &, otexstream & os,
320 char_type c, char_type next,
321 OutputParams const &);
323 /// Output a space in appropriate formatting (or a surrogate pair
324 /// if the next character is a combining character).
325 /// \return whether a surrogate pair was output.
326 bool simpleTeXBlanks(BufferParams const &,
327 OutputParams const &,
330 unsigned int & column,
332 Layout const & style);
334 /// This could go to ParagraphParameters if we want to.
335 int startTeXParParams(BufferParams const &, otexstream &,
336 OutputParams const &) const;
338 /// This could go to ParagraphParameters if we want to.
339 bool endTeXParParams(BufferParams const &, otexstream &,
340 OutputParams const &) const;
343 void latexInset(BufferParams const &,
348 Font const & outerfont,
350 Change & running_change,
351 Layout const & style,
353 unsigned int & column);
356 void latexSpecialChar(
358 BufferParams const & bparams,
359 OutputParams const & runparams,
360 Font const & running_font,
361 string & alien_script,
362 Layout const & style,
365 unsigned int & column);
372 unsigned int & column);
378 unsigned int & column);
384 unsigned int & column);
387 void validate(LaTeXFeatures & features) const;
389 /// Checks if the paragraph contains only text and no inset or font change.
390 bool onlyText(Buffer const & buf, Font const & outerfont,
391 pos_type initial) const;
393 /// a vector of speller skip positions
394 typedef vector<FontSpan> SkipPositions;
395 typedef SkipPositions::const_iterator SkipPositionsIterator;
397 void appendSkipPosition(SkipPositions & skips, pos_type const pos) const;
399 Language * getSpellLanguage(pos_type const from) const;
401 Language * locateSpellRange(pos_type & from, pos_type & to,
402 SkipPositions & skips) const;
404 bool hasSpellerChange() const
406 SpellChecker::ChangeNumber speller_change_number = 0;
407 if (theSpellChecker())
408 speller_change_number = theSpellChecker()->changeNumber();
409 return speller_change_number > speller_state_.currentChangeNumber();
412 bool ignoreWord(docstring const & word) const ;
414 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
416 pos_type textsize = owner_->size();
417 // check for sane arguments
418 if (to <= from || from >= textsize)
420 FontSpan fp = FontSpan(from, to - 1);
421 speller_state_.setRange(fp, state);
424 void requestSpellCheck(pos_type pos)
427 speller_state_.needsCompleteRefresh(speller_state_.currentChangeNumber());
429 speller_state_.needsRefresh(pos);
432 void readySpellCheck()
434 speller_state_.needsRefresh(-1);
437 bool needsSpellCheck() const
439 return speller_state_.needsRefresh();
442 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
444 speller_state_.refreshRange(first, last);
446 last = owner_->size();
449 pos_type endpos = last;
450 owner_->locateWord(first, endpos, WHOLE_WORD, true);
453 owner_->locateWord(last, endpos, WHOLE_WORD, true);
458 int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
462 while (it != et && it->first < start) {
463 int skip = it->last - it->first + 1;
471 void markMisspelledWords(pos_type const & first, pos_type const & last,
472 SpellChecker::Result result,
473 docstring const & word,
474 SkipPositions const & skips);
476 InsetCode ownerCode() const
478 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
481 /// Which Paragraph owns us?
485 Inset const * inset_owner_;
494 ParagraphParameters params_;
496 /// for recording and looking up changes
500 InsetList insetlist_;
503 pos_type begin_of_body_;
505 typedef docstring TextContainer;
509 typedef set<docstring> Words;
510 typedef map<string, Words> LangWordsMap;
514 Layout const * layout_;
516 SpellCheckerState speller_state_;
520 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
521 : owner_(owner), inset_owner_(nullptr), id_(-1), begin_of_body_(0), layout_(&layout)
528 int Paragraph::Private::make_id()
530 // The id is unique per session across buffers because it is used in
531 // LFUN_PARAGRAPH_GOTO to switch to a different buffer, for instance in the
534 static atomic_uint next_id(0);
539 Paragraph::Private::Private(Private const & p, Paragraph * owner)
540 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
542 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
543 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
546 requestSpellCheck(p.text_.size());
550 Paragraph::Private::Private(Private const & p, Paragraph * owner,
551 pos_type beg, pos_type end)
552 : owner_(owner), inset_owner_(p.inset_owner_), id_(make_id()),
553 params_(p.params_), changes_(p.changes_),
554 insetlist_(p.insetlist_, beg, end),
555 begin_of_body_(p.begin_of_body_), words_(p.words_),
558 if (beg >= pos_type(p.text_.size()))
560 text_ = p.text_.substr(beg, end - beg);
562 FontList::const_iterator fcit = fontlist_.begin();
563 FontList::const_iterator fend = fontlist_.end();
564 for (; fcit != fend; ++fcit) {
565 if (fcit->pos() < beg)
567 if (fcit->pos() >= end) {
568 // Add last entry in the fontlist_.
569 fontlist_.set(text_.size() - 1, fcit->font());
572 // Add a new entry in the fontlist_.
573 fontlist_.set(fcit->pos() - beg, fcit->font());
575 requestSpellCheck(p.text_.size());
579 void Paragraph::addChangesToToc(DocIterator const & cdit, Buffer const & buf,
580 bool output_active, TocBackend & backend) const
582 d->changes_.addToToc(cdit, buf, output_active, backend);
586 bool Paragraph::isDeleted(pos_type start, pos_type end) const
588 LASSERT(start >= 0 && start <= size(), return false);
589 LASSERT(end > start && end <= size() + 1, return false);
591 return d->changes_.isDeleted(start, end);
595 bool Paragraph::isChanged(pos_type start, pos_type end) const
597 LASSERT(start >= 0 && start <= size(), return false);
598 LASSERT(end > start && end <= size() + 1, return false);
600 return d->changes_.isChanged(start, end);
603 // FIXME: Ideally the diverse isChanged() methods should account for that!
604 bool Paragraph::hasChangedInsets(pos_type start, pos_type end) const
606 LASSERT(start >= 0 && start <= size(), return false);
607 LASSERT(end > start && end <= size() + 1, return false);
609 for (auto const & icit : d->insetlist_) {
610 if (icit.pos < start)
614 if (icit.inset && icit.inset->isChanged())
620 bool Paragraph::isChanged() const
622 return d->changes_.isChanged();
626 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
628 // keep the logic here in sync with the logic of eraseChars()
632 Change const & change = d->changes_.lookup(size());
633 return change.inserted() && change.currentAuthor();
636 Change Paragraph::parEndChange() const
638 return d->changes_.lookup(size());
642 void Paragraph::setChange(Change const & change)
644 // beware of the imaginary end-of-par character!
645 d->changes_.set(change, 0, size() + 1);
648 * Propagate the change recursively - but not in case of DELETED!
650 * Imagine that your co-author makes changes in an existing inset. He
651 * sends your document to you and you come to the conclusion that the
652 * inset should go completely. If you erase it, LyX must not delete all
653 * text within the inset. Otherwise, the change tracked insertions of
654 * your co-author get lost and there is no way to restore them later.
656 * Conclusion: An inset's content should remain untouched if you delete it
659 if (!change.deleted()) {
660 for (pos_type pos = 0; pos < size(); ++pos) {
661 if (Inset * inset = getInset(pos))
662 inset->setChange(change);
668 void Paragraph::setChange(pos_type pos, Change const & change)
670 LASSERT(pos >= 0 && pos <= size(), return);
671 d->changes_.set(change, pos);
673 // see comment in setChange(Change const &) above
674 if (!change.deleted() && pos < size())
675 if (Inset * inset = getInset(pos))
676 inset->setChange(change);
680 Change const & Paragraph::lookupChange(pos_type pos) const
682 LBUFERR(pos >= 0 && pos <= size());
683 return d->changes_.lookup(pos);
687 void Paragraph::acceptChanges(pos_type start, pos_type end)
689 LASSERT(start >= 0 && start <= size(), return);
690 LASSERT(end > start && end <= size() + 1, return);
692 for (pos_type pos = start; pos < end; ++pos) {
693 switch (lookupChange(pos).type) {
694 case Change::UNCHANGED:
695 // accept changes in nested inset
696 if (Inset * inset = getInset(pos))
697 inset->acceptChanges();
700 case Change::INSERTED:
701 d->changes_.set(Change(Change::UNCHANGED), pos);
702 // also accept changes in nested inset
703 if (Inset * inset = getInset(pos))
704 inset->acceptChanges();
707 case Change::DELETED:
708 // Suppress access to non-existent
709 // "end-of-paragraph char"
711 eraseChar(pos, false);
722 void Paragraph::rejectChanges(pos_type start, pos_type end)
724 LASSERT(start >= 0 && start <= size(), return);
725 LASSERT(end > start && end <= size() + 1, return);
727 for (pos_type pos = start; pos < end; ++pos) {
728 switch (lookupChange(pos).type) {
729 case Change::UNCHANGED:
730 // reject changes in nested inset
731 if (Inset * inset = getInset(pos))
732 inset->rejectChanges();
735 case Change::INSERTED:
736 // Suppress access to non-existent
737 // "end-of-paragraph char"
739 eraseChar(pos, false);
745 case Change::DELETED:
746 d->changes_.set(Change(Change::UNCHANGED), pos);
748 // Do NOT reject changes within a deleted inset!
749 // There may be insertions of a co-author inside of it!
757 void Paragraph::Private::insertChar(pos_type pos, char_type c,
758 Change const & change)
760 LASSERT(pos >= 0 && pos <= int(text_.size()), return);
763 changes_.insert(change, pos);
765 // This is actually very common when parsing buffers (and
766 // maybe inserting ascii text)
767 if (pos == pos_type(text_.size())) {
768 // when appending characters, no need to update tables
770 // but we want spell checking
771 requestSpellCheck(pos);
775 text_.insert(text_.begin() + pos, c);
777 // Update the font table.
778 fontlist_.increasePosAfterPos(pos);
781 insetlist_.increasePosAfterPos(pos);
783 // Update list of misspelled positions
784 speller_state_.increasePosAfterPos(pos);
788 bool Paragraph::insertInset(pos_type pos, Inset * inset,
789 Font const & font, Change const & change)
791 LASSERT(inset, return false);
792 LASSERT(pos >= 0 && pos <= size(), return false);
794 // Paragraph::insertInset() can be used in cut/copy/paste operation where
795 // d->inset_owner_ is not set yet.
796 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
799 d->insertChar(pos, META_INSET, change);
800 LASSERT(d->text_[pos] == META_INSET, return false);
802 // Add a new entry in the insetlist_.
803 d->insetlist_.insert(inset, pos);
805 // Some insets require run of spell checker
806 requestSpellCheck(pos);
812 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
814 LASSERT(pos >= 0 && pos <= size(), return false);
816 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
819 Change change = d->changes_.lookup(pos);
821 // set the character to DELETED if
822 // a) it was previously unchanged or
823 // b) it was inserted by a co-author
825 if (!change.changed() ||
826 (change.inserted() && !change.currentAuthor())) {
827 setChange(pos, Change(Change::DELETED));
828 // request run of spell checker
829 requestSpellCheck(pos);
833 if (change.deleted())
837 // Don't physically access the imaginary end-of-paragraph character.
838 // eraseChar() can only mark it as DELETED. A physical deletion of
839 // end-of-par must be handled externally.
845 d->changes_.erase(pos);
847 // if it is an inset, delete the inset entry
848 if (d->text_[pos] == META_INSET)
849 d->insetlist_.erase(pos);
851 d->text_.erase(d->text_.begin() + pos);
853 // Update the fontlist_
854 d->fontlist_.erase(pos);
856 // Update the insetlist_
857 d->insetlist_.decreasePosAfterPos(pos);
859 // Update list of misspelled positions
860 d->speller_state_.decreasePosAfterPos(pos);
861 d->speller_state_.refreshLast(size());
867 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
869 LASSERT(start >= 0 && start <= size(), return 0);
870 LASSERT(end >= start && end <= size() + 1, return 0);
873 for (pos_type count = end - start; count; --count) {
874 if (!eraseChar(i, trackChanges))
880 // Handle combining characters
881 int Paragraph::Private::latexSurrogatePair(BufferParams const & bparams,
882 otexstream & os, char_type c, char_type next,
883 OutputParams const & runparams)
885 // Writing next here may circumvent a possible font change between
886 // c and next. Since next is only output if it forms a surrogate pair
887 // with c we can ignore this:
888 // A font change inside a surrogate pair does not make sense and is
889 // hopefully impossible to input.
890 // FIXME: change tracking
891 // Is this correct WRT change tracking?
892 Encoding const & encoding = *(runparams.encoding);
893 docstring latex1 = encoding.latexChar(next).first;
894 if (runparams.inIPA) {
895 string const tipashortcut = Encodings::TIPAShortcut(next);
896 if (!tipashortcut.empty()) {
897 latex1 = from_ascii(tipashortcut);
900 docstring latex2 = encoding.latexChar(c).first;
902 if (bparams.useNonTeXFonts || docstring(1, next) == latex1) {
903 // Encoding supports the combination:
904 // output as is (combining char after base char).
905 os << latex2 << latex1;
906 return latex1.length() + latex2.length();
909 os << latex1 << "{" << latex2 << "}";
910 return latex1.length() + latex2.length() + 2;
914 bool Paragraph::Private::simpleTeXBlanks(BufferParams const & bparams,
915 OutputParams const & runparams,
918 unsigned int & column,
920 Layout const & style)
922 if (style.pass_thru || runparams.pass_thru)
925 if (i + 1 < int(text_.size())) {
926 char_type next = text_[i + 1];
927 if (Encodings::isCombiningChar(next)) {
928 // This space has an accent, so we must always output it.
929 column += latexSurrogatePair(bparams, os, ' ', next, runparams) - 1;
934 if (runparams.linelen > 0
935 && column > runparams.linelen
937 && text_[i - 1] != ' '
938 && (i + 1 < int(text_.size()))
939 // same in FreeSpacing mode
940 && !owner_->isFreeSpacing()
941 // In typewriter mode, we want to avoid
942 // ! . ? : at the end of a line
943 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
944 && (text_[i - 1] == '.'
945 || text_[i - 1] == '?'
946 || text_[i - 1] == ':'
947 || text_[i - 1] == '!'))) {
949 os.texrow().start(owner_->id(), i + 1);
951 } else if (style.free_spacing) {
960 void Paragraph::Private::latexInset(BufferParams const & bparams,
962 OutputParams & runparams,
965 Font const & outerfont,
967 Change & running_change,
968 Layout const & style,
970 unsigned int & column)
972 Inset * inset = owner_->getInset(i);
975 if (style.pass_thru) {
976 odocstringstream ods;
977 inset->plaintext(ods, runparams);
982 // FIXME: move this to InsetNewline::latex
983 if (inset->lyxCode() == NEWLINE_CODE || inset->lyxCode() == SEPARATOR_CODE) {
984 // newlines are handled differently here than
985 // the default in simpleTeXSpecialChars().
986 if (!style.newline_allowed) {
990 bool needPar = false;
991 column += running_font.latexWriteEndChanges(
992 os, bparams, runparams,
993 basefont, basefont, needPar);
997 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
1000 basefont = owner_->getLayoutFont(bparams, outerfont);
1001 running_font = basefont;
1003 if (runparams.moving_arg)
1007 os.texrow().start(owner_->id(), i + 1);
1011 if (owner_->isDeleted(i)) {
1012 if( ++runparams.inDeletedInset == 1)
1013 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1016 if (inset->canTrackChanges()) {
1017 column += Changes::latexMarkChange(os, bparams, running_change,
1018 Change(Change::UNCHANGED), runparams);
1019 running_change = Change(Change::UNCHANGED);
1023 odocstream::pos_type const len = os.os().tellp();
1025 if (inset->forceLTR(runparams)
1026 && running_font.isRightToLeft()
1027 // ERT is an exception, it should be output with no
1028 // decorations at all
1029 && inset->lyxCode() != ERT_CODE) {
1030 if (runparams.use_polyglossia) {
1032 } else if (running_font.language()->lang() == "farsi"
1033 || running_font.language()->lang() == "arabic_arabi")
1034 os << "\\textLR{" << termcmd;
1040 // FIXME: Bug: we can have an empty font change here!
1041 // if there has just been a font change, we are going to close it
1042 // right now, which means stupid latex code like \textsf{}. AFAIK,
1043 // this does not harm dvi output. A minor bug, thus (JMarc)
1045 // Some insets cannot be inside a font change command.
1046 // However, even such insets *can* be placed in \L or \R
1047 // or their equivalents (for RTL language switches), so we don't
1048 // close the language in those cases.
1049 // ArabTeX, though, cannot handle this special behavior, it seems.
1050 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
1051 || running_font.language()->lang() == "arabic_arabtex";
1052 if (open_font && !inset->inheritFont()) {
1053 bool needPar = false;
1054 bool closeLanguage = arabtex
1055 || basefont.isRightToLeft() == running_font.isRightToLeft();
1056 unsigned int count = running_font.latexWriteEndChanges(os,
1057 bparams, runparams, basefont, basefont,
1058 needPar, closeLanguage);
1060 // if any font properties were closed, update the running_font,
1061 // making sure, however, to leave the language as it was
1063 // FIXME: probably a better way to keep track of the old
1064 // language, than copying the entire font?
1065 Font const copy_font(running_font);
1066 basefont = owner_->getLayoutFont(bparams, outerfont);
1067 running_font = basefont;
1069 running_font.setLanguage(copy_font.language());
1070 // leave font open if language is still open
1071 open_font = (running_font.language() == basefont.language());
1073 runparams.local_font = &basefont;
1077 size_t const previous_row_count = os.texrow().rows();
1080 runparams.lastid = id_;
1081 runparams.lastpos = i;
1082 inset->latex(os, runparams);
1083 } catch (EncodingException & e) {
1084 // add location information and throw again.
1093 if (os.texrow().rows() > previous_row_count) {
1094 os.texrow().start(owner_->id(), i + 1);
1097 column += (unsigned int)(os.os().tellp() - len);
1100 if (owner_->isDeleted(i))
1101 --runparams.inDeletedInset;
1105 void Paragraph::Private::latexSpecialChar(otexstream & os,
1106 BufferParams const & bparams,
1107 OutputParams const & runparams,
1108 Font const & running_font,
1109 string & alien_script,
1110 Layout const & style,
1113 unsigned int & column)
1115 char_type const c = owner_->getUChar(bparams, runparams, i);
1117 if (style.pass_thru || runparams.pass_thru
1118 || contains(style.pass_thru_chars, c)
1119 || contains(runparams.pass_thru_chars, c)) {
1121 Encoding const * const enc = runparams.encoding;
1122 if (enc && !enc->encodable(c))
1123 throw EncodingException(c);
1129 // TIPA uses its own T3 encoding
1130 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1132 // If T1 font encoding is used, use the special
1133 // characters it provides.
1134 // NOTE: Some languages reset the font encoding internally to a
1135 // non-standard font encoding. If we are using such a language,
1136 // we do not output special T1 chars.
1137 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1138 && !runparams.isFullUnicode() && bparams.main_font_encoding() == "T1"
1139 && latexSpecialT1(c, os, i, column))
1141 // NOTE: "fontspec" (non-TeX fonts) sets the font encoding to "TU" (untill 2017 "EU1" or "EU2")
1142 else if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1143 && runparams.isFullUnicode() && latexSpecialTU(c, os, i, column))
1146 // Otherwise, we use what LaTeX provides us.
1149 os << "\\textbackslash" << termcmd;
1153 os << "\\textless" << termcmd;
1157 os << "\\textgreater" << termcmd;
1161 os << "\\textbar" << termcmd;
1166 if (i + 1 < static_cast<pos_type>(text_.size()) &&
1167 (end_pos == -1 || i + 1 < end_pos) &&
1168 text_[i+1] == '-') {
1169 // Prevent "--" becoming an en dash and "---" an em dash.
1170 // (Within \ttfamily, "---" is merged to en dash + hyphen.)
1176 os << "\\textquotedbl" << termcmd;
1181 case '%': case '#': case '{':
1189 os << "\\textasciitilde" << termcmd;
1194 os << "\\textasciicircum" << termcmd;
1201 // avoid being mistaken for optional arguments
1209 // Blanks are printed before font switching.
1210 // Sure? I am not! (try nice-latex)
1211 // I am sure it's correct. LyX might be smarter
1212 // in the future, but for now, nothing wrong is
1218 // XeTeX's dash behaviour is determined via a global setting
1219 if (bparams.use_dash_ligatures
1220 && owner_->getFontSettings(bparams, i).fontInfo().family() != TYPEWRITER_FAMILY
1222 // TODO #10961: && not in inset Flex Code
1223 // TODO #10961: && not in layout LyXCode
1224 && (!bparams.useNonTeXFonts || runparams.flavor != OutputParams::XETEX)) {
1241 Encoding const & encoding = *(runparams.encoding);
1242 char_type next = '\0';
1243 if (i + 1 < int(text_.size())) {
1244 next = text_[i + 1];
1245 if (Encodings::isCombiningChar(next)) {
1246 column += latexSurrogatePair(bparams, os, c, next, runparams) - 1;
1251 pair<docstring, bool> latex = encoding.latexChar(c);
1252 docstring nextlatex;
1253 bool nexttipas = false;
1254 string nexttipashortcut;
1255 if (next != '\0' && next != META_INSET && !encoding.encodable(next)) {
1256 nextlatex = encoding.latexChar(next).first;
1257 if (runparams.inIPA) {
1258 nexttipashortcut = Encodings::TIPAShortcut(next);
1259 nexttipas = !nexttipashortcut.empty();
1263 if (runparams.inIPA) {
1264 string const tipashortcut = Encodings::TIPAShortcut(c);
1265 if (!tipashortcut.empty()) {
1266 latex.first = from_ascii(tipashortcut);
1267 latex.second = false;
1271 // eventually close "script wrapper" command (see `Paragraph::latex`)
1272 if (!alien_script.empty()
1273 && alien_script != Encodings::isKnownScriptChar(next)) {
1274 column += latex.first.length();
1275 alien_script.clear();
1276 os << latex.first << "}";
1280 && ((!prefixIs(nextlatex, '\\')
1281 && !prefixIs(nextlatex, '{')
1282 && !prefixIs(nextlatex, '}'))
1284 && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1286 // Prevent eating of a following space or command corruption by
1287 // following characters
1288 if (next == ' ' || next == '\0') {
1289 column += latex.first.length() + 1;
1290 os << latex.first << "{}";
1292 column += latex.first.length();
1293 os << latex.first << " ";
1296 column += latex.first.length() - 1;
1304 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1305 pos_type i, unsigned int & column)
1311 // In T1 encoding, these characters exist
1312 // but we should avoid ligatures
1313 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1315 os << "\\textcompwordmark" << termcmd;
1322 // soul.sty breaks with \char`\"
1323 os << "\\textquotedbl" << termcmd;
1332 bool Paragraph::Private::latexSpecialTU(char_type const c, otexstream & os,
1333 pos_type i, unsigned int & column)
1335 // TU encoding is currently on par with T1.
1336 return latexSpecialT1(c, os, i, column);
1340 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1341 pos_type /*i*/, unsigned int & column)
1351 os << "\\textvertline" << termcmd;
1360 void Paragraph::Private::validate(LaTeXFeatures & features) const
1362 if (layout_->inpreamble && inset_owner_) {
1363 // FIXME: Using a string stream here circumvents the encoding
1364 // switching machinery of odocstream. Therefore the
1365 // output is wrong if this paragraph contains content
1366 // that needs to switch encoding.
1367 Buffer const & buf = inset_owner_->buffer();
1368 otexstringstream os;
1369 os << layout_->preamble();
1370 size_t const length = os.length();
1371 TeXOnePar(buf, *inset_owner_->getText(int(buf.getParFromID(owner_->id()).idx())),
1372 buf.getParFromID(owner_->id()).pit(), os,
1373 features.runparams(), string(), 0, -1, true);
1374 if (os.length() > length)
1375 features.addPreambleSnippet(os.release(), true);
1378 if (features.runparams().flavor == OutputParams::HTML
1379 && layout_->htmltitle()) {
1380 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1383 // check the params.
1384 if (!params_.spacing().isDefault())
1385 features.require("setspace");
1388 features.useLayout(layout_->name());
1391 fontlist_.validate(features);
1393 // then the indentation
1394 if (!params_.leftIndent().zero())
1395 features.require("ParagraphLeftIndent");
1398 InsetList::const_iterator icit = insetlist_.begin();
1399 InsetList::const_iterator iend = insetlist_.end();
1400 for (; icit != iend; ++icit) {
1402 features.inDeletedInset(owner_->isDeleted(icit->pos));
1403 if (icit->inset->lyxCode() == FOOT_CODE) {
1404 // FIXME: an item inset would make things much easier.
1405 if ((layout_->latextype == LATEX_LIST_ENVIRONMENT
1406 || (layout_->latextype == LATEX_ITEM_ENVIRONMENT
1407 && layout_->margintype == MARGIN_FIRST_DYNAMIC))
1408 && (icit->pos < begin_of_body_
1409 || (icit->pos == begin_of_body_
1410 && (icit->pos == 0 || text_[icit->pos - 1] != ' '))))
1411 features.saveNoteEnv("description");
1413 icit->inset->validate(features);
1414 features.inDeletedInset(false);
1415 if (layout_->needprotect &&
1416 icit->inset->lyxCode() == FOOT_CODE)
1417 features.require("NeedLyXFootnoteCode");
1421 // then the contents
1422 BufferParams const bp = features.runparams().is_child
1423 ? features.buffer().masterParams() : features.buffer().params();
1424 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1425 char_type c = text_[i];
1426 CharInfo const & ci = Encodings::unicodeCharInfo(c);
1428 if (features.runparams().isFullUnicode() && bp.useNonTeXFonts)
1429 features.require("textquotedblp");
1430 else if (bp.main_font_encoding() != "T1"
1431 || ((&owner_->getFontSettings(bp, i))->language()->internalFontEncoding()))
1432 features.require("textquotedbl");
1433 } else if (ci.textfeature() && contains(ci.textpreamble(), '=')) {
1434 // features that depend on the font or input encoding
1435 string feats = ci.textpreamble();
1436 string fontenc = (&owner_->getFontSettings(bp, i))->language()->fontenc(bp);
1437 if (fontenc.empty())
1438 fontenc = features.runparams().main_fontenc;
1439 while (!feats.empty()) {
1441 feats = split(feats, feat, ',');
1442 if (contains(feat, "!=")) {
1443 // a feature that is required except for the spcified
1444 // font or input encodings
1446 string const contexts = ltrim(split(feat, realfeature, '!'), "=");
1447 // multiple encodings are separated by semicolon
1448 vector<string> context = getVectorFromString(contexts, ";");
1449 // require feature if the context matches neither current font
1450 // nor input encoding
1451 if (std::find(context.begin(), context.end(), fontenc) == context.end()
1452 && std::find(context.begin(), context.end(),
1453 features.runparams().encoding->name()) == context.end())
1454 features.require(realfeature);
1455 } else if (contains(feat, '=')) {
1456 // a feature that is required only for the spcified
1457 // font or input encodings
1459 string const contexts = split(feat, realfeature, '=');
1460 // multiple encodings are separated by semicolon
1461 vector<string> context = getVectorFromString(contexts, ";");
1462 // require feature if the context matches either current font
1463 // or input encoding
1464 if (std::find(context.begin(), context.end(), fontenc) != context.end()
1465 || std::find(context.begin(), context.end(),
1466 features.runparams().encoding->name()) != context.end())
1467 features.require(realfeature);
1470 } else if (!bp.use_dash_ligatures
1471 && (c == 0x2013 || c == 0x2014)
1472 && bp.useNonTeXFonts
1473 && features.runparams().flavor == OutputParams::XETEX)
1474 // XeTeX's dash behaviour is determined via a global setting
1475 features.require("xetexdashbreakstate");
1476 BufferEncodings::validate(c, features);
1480 /////////////////////////////////////////////////////////////////////
1484 /////////////////////////////////////////////////////////////////////
1487 Layout const emptyParagraphLayout;
1490 Paragraph::Paragraph()
1491 : d(new Paragraph::Private(this, emptyParagraphLayout))
1498 Paragraph::Paragraph(Paragraph const & par)
1499 : itemdepth(par.itemdepth),
1500 d(new Paragraph::Private(*par.d, this))
1506 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1507 : itemdepth(par.itemdepth),
1508 d(new Paragraph::Private(*par.d, this, beg, end))
1514 Paragraph & Paragraph::operator=(Paragraph const & par)
1516 // needed as we will destroy the private part before copying it
1518 itemdepth = par.itemdepth;
1522 d = new Private(*par.d, this);
1529 Paragraph::~Paragraph()
1538 // this shall be called just before every "os << ..." action.
1539 void flushString(ostream & os, docstring & s)
1548 void Paragraph::write(ostream & os, BufferParams const & bparams,
1549 depth_type & dth) const
1551 // The beginning or end of a deeper (i.e. nested) area?
1552 if (dth != d->params_.depth()) {
1553 if (d->params_.depth() > dth) {
1554 while (d->params_.depth() > dth) {
1555 os << "\n\\begin_deeper";
1559 while (d->params_.depth() < dth) {
1560 os << "\n\\end_deeper";
1566 // First write the layout
1567 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1569 d->params_.write(os);
1571 Font font1(inherit_font, bparams.language);
1573 Change running_change = Change(Change::UNCHANGED);
1575 // this string is used as a buffer to avoid repetitive calls
1576 // to to_utf8(), which turn out to be expensive (JMarc)
1577 docstring write_buffer;
1580 for (pos_type i = 0; i <= size(); ++i) {
1582 Change const & change = lookupChange(i);
1583 if (change != running_change)
1584 flushString(os, write_buffer);
1585 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1586 running_change = change;
1591 // Write font changes
1592 Font font2 = getFontSettings(bparams, i);
1593 if (font2 != font1) {
1594 flushString(os, write_buffer);
1595 font2.lyxWriteChanges(font1, os);
1600 char_type const c = d->text_[i];
1603 if (Inset const * inset = getInset(i)) {
1604 flushString(os, write_buffer);
1605 if (inset->directWrite()) {
1606 // international char, let it write
1607 // code directly so it's shorter in
1613 os << "\\begin_inset ";
1615 os << "\n\\end_inset\n\n";
1618 // FIXME This can be removed again once the mystery
1619 // crash has been resolved.
1624 flushString(os, write_buffer);
1625 os << "\n\\backslash\n";
1629 flushString(os, write_buffer);
1630 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1637 if ((column > 70 && c == ' ')
1639 flushString(os, write_buffer);
1643 // this check is to amend a bug. LyX sometimes
1644 // inserts '\0' this could cause problems.
1646 write_buffer.push_back(c);
1648 LYXERR0("NUL char in structure.");
1654 flushString(os, write_buffer);
1655 os << "\n\\end_layout\n";
1656 // FIXME This can be removed again once the mystery
1657 // crash has been resolved.
1662 void Paragraph::validate(LaTeXFeatures & features) const
1664 d->validate(features);
1665 bool fragile = features.runparams().moving_arg;
1666 fragile |= layout().needprotect;
1667 if (inInset().getLayout().isNeedProtect())
1669 if (needsCProtection(fragile))
1670 features.require("cprotect");
1674 void Paragraph::insert(pos_type start, docstring const & str,
1675 Font const & font, Change const & change)
1677 for (size_t i = 0, n = str.size(); i != n ; ++i)
1678 insertChar(start + i, str[i], font, change);
1682 void Paragraph::appendChar(char_type c, Font const & font,
1683 Change const & change)
1686 d->changes_.insert(change, d->text_.size());
1687 // when appending characters, no need to update tables
1688 d->text_.push_back(c);
1689 setFont(d->text_.size() - 1, font);
1690 d->requestSpellCheck(d->text_.size() - 1);
1694 void Paragraph::appendString(docstring const & s, Font const & font,
1695 Change const & change)
1697 pos_type end = s.size();
1698 size_t oldsize = d->text_.size();
1699 size_t newsize = oldsize + end;
1700 size_t capacity = d->text_.capacity();
1701 if (newsize >= capacity)
1702 d->text_.reserve(max(capacity + 100, newsize));
1704 // when appending characters, no need to update tables
1707 // FIXME: Optimize this!
1708 for (size_t i = oldsize; i != newsize; ++i) {
1710 d->changes_.insert(change, i);
1711 d->requestSpellCheck(i);
1713 d->fontlist_.set(oldsize, font);
1714 d->fontlist_.set(newsize - 1, font);
1718 void Paragraph::insertChar(pos_type pos, char_type c,
1721 d->insertChar(pos, c, Change(trackChanges ?
1722 Change::INSERTED : Change::UNCHANGED));
1726 void Paragraph::insertChar(pos_type pos, char_type c,
1727 Font const & font, bool trackChanges)
1729 d->insertChar(pos, c, Change(trackChanges ?
1730 Change::INSERTED : Change::UNCHANGED));
1735 void Paragraph::insertChar(pos_type pos, char_type c,
1736 Font const & font, Change const & change)
1738 d->insertChar(pos, c, change);
1743 void Paragraph::resetFonts(Font const & font)
1745 d->fontlist_.clear();
1746 d->fontlist_.set(0, font);
1747 d->fontlist_.set(d->text_.size() - 1, font);
1750 // Gets uninstantiated font setting at position.
1751 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1755 LYXERR0("pos: " << pos << " size: " << size());
1759 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1760 if (cit != d->fontlist_.end())
1763 if (pos == size() && !empty())
1764 return getFontSettings(bparams, pos - 1);
1766 // Optimisation: avoid a full font instantiation if there is no
1767 // language change from previous call.
1768 static Font previous_font;
1769 static Language const * previous_lang = nullptr;
1770 Language const * lang = getParLanguage(bparams);
1771 if (lang != previous_lang) {
1772 previous_lang = lang;
1773 previous_font = Font(inherit_font, lang);
1775 return previous_font;
1779 FontSpan Paragraph::fontSpan(pos_type pos) const
1781 LBUFERR(pos <= size());
1784 return FontSpan(pos, pos);
1787 FontList::const_iterator cit = d->fontlist_.begin();
1788 FontList::const_iterator end = d->fontlist_.end();
1789 for (; cit != end; ++cit) {
1790 if (cit->pos() >= pos) {
1791 if (pos >= beginOfBody())
1792 return FontSpan(max(start, beginOfBody()),
1795 return FontSpan(start,
1796 min(beginOfBody() - 1,
1799 start = cit->pos() + 1;
1802 // This should not happen, but if so, we take no chances.
1803 LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1804 LASSERT(false, return FontSpan(pos, pos));
1808 // Gets uninstantiated font setting at position 0
1809 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1811 if (!empty() && !d->fontlist_.empty())
1812 return d->fontlist_.begin()->font();
1814 // Optimisation: avoid a full font instantiation if there is no
1815 // language change from previous call.
1816 static Font previous_font;
1817 static Language const * previous_lang = nullptr;
1818 if (bparams.language != previous_lang) {
1819 previous_lang = bparams.language;
1820 previous_font = Font(inherit_font, bparams.language);
1823 return previous_font;
1827 // Gets the fully instantiated font at a given position in a paragraph
1828 // This is basically the same function as Text::GetFont() in text2.cpp.
1829 // The difference is that this one is used for generating the LaTeX file,
1830 // and thus cosmetic "improvements" are disallowed: This has to deliver
1831 // the true picture of the buffer. (Asger)
1832 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1833 Font const & outerfont) const
1837 Font font = getFontSettings(bparams, pos);
1839 pos_type const body_pos = beginOfBody();
1840 FontInfo & fi = font.fontInfo();
1842 fi.realize(d->layout_->labelfont);
1844 fi.realize(d->layout_->font);
1846 fi.realize(outerfont.fontInfo());
1847 fi.realize(bparams.getFont().fontInfo());
1853 Font const Paragraph::getLabelFont
1854 (BufferParams const & bparams, Font const & outerfont) const
1856 FontInfo tmpfont = d->layout_->labelfont;
1857 tmpfont.realize(outerfont.fontInfo());
1858 tmpfont.realize(bparams.getFont().fontInfo());
1859 return Font(tmpfont, getParLanguage(bparams));
1863 Font const Paragraph::getLayoutFont
1864 (BufferParams const & bparams, Font const & outerfont) const
1866 FontInfo tmpfont = d->layout_->font;
1867 tmpfont.realize(outerfont.fontInfo());
1868 tmpfont.realize(bparams.getFont().fontInfo());
1869 return Font(tmpfont, getParLanguage(bparams));
1873 char_type Paragraph::getUChar(BufferParams const & bparams,
1874 OutputParams const & rp,
1877 char_type c = d->text_[pos];
1879 // Return unchanged character in LTR languages
1880 // or if we use poylglossia/bidi (XeTeX).
1881 if (rp.useBidiPackage()
1882 || !getFontSettings(bparams, pos).isRightToLeft())
1885 // Without polyglossia/bidi, we need to account for some special cases.
1886 // FIXME This needs to be audited!
1888 // * The input is as expected for all delimiters
1889 // => checked for Hebrew!
1890 // * The output matches the display in the LyX workarea
1891 // => checked for Hebrew!
1892 // * The special cases below are really necessary
1893 // => checked for Hebrew!
1894 // * In arabic_arabi, brackets are transformed to Arabic
1895 // Ornate Parentheses. Is this is really wanted?
1897 string const & lang = getFontSettings(bparams, pos).language()->lang();
1900 // 1. In the following languages, parentheses need to be reversed.
1901 // Also with polyglodia/luabidi
1902 bool const reverseparens = (lang == "hebrew" || rp.use_polyglossia);
1904 // 2. In the following languages, brackets don't need to be reversed.
1905 bool const reversebrackets = lang != "arabic_arabtex"
1906 && lang != "arabic_arabi"
1909 // Now swap delimiters if needed.
1920 if (reversebrackets)
1924 if (reversebrackets)
1945 void Paragraph::setFont(pos_type pos, Font const & font)
1947 LASSERT(pos <= size(), return);
1949 // First, reduce font against layout/label font
1950 // Update: The setCharFont() routine in text2.cpp already
1951 // reduces font, so we don't need to do that here. (Asger)
1953 d->fontlist_.set(pos, font);
1957 void Paragraph::makeSameLayout(Paragraph const & par)
1959 d->layout_ = par.d->layout_;
1960 d->params_ = par.d->params_;
1964 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1966 if (isFreeSpacing())
1972 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1973 if (eraseChar(pos, trackChanges))
1979 return count > 0 || pos > 0;
1983 bool Paragraph::hasSameLayout(Paragraph const & par) const
1985 return par.d->layout_ == d->layout_
1986 && d->params_.sameLayout(par.d->params_);
1990 depth_type Paragraph::getDepth() const
1992 return d->params_.depth();
1996 depth_type Paragraph::getMaxDepthAfter() const
1998 if (d->layout_->isEnvironment())
1999 return d->params_.depth() + 1;
2001 return d->params_.depth();
2005 LyXAlignment Paragraph::getAlign(BufferParams const & bparams) const
2007 if (d->params_.align() == LYX_ALIGN_LAYOUT)
2008 return getDefaultAlign(bparams);
2010 return d->params_.align();
2014 LyXAlignment Paragraph::getDefaultAlign(BufferParams const & bparams) const
2016 LyXAlignment res = layout().align;
2017 if (isRTL(bparams)) {
2019 if (res == LYX_ALIGN_LEFT)
2020 res = LYX_ALIGN_RIGHT;
2021 else if (res == LYX_ALIGN_RIGHT)
2022 res = LYX_ALIGN_LEFT;
2028 docstring const & Paragraph::labelString() const
2030 return d->params_.labelString();
2034 // the next two functions are for the manual labels
2035 docstring const Paragraph::getLabelWidthString() const
2037 if (d->layout_->margintype == MARGIN_MANUAL
2038 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2039 return d->params_.labelWidthString();
2041 return _("Senseless with this layout!");
2045 void Paragraph::setLabelWidthString(docstring const & s)
2047 d->params_.labelWidthString(s);
2051 docstring Paragraph::expandLabel(Layout const & layout,
2052 BufferParams const & bparams) const
2054 return expandParagraphLabel(layout, bparams, true);
2058 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2059 BufferParams const & bparams, bool process_appendix) const
2061 DocumentClass const & tclass = bparams.documentClass();
2062 string const & lang = getParLanguage(bparams)->code();
2063 bool const in_appendix = process_appendix && d->params_.appendix();
2064 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2066 if (fmt.empty() && !layout.counter.empty())
2067 return tclass.counters().theCounter(layout.counter, lang);
2069 // handle 'inherited level parts' in 'fmt',
2070 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2071 size_t const i = fmt.find('@', 0);
2072 if (i != docstring::npos) {
2073 size_t const j = fmt.find('@', i + 1);
2074 if (j != docstring::npos) {
2075 docstring parent(fmt, i + 1, j - i - 1);
2076 docstring label = from_ascii("??");
2077 if (tclass.hasLayout(parent))
2078 label = expandParagraphLabel(tclass[parent], bparams,
2080 fmt = docstring(fmt, 0, i) + label
2081 + docstring(fmt, j + 1, docstring::npos);
2085 return tclass.counters().counterLabel(fmt, lang);
2089 void Paragraph::applyLayout(Layout const & new_layout)
2091 d->layout_ = &new_layout;
2092 LyXAlignment const oldAlign = d->params_.align();
2094 if (!(oldAlign & d->layout_->alignpossible)) {
2095 frontend::Alert::warning(_("Alignment not permitted"),
2096 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2097 d->params_.align(LYX_ALIGN_LAYOUT);
2102 pos_type Paragraph::beginOfBody() const
2104 return d->begin_of_body_;
2108 void Paragraph::setBeginOfBody()
2110 if (d->layout_->labeltype != LABEL_MANUAL) {
2111 d->begin_of_body_ = 0;
2115 // Unroll the first two cycles of the loop
2116 // and remember the previous character to
2117 // remove unnecessary getChar() calls
2119 pos_type end = size();
2120 bool prev_char_deleted = false;
2121 if (i < end && (!(isNewline(i) || isEnvSeparator(i)) || isDeleted(i))) {
2124 char_type previous_char = d->text_[i];
2125 if (!(isNewline(i) || isEnvSeparator(i))) {
2127 while (i < end && (previous_char != ' ' || prev_char_deleted)) {
2128 char_type temp = d->text_[i];
2129 prev_char_deleted = isDeleted(i);
2130 if (!isDeleted(i) && (isNewline(i) || isEnvSeparator(i)))
2133 previous_char = temp;
2139 d->begin_of_body_ = i;
2143 bool Paragraph::allowParagraphCustomization() const
2145 return inInset().allowParagraphCustomization();
2149 bool Paragraph::usePlainLayout() const
2151 return inInset().usePlainLayout();
2155 bool Paragraph::isPassThru() const
2157 return inInset().isPassThru() || d->layout_->pass_thru;
2162 // paragraphs inside floats need different alignment tags to avoid
2165 bool noTrivlistCentering(InsetCode code)
2167 return code == FLOAT_CODE
2168 || code == WRAP_CODE
2169 || code == CELL_CODE;
2173 string correction(string const & orig)
2175 if (orig == "flushleft")
2176 return "raggedright";
2177 if (orig == "flushright")
2178 return "raggedleft";
2179 if (orig == "center")
2185 bool corrected_env(otexstream & os, string const & suffix, string const & env,
2186 InsetCode code, bool const lastpar, int & col)
2188 string macro = suffix + "{";
2189 if (noTrivlistCentering(code)) {
2191 // the last paragraph in non-trivlist-aligned
2192 // context is special (to avoid unwanted whitespace)
2193 if (suffix == "\\begin") {
2194 macro = "\\" + correction(env) + "{}";
2195 os << from_ascii(macro);
2196 col += macro.size();
2201 macro += correction(env);
2205 if (suffix == "\\par\\end") {
2209 os << from_ascii(macro);
2210 col += macro.size();
2211 if (suffix == "\\begin") {
2221 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2222 otexstream & os, OutputParams const & runparams) const
2227 (bparams.paragraph_separation == BufferParams::ParagraphIndentSeparation) ?
2228 (layout_->toggle_indent != ITOGGLE_NEVER) :
2229 (layout_->toggle_indent == ITOGGLE_ALWAYS);
2231 if (canindent && params_.noindent() && !layout_->pass_thru) {
2232 os << "\\noindent ";
2236 LyXAlignment const curAlign = params_.align();
2238 if (curAlign == layout_->align)
2242 case LYX_ALIGN_NONE:
2243 case LYX_ALIGN_BLOCK:
2244 case LYX_ALIGN_LAYOUT:
2245 case LYX_ALIGN_SPECIAL:
2246 case LYX_ALIGN_DECIMAL:
2248 case LYX_ALIGN_LEFT:
2249 case LYX_ALIGN_RIGHT:
2250 case LYX_ALIGN_CENTER:
2251 if (runparams.moving_arg) {
2258 string const begin_tag = "\\begin";
2259 InsetCode code = ownerCode();
2260 bool const lastpar = runparams.isLastPar;
2261 // RTL in classic (PDF)LaTeX (without the Bidi package)
2262 // Luabibdi (used by LuaTeX) behaves like classic
2263 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2264 && !runparams.useBidiPackage();
2267 case LYX_ALIGN_NONE:
2268 case LYX_ALIGN_BLOCK:
2269 case LYX_ALIGN_LAYOUT:
2270 case LYX_ALIGN_SPECIAL:
2271 case LYX_ALIGN_DECIMAL:
2273 case LYX_ALIGN_LEFT: {
2275 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2276 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2278 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2280 } case LYX_ALIGN_RIGHT: {
2282 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2283 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2285 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2287 } case LYX_ALIGN_CENTER: {
2288 corrected_env(os, begin_tag, "center", code, lastpar, column);
2297 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2298 otexstream & os, OutputParams const & runparams) const
2300 LyXAlignment const curAlign = params_.align();
2302 if (curAlign == layout_->align)
2306 case LYX_ALIGN_NONE:
2307 case LYX_ALIGN_BLOCK:
2308 case LYX_ALIGN_LAYOUT:
2309 case LYX_ALIGN_SPECIAL:
2310 case LYX_ALIGN_DECIMAL:
2312 case LYX_ALIGN_LEFT:
2313 case LYX_ALIGN_RIGHT:
2314 case LYX_ALIGN_CENTER:
2315 if (runparams.moving_arg)
2320 bool output = false;
2322 string const end_tag = "\\par\\end";
2323 InsetCode code = ownerCode();
2324 bool const lastpar = runparams.isLastPar;
2325 // RTL in classic (PDF)LaTeX (without the Bidi package)
2326 // Luabibdi (used by LuaTeX) behaves like classic
2327 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2328 && !runparams.useBidiPackage();
2331 case LYX_ALIGN_NONE:
2332 case LYX_ALIGN_BLOCK:
2333 case LYX_ALIGN_LAYOUT:
2334 case LYX_ALIGN_SPECIAL:
2335 case LYX_ALIGN_DECIMAL:
2337 case LYX_ALIGN_LEFT: {
2339 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2340 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2342 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2344 } case LYX_ALIGN_RIGHT: {
2346 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2347 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2349 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2351 } case LYX_ALIGN_CENTER: {
2352 corrected_env(os, end_tag, "center", code, lastpar, col);
2357 return output || lastpar;
2361 // This one spits out the text of the paragraph
2362 void Paragraph::latex(BufferParams const & bparams,
2363 Font const & outerfont,
2365 OutputParams const & runparams,
2366 int start_pos, int end_pos, bool force) const
2368 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2370 // FIXME This check should not be needed. Perhaps issue an
2371 // error if it triggers.
2372 Layout const & style = inInset().forcePlainLayout() ?
2373 bparams.documentClass().plainLayout() : *d->layout_;
2375 if (!force && style.inpreamble)
2378 bool const allowcust = allowParagraphCustomization();
2380 // Current base font for all inherited font changes, without any
2381 // change caused by an individual character, except for the language:
2382 // It is set to the language of the first character.
2383 // As long as we are in the label, this font is the base font of the
2384 // label. Before the first body character it is set to the base font
2388 // If there is an open font-encoding changing command (script wrapper),
2389 // alien_script is set to its name
2390 string alien_script;
2393 // Maybe we have to create a optional argument.
2394 pos_type body_pos = beginOfBody();
2395 unsigned int column = 0;
2398 // the optional argument is kept in curly brackets in
2399 // case it contains a ']'
2400 // This is not strictly needed, but if this is changed it
2401 // would be a file format change, and tex2lyx would need
2402 // to be adjusted, since it unconditionally removes the
2403 // braces when it parses \item.
2406 basefont = getLabelFont(bparams, outerfont);
2408 basefont = getLayoutFont(bparams, outerfont);
2411 // Which font is currently active?
2412 Font running_font(basefont);
2413 // Do we have an open font change?
2414 bool open_font = false;
2416 Change runningChange = Change(Change::UNCHANGED);
2418 Encoding const * const prev_encoding = runparams.encoding;
2420 os.texrow().start(id(), 0);
2422 // if the paragraph is empty, the loop will not be entered at all
2424 // For InTitle commands, we have already opened a group
2425 // in output_latex::TeXOnePar.
2426 if (style.isCommand() && !style.intitle) {
2430 if (!style.leftdelim().empty()) {
2431 os << style.leftdelim();
2432 column += style.leftdelim().size();
2435 column += d->startTeXParParams(bparams, os, runparams);
2438 // Whether a \par can be issued for insets typeset inline with text.
2439 // Yes if greater than 0. This has to be static.
2440 THREAD_LOCAL_STATIC int parInline = 0;
2442 for (pos_type i = 0; i < size(); ++i) {
2443 // First char in paragraph or after label?
2444 if (i == body_pos) {
2447 bool needPar = false;
2448 column += running_font.latexWriteEndChanges(
2449 os, bparams, runparams,
2450 basefont, basefont, needPar);
2453 basefont = getLayoutFont(bparams, outerfont);
2454 running_font = basefont;
2456 column += Changes::latexMarkChange(os, bparams,
2457 runningChange, Change(Change::UNCHANGED),
2459 runningChange = Change(Change::UNCHANGED);
2464 // For InTitle commands, we have already opened a group
2465 // in output_latex::TeXOnePar.
2466 if (style.isCommand() && !style.intitle) {
2471 if (!style.leftdelim().empty()) {
2472 os << style.leftdelim();
2473 column += style.leftdelim().size();
2477 column += d->startTeXParParams(bparams, os,
2481 runparams.wasDisplayMath = runparams.inDisplayMath;
2482 runparams.inDisplayMath = false;
2483 bool deleted_display_math = false;
2484 Change const & change = runparams.inDeletedInset
2485 ? runparams.changeOfDeletedInset : lookupChange(i);
2487 char_type const c = d->text_[i];
2489 // Check whether a display math inset follows
2491 && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2493 runparams.ctObject = getInset(i)->CtObject(runparams);
2495 InsetMath const * im = getInset(i)->asInsetMath();
2496 if (im && im->asHullInset()
2497 && im->asHullInset()->outerDisplay()) {
2498 runparams.inDisplayMath = true;
2499 // runparams.inDeletedInset will be set by
2500 // latexInset later, but we need this info
2501 // before it is called. On the other hand, we
2502 // cannot set it here because it is a counter.
2503 deleted_display_math = isDeleted(i);
2505 if (bparams.output_changes && deleted_display_math
2506 && runningChange == change
2507 && change.type == Change::DELETED
2508 && !os.afterParbreak()) {
2509 // A display math in the same paragraph follows.
2510 // We have to close and then reopen \lyxdeleted,
2511 // otherwise the math will be shifted up.
2512 OutputParams rp = runparams;
2514 bool needPar = false;
2515 column += running_font.latexWriteEndChanges(
2516 os, bparams, rp, basefont,
2520 basefont = (body_pos > i) ? getLabelFont(bparams, outerfont)
2521 : getLayoutFont(bparams, outerfont);
2522 running_font = basefont;
2523 column += Changes::latexMarkChange(os, bparams,
2524 Change(Change::INSERTED), change, rp);
2528 if (bparams.output_changes && runningChange != change) {
2529 if (!alien_script.empty()) {
2532 alien_script.clear();
2535 bool needPar = false;
2536 column += running_font.latexWriteEndChanges(
2537 os, bparams, runparams,
2538 basefont, basefont, needPar);
2541 basefont = (body_pos > i) ? getLabelFont(bparams, outerfont)
2542 : getLayoutFont(bparams, outerfont);
2543 running_font = basefont;
2544 column += Changes::latexMarkChange(os, bparams, runningChange,
2546 runningChange = change;
2549 // do not output text which is marked deleted
2550 // if change tracking output is disabled
2551 if (!bparams.output_changes && change.deleted()) {
2557 // Fully instantiated font
2558 Font const current_font = getFont(bparams, i, outerfont);
2560 Font const last_font = running_font;
2561 bool const in_ct_deletion = (bparams.output_changes
2562 && runningChange == change
2563 && change.type == Change::DELETED
2564 && !os.afterParbreak());
2566 // Do we need to close the previous font?
2568 (current_font != running_font ||
2569 current_font.language() != running_font.language()))
2571 // ensure there is no open script-wrapper
2572 if (!alien_script.empty()) {
2575 alien_script.clear();
2577 bool needPar = false;
2578 if (in_ct_deletion) {
2579 // We have to close and then reopen \lyxdeleted,
2580 // as strikeout needs to be on lowest level.
2584 column += running_font.latexWriteEndChanges(
2585 os, bparams, runparams, basefont,
2586 (i == body_pos-1) ? basefont : current_font,
2588 if (in_ct_deletion) {
2589 // We have to close and then reopen \lyxdeleted,
2590 // as strikeout needs to be on lowest level.
2591 OutputParams rp = runparams;
2592 column += Changes::latexMarkChange(os, bparams,
2593 Change(Change::UNCHANGED), Change(Change::DELETED), rp);
2595 running_font = basefont;
2599 // if necessary, close language environment before opening CJK
2600 string const running_lang = running_font.language()->babel();
2601 string const lang_end_command = lyxrc.language_command_end;
2602 if (!lang_end_command.empty() && !bparams.useNonTeXFonts
2603 && !running_lang.empty()
2604 && running_lang == openLanguageName()
2605 && current_font.language()->encoding()->package() == Encoding::CJK) {
2606 string end_tag = subst(lang_end_command, "$$lang", running_lang);
2607 os << from_ascii(end_tag);
2608 column += end_tag.length();
2612 // Switch file encoding if necessary (and allowed)
2613 if (!runparams.pass_thru && !style.pass_thru &&
2614 runparams.encoding->package() != Encoding::none &&
2615 current_font.language()->encoding()->package() != Encoding::none) {
2616 pair<bool, int> const enc_switch =
2617 switchEncoding(os.os(), bparams, runparams,
2618 *(current_font.language()->encoding()));
2619 if (enc_switch.first) {
2620 column += enc_switch.second;
2621 runparams.encoding = current_font.language()->encoding();
2625 // A display math inset inside an ulem command will be output
2626 // as a box of width \linewidth, so we have to either disable
2627 // indentation if the inset starts a paragraph, or start a new
2628 // line to accommodate such box. This has to be done before
2629 // writing any font changing commands.
2630 if (runparams.inDisplayMath && !deleted_display_math
2631 && runparams.inulemcmd) {
2632 if (os.afterParbreak())
2638 // Do we need to change font?
2639 if ((current_font != running_font ||
2640 current_font.language() != running_font.language())
2641 && i != body_pos - 1)
2643 if (in_ct_deletion) {
2644 // We have to close and then reopen \lyxdeleted,
2645 // as strikeout needs to be on lowest level.
2646 bool needPar = false;
2647 OutputParams rp = runparams;
2648 column += running_font.latexWriteEndChanges(
2649 os, bparams, rp, basefont,
2654 odocstringstream ods;
2655 column += current_font.latexWriteStartChanges(ods, bparams,
2656 runparams, basefont,
2658 // Check again for display math in ulem commands as a
2659 // font change may also occur just before a math inset.
2660 if (runparams.inDisplayMath && !deleted_display_math
2661 && runparams.inulemcmd) {
2662 if (os.afterParbreak())
2667 running_font = current_font;
2669 docstring fontchange = ods.str();
2670 // check whether the fontchange ends with a \\textcolor
2671 // modifier and the text starts with a space (bug 4473)
2672 docstring const last_modifier = rsplit(fontchange, '\\');
2673 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2674 os << fontchange << from_ascii("{}");
2675 // check if the fontchange ends with a trailing blank
2676 // (like "\small " (see bug 3382)
2677 else if (suffixIs(fontchange, ' ') && c == ' ')
2678 os << fontchange.substr(0, fontchange.size() - 1)
2679 << from_ascii("{}");
2682 if (in_ct_deletion) {
2683 // We have to close and then reopen \lyxdeleted,
2684 // as strikeout needs to be on lowest level.
2685 OutputParams rp = runparams;
2686 column += Changes::latexMarkChange(os, bparams,
2687 Change(Change::UNCHANGED), change, rp);
2691 // FIXME: think about end_pos implementation...
2692 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2693 // FIXME: integrate this case in latexSpecialChar
2694 // Do not print the separation of the optional argument
2695 // if style.pass_thru is false. This works because
2696 // latexSpecialChar ignores spaces if
2697 // style.pass_thru is false.
2698 if (i != body_pos - 1) {
2699 if (d->simpleTeXBlanks(bparams, runparams, os,
2700 i, column, current_font, style)) {
2701 // A surrogate pair was output. We
2702 // must not call latexSpecialChar
2703 // in this iteration, since it would output
2704 // the combining character again.
2711 OutputParams rp = runparams;
2712 rp.free_spacing = style.free_spacing;
2713 rp.local_font = ¤t_font;
2714 rp.intitle = style.intitle;
2716 // Two major modes: LaTeX or plain
2717 // Handle here those cases common to both modes
2718 // and then split to handle the two modes separately.
2719 if (c == META_INSET) {
2720 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2721 // Greyedout notes and, in general, all insets
2722 // with InsetLayout::isDisplay() == false,
2723 // are typeset inline with the text. So, we
2724 // can add a \par to the last paragraph of
2725 // such insets only if nothing else follows.
2726 bool incremented = false;
2727 Inset const * inset = getInset(i);
2728 InsetText const * textinset = inset
2729 ? inset->asInsetText()
2731 if (i + 1 == size() && textinset
2732 && !inset->getLayout().isDisplay()) {
2733 ParagraphList const & pars =
2734 textinset->text().paragraphs();
2735 pit_type const pit = pars.size() - 1;
2736 Font const lastfont =
2737 pit < 0 || pars[pit].empty()
2738 ? pars[pit].getLayoutFont(
2741 : pars[pit].getFont(bparams,
2742 pars[pit].size() - 1,
2744 if (lastfont.fontInfo().size() !=
2745 basefont.fontInfo().size()) {
2750 d->latexInset(bparams, os, rp, running_font,
2751 basefont, outerfont, open_font,
2752 runningChange, style, i, column);
2756 if (runparams.ctObject == OutputParams::CT_DISPLAYOBJECT
2757 || runparams.ctObject == OutputParams::CT_UDISPLAYOBJECT) {
2758 // Close \lyx*deleted and force its
2759 // reopening (if needed)
2762 runningChange = Change(Change::UNCHANGED);
2763 runparams.ctObject = OutputParams::CT_NORMAL;
2766 } else if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2767 if (!bparams.useNonTeXFonts)
2768 script = Encodings::isKnownScriptChar(c);
2769 if (script != alien_script) {
2770 if (!alien_script.empty()) {
2772 alien_script.clear();
2774 string fontenc = running_font.language()->fontenc(bparams);
2776 && !Encodings::fontencSupportsScript(fontenc, script)) {
2777 column += script.length() + 2;
2778 os << "\\" << script << "{";
2779 alien_script = script;
2783 d->latexSpecialChar(os, bparams, rp, running_font,
2784 alien_script, style, i, end_pos, column);
2785 } catch (EncodingException & e) {
2786 if (runparams.dryrun) {
2787 os << "<" << _("LyX Warning: ")
2788 << _("uncodable character") << " '";
2792 // add location information and throw again.
2800 // Set the encoding to that returned from latexSpecialChar (see
2801 // comment for encoding member in OutputParams.h)
2802 runparams.encoding = rp.encoding;
2804 // Also carry on the info on a closed ulem command for insets
2805 // such as Note that do not produce any output, so that no
2806 // command is ever executed but its opening was recorded.
2807 runparams.inulemcmd = rp.inulemcmd;
2809 // These need to be passed upstream as well
2810 runparams.need_maketitle = rp.need_maketitle;
2811 runparams.have_maketitle = rp.have_maketitle;
2813 // And finally, pass the post_macros upstream
2814 runparams.post_macro = rp.post_macro;
2817 // Close wrapper for alien script
2818 if (!alien_script.empty()) {
2820 alien_script.clear();
2823 // If we have an open font definition, we have to close it
2825 // Make sure that \\par is done with the font of the last
2826 // character if this has another size as the default.
2827 // This is necessary because LaTeX (and LyX on the screen)
2828 // calculates the space between the baselines according
2829 // to this font. (Matthias)
2831 // We must not change the font for the last paragraph
2832 // of non-multipar insets, tabular cells or commands,
2833 // since this produces unwanted whitespace.
2835 Font const font = empty()
2836 ? getLayoutFont(bparams, outerfont)
2837 : getFont(bparams, size() - 1, outerfont);
2839 InsetText const * textinset = inInset().asInsetText();
2841 bool const maintext = textinset
2842 ? textinset->text().isMainText()
2845 size_t const numpars = textinset
2846 ? textinset->text().paragraphs().size()
2849 bool needPar = false;
2851 if (style.resfont.size() != font.fontInfo().size()
2852 && (!runparams.isLastPar || maintext
2853 || (numpars > 1 && d->ownerCode() != CELL_CODE
2854 && (inInset().getLayout().isDisplay()
2856 && !style.isCommand()) {
2859 #ifdef FIXED_LANGUAGE_END_DETECTION
2861 running_font.latexWriteEndChanges(os, bparams,
2862 runparams, basefont,
2863 next_->getFont(bparams, 0, outerfont),
2866 running_font.latexWriteEndChanges(os, bparams,
2867 runparams, basefont, basefont, needPar);
2870 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2871 //FIXME: there as we start another \selectlanguage with the next paragraph if
2872 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2873 running_font.latexWriteEndChanges(os, bparams, runparams,
2874 basefont, basefont, needPar);
2877 // The \par could not be inserted at the same nesting
2878 // level of the font size change, so do it now.
2879 os << "{\\" << font.latexSize() << "\\par}";
2883 column += Changes::latexMarkChange(os, bparams, runningChange,
2884 Change(Change::UNCHANGED), runparams);
2886 // Needed if there is an optional argument but no contents.
2887 if (body_pos > 0 && body_pos == size()) {
2891 if (!style.rightdelim().empty()) {
2892 os << style.rightdelim();
2893 column += style.rightdelim().size();
2896 if (allowcust && d->endTeXParParams(bparams, os, runparams)
2897 && runparams.encoding != prev_encoding) {
2898 runparams.encoding = prev_encoding;
2899 os << setEncoding(prev_encoding->iconvName());
2902 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2906 bool Paragraph::emptyTag() const
2908 for (pos_type i = 0; i < size(); ++i) {
2909 if (Inset const * inset = getInset(i)) {
2910 InsetCode lyx_code = inset->lyxCode();
2911 // FIXME testing like that is wrong. What is
2913 if (lyx_code != TOC_CODE &&
2914 lyx_code != INCLUDE_CODE &&
2915 lyx_code != GRAPHICS_CODE &&
2916 lyx_code != ERT_CODE &&
2917 lyx_code != LISTINGS_CODE &&
2918 lyx_code != FLOAT_CODE &&
2919 lyx_code != TABULAR_CODE) {
2923 char_type c = d->text_[i];
2924 if (c != ' ' && c != '\t')
2932 string Paragraph::getID(Buffer const &, OutputParams const &)
2935 for (pos_type i = 0; i < size(); ++i) {
2936 if (Inset const * inset = getInset(i)) {
2937 InsetCode lyx_code = inset->lyxCode();
2938 if (lyx_code == LABEL_CODE) {
2939 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2940 docstring const & id = il->getParam("name");
2941 return "id='" + to_utf8(xml::cleanID(id)) + "'";
2949 pos_type Paragraph::firstWordDocBook(XMLStream & xs, OutputParams const & runparams) const
2952 for (i = 0; i < size(); ++i) {
2953 if (Inset const * inset = getInset(i)) {
2954 inset->docbook(xs, runparams);
2956 char_type c = d->text_[i];
2966 pos_type Paragraph::firstWordLyXHTML(XMLStream & xs, OutputParams const & runparams)
2970 for (i = 0; i < size(); ++i) {
2971 if (Inset const * inset = getInset(i)) {
2972 inset->xhtml(xs, runparams);
2974 char_type c = d->text_[i];
2984 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2987 pos_type size = text_.size();
2988 for (pos_type i = initial; i < size; ++i) {
2989 Font font = owner_->getFont(buf.params(), i, outerfont);
2990 if (text_[i] == META_INSET)
2992 if (i != initial && font != font_old)
3003 void doFontSwitchDocBook(vector<xml::FontTag> & tagsToOpen,
3004 vector<xml::EndFontTag> & tagsToClose,
3005 bool & flag, FontState curstate, xml::FontTypes type)
3007 if (curstate == FONT_ON) {
3008 tagsToOpen.push_back(docbookStartFontTag(type));
3011 tagsToClose.push_back(docbookEndFontTag(type));
3016 class OptionalFontType {
3021 OptionalFontType(): has_value(false), ft(xml::FT_EMPH) {} // A possible value at random for ft.
3022 OptionalFontType(xml::FontTypes ft): has_value(true), ft(ft) {}
3025 OptionalFontType fontShapeToXml(FontShape fs)
3029 return {xml::FT_ITALIC};
3031 return {xml::FT_SLANTED};
3032 case SMALLCAPS_SHAPE:
3033 return {xml::FT_SMALLCAPS};
3038 // the other tags are for internal use
3044 OptionalFontType fontFamilyToXml(FontFamily fm)
3048 return {xml::FT_ROMAN};
3051 return {xml::FT_SANS};
3053 case TYPEWRITER_FAMILY:
3054 return {xml::FT_TYPE};
3056 case INHERIT_FAMILY:
3059 // the other tags are for internal use
3065 OptionalFontType fontSizeToXml(FontSize fs)
3069 return {xml::FT_SIZE_TINY};
3071 return {xml::FT_SIZE_SCRIPT};
3073 return {xml::FT_SIZE_FOOTNOTE};
3075 return {xml::FT_SIZE_SMALL};
3077 return {xml::FT_SIZE_LARGE};
3079 return {xml::FT_SIZE_LARGER};
3081 return {xml::FT_SIZE_LARGEST};
3083 return {xml::FT_SIZE_HUGE};
3085 return {xml::FT_SIZE_HUGER};
3087 return {xml::FT_SIZE_INCREASE};
3089 return {xml::FT_SIZE_DECREASE};
3094 // the other tags are for internal use
3101 }// anonymous namespace
3104 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
3106 OutputParams const & runparams,
3107 Font const & outerfont,
3108 bool start_paragraph, bool close_paragraph,
3109 pos_type initial) const
3111 // track whether we have opened these tags
3112 bool emph_flag = false;
3113 bool bold_flag = false;
3114 bool noun_flag = false;
3115 bool ubar_flag = false;
3116 bool dbar_flag = false;
3117 bool sout_flag = false;
3118 bool wave_flag = false;
3120 bool shap_flag = false;
3122 bool faml_flag = false;
3124 bool size_flag = false;
3126 Layout const & style = *d->layout_;
3128 if (start_paragraph)
3129 xs.startDivision(allowEmpty());
3132 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3134 FontShape curr_fs = INHERIT_SHAPE;
3135 FontFamily curr_fam = INHERIT_FAMILY;
3136 FontSize curr_size = INHERIT_SIZE;
3138 string const default_family =
3139 buf.masterBuffer()->params().fonts_default_family;
3141 vector<xml::FontTag> tagsToOpen;
3142 vector<xml::EndFontTag> tagsToClose;
3144 // parsing main loop
3145 for (pos_type i = initial; i < size(); ++i) {
3146 // let's not show deleted material in the output
3150 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3153 FontState curstate = font.fontInfo().emph();
3154 if (font_old.emph() != curstate)
3155 doFontSwitchDocBook(tagsToOpen, tagsToClose, emph_flag, curstate, xml::FT_EMPH);
3158 curstate = font.fontInfo().noun();
3159 if (font_old.noun() != curstate)
3160 doFontSwitchDocBook(tagsToOpen, tagsToClose, noun_flag, curstate, xml::FT_NOUN);
3163 curstate = font.fontInfo().underbar();
3164 if (font_old.underbar() != curstate)
3165 doFontSwitchDocBook(tagsToOpen, tagsToClose, ubar_flag, curstate, xml::FT_UBAR);
3168 curstate = font.fontInfo().strikeout();
3169 if (font_old.strikeout() != curstate)
3170 doFontSwitchDocBook(tagsToOpen, tagsToClose, sout_flag, curstate, xml::FT_SOUT);
3173 curstate = font.fontInfo().uuline();
3174 if (font_old.uuline() != curstate)
3175 doFontSwitchDocBook(tagsToOpen, tagsToClose, dbar_flag, curstate, xml::FT_DBAR);
3178 curstate = font.fontInfo().uwave();
3179 if (font_old.uwave() != curstate)
3180 doFontSwitchDocBook(tagsToOpen, tagsToClose, wave_flag, curstate, xml::FT_WAVE);
3183 // a little hackish, but allows us to reuse what we have.
3184 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3185 if (font_old.series() != font.fontInfo().series())
3186 doFontSwitchDocBook(tagsToOpen, tagsToClose, bold_flag, curstate, xml::FT_BOLD);
3189 curr_fs = font.fontInfo().shape();
3190 FontShape old_fs = font_old.shape();
3191 if (old_fs != curr_fs) {
3193 OptionalFontType tag = fontShapeToXml(old_fs);
3194 if (tag.has_value) {
3195 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3200 OptionalFontType tag = fontShapeToXml(curr_fs);
3201 if (tag.has_value) {
3202 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3207 curr_fam = font.fontInfo().family();
3208 FontFamily old_fam = font_old.family();
3209 if (old_fam != curr_fam) {
3211 OptionalFontType tag = fontFamilyToXml(old_fam);
3212 if (tag.has_value) {
3213 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3219 // we will treat a "default" font family as roman, since we have
3220 // no other idea what to do.
3221 if (default_family != "rmdefault" && default_family != "default") {
3222 tagsToOpen.push_back(docbookStartFontTag(xml::FT_ROMAN));
3227 if (default_family != "sfdefault") {
3228 tagsToOpen.push_back(docbookStartFontTag(xml::FT_SANS));
3232 case TYPEWRITER_FAMILY:
3233 if (default_family != "ttdefault") {
3234 tagsToOpen.push_back(docbookStartFontTag(xml::FT_TYPE));
3238 case INHERIT_FAMILY:
3241 // the other tags are for internal use
3248 curr_size = font.fontInfo().size();
3249 FontSize old_size = font_old.size();
3250 if (old_size != curr_size) {
3252 OptionalFontType tag = fontSizeToXml(old_size);
3253 if (tag.has_value) {
3254 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3259 OptionalFontType tag = fontSizeToXml(curr_size);
3260 if (tag.has_value) {
3261 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3267 // Other such tags? What about the other text ranges?
3269 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3270 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3271 for (; cit != cen; ++cit)
3274 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3275 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3276 for (; sit != sen; ++sit)
3279 tagsToClose.clear();
3282 if (Inset const * inset = getInset(i)) {
3283 if (!runparams.for_toc || inset->isInToc()) {
3284 OutputParams np = runparams;
3285 np.local_font = &font;
3286 // If the paragraph has size 1, then we are in the "special
3287 // case" where we do not output the containing paragraph info.
3288 if (!inset->getLayout().htmlisblock() && size() != 1) // TODO: htmlisblock here too!
3289 np.docbook_in_par = true;
3290 inset->docbook(xs, np);
3293 char_type c = getUChar(buf.masterBuffer()->params(), runparams, i);
3296 font_old = font.fontInfo();
3299 // FIXME, this code is just imported from XHTML
3300 // I'm worried about what happens if a branch, say, is itself
3301 // wrapped in some font stuff. I think that will not work.
3303 if (runparams.docbook_in_listing)
3305 if (close_paragraph)
3312 void doFontSwitchXHTML(vector<xml::FontTag> & tagsToOpen,
3313 vector<xml::EndFontTag> & tagsToClose,
3314 bool & flag, FontState curstate, xml::FontTypes type)
3316 if (curstate == FONT_ON) {
3317 tagsToOpen.push_back(xhtmlStartFontTag(type));
3320 tagsToClose.push_back(xhtmlEndFontTag(type));
3325 } // anonymous namespace
3328 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
3330 OutputParams const & runparams,
3331 Font const & outerfont,
3332 bool start_paragraph, bool close_paragraph,
3333 pos_type initial) const
3337 // track whether we have opened these tags
3338 bool emph_flag = false;
3339 bool bold_flag = false;
3340 bool noun_flag = false;
3341 bool ubar_flag = false;
3342 bool dbar_flag = false;
3343 bool sout_flag = false;
3344 bool xout_flag = false;
3345 bool wave_flag = false;
3347 bool shap_flag = false;
3349 bool faml_flag = false;
3351 bool size_flag = false;
3353 Layout const & style = *d->layout_;
3355 if (start_paragraph)
3356 xs.startDivision(allowEmpty());
3359 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3361 FontShape curr_fs = INHERIT_SHAPE;
3362 FontFamily curr_fam = INHERIT_FAMILY;
3363 FontSize curr_size = INHERIT_SIZE;
3365 string const default_family =
3366 buf.masterBuffer()->params().fonts_default_family;
3368 vector<xml::FontTag> tagsToOpen;
3369 vector<xml::EndFontTag> tagsToClose;
3371 // parsing main loop
3372 for (pos_type i = initial; i < size(); ++i) {
3373 // let's not show deleted material in the output
3377 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3380 FontState curstate = font.fontInfo().emph();
3381 if (font_old.emph() != curstate)
3382 doFontSwitchXHTML(tagsToOpen, tagsToClose, emph_flag, curstate, xml::FT_EMPH);
3385 curstate = font.fontInfo().noun();
3386 if (font_old.noun() != curstate)
3387 doFontSwitchXHTML(tagsToOpen, tagsToClose, noun_flag, curstate, xml::FT_NOUN);
3390 curstate = font.fontInfo().underbar();
3391 if (font_old.underbar() != curstate)
3392 doFontSwitchXHTML(tagsToOpen, tagsToClose, ubar_flag, curstate, xml::FT_UBAR);
3395 curstate = font.fontInfo().strikeout();
3396 if (font_old.strikeout() != curstate)
3397 doFontSwitchXHTML(tagsToOpen, tagsToClose, sout_flag, curstate, xml::FT_SOUT);
3400 curstate = font.fontInfo().xout();
3401 if (font_old.xout() != curstate)
3402 doFontSwitchXHTML(tagsToOpen, tagsToClose, xout_flag, curstate, xml::FT_XOUT);
3405 curstate = font.fontInfo().uuline();
3406 if (font_old.uuline() != curstate)
3407 doFontSwitchXHTML(tagsToOpen, tagsToClose, dbar_flag, curstate, xml::FT_DBAR);
3410 curstate = font.fontInfo().uwave();
3411 if (font_old.uwave() != curstate)
3412 doFontSwitchXHTML(tagsToOpen, tagsToClose, wave_flag, curstate, xml::FT_WAVE);
3415 // a little hackish, but allows us to reuse what we have.
3416 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3417 if (font_old.series() != font.fontInfo().series())
3418 doFontSwitchXHTML(tagsToOpen, tagsToClose, bold_flag, curstate, xml::FT_BOLD);
3421 curr_fs = font.fontInfo().shape();
3422 FontShape old_fs = font_old.shape();
3423 if (old_fs != curr_fs) {
3427 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ITALIC));
3430 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SLANTED));
3432 case SMALLCAPS_SHAPE:
3433 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SMALLCAPS));
3439 // the other tags are for internal use
3447 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ITALIC));
3451 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SLANTED));
3454 case SMALLCAPS_SHAPE:
3455 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SMALLCAPS));
3462 // the other tags are for internal use
3469 curr_fam = font.fontInfo().family();
3470 FontFamily old_fam = font_old.family();
3471 if (old_fam != curr_fam) {
3475 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ROMAN));
3478 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SANS));
3480 case TYPEWRITER_FAMILY:
3481 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_TYPE));
3483 case INHERIT_FAMILY:
3486 // the other tags are for internal use
3494 // we will treat a "default" font family as roman, since we have
3495 // no other idea what to do.
3496 if (default_family != "rmdefault" && default_family != "default") {
3497 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ROMAN));
3502 if (default_family != "sfdefault") {
3503 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SANS));
3507 case TYPEWRITER_FAMILY:
3508 if (default_family != "ttdefault") {
3509 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_TYPE));
3513 case INHERIT_FAMILY:
3516 // the other tags are for internal use
3523 curr_size = font.fontInfo().size();
3524 FontSize old_size = font_old.size();
3525 if (old_size != curr_size) {
3529 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_TINY));
3532 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SCRIPT));
3535 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_FOOTNOTE));
3538 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SMALL));
3541 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGE));
3544 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGER));
3547 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGEST));
3550 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGE));
3553 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGER));
3556 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_INCREASE));
3559 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_DECREASE));
3565 // the other tags are for internal use
3571 switch (curr_size) {
3573 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_TINY));
3577 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SCRIPT));
3581 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_FOOTNOTE));
3585 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SMALL));
3589 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGE));
3593 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGER));
3597 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGEST));
3601 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGE));
3605 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGER));
3609 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_INCREASE));
3613 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_DECREASE));
3620 // the other tags are for internal use
3627 // Other such tags? What about the other text ranges?
3629 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3630 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3631 for (; cit != cen; ++cit)
3634 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3635 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3636 for (; sit != sen; ++sit)
3639 tagsToClose.clear();
3642 Inset const * inset = getInset(i);
3644 if (!runparams.for_toc || inset->isInToc()) {
3645 OutputParams np = runparams;
3646 np.local_font = &font;
3647 // If the paragraph has size 1, then we are in the "special
3648 // case" where we do not output the containing paragraph info
3649 if (!inset->getLayout().htmlisblock() && size() != 1)
3650 np.html_in_par = true;
3651 retval += inset->xhtml(xs, np);
3654 char_type c = getUChar(buf.masterBuffer()->params(),
3656 if (c == ' ' && (style.free_spacing || runparams.free_spacing))
3657 xs << XMLStream::ESCAPE_NONE << " ";
3661 font_old = font.fontInfo();
3665 // I'm worried about what happens if a branch, say, is itself
3666 // wrapped in some font stuff. I think that will not work.
3668 if (close_paragraph)
3675 bool Paragraph::isHfill(pos_type pos) const
3677 Inset const * inset = getInset(pos);
3678 return inset && inset->isHfill();
3682 bool Paragraph::isNewline(pos_type pos) const
3684 // U+2028 LINE SEPARATOR
3685 // U+2029 PARAGRAPH SEPARATOR
3686 char_type const c = d->text_[pos];
3687 if (c == 0x2028 || c == 0x2029)
3689 Inset const * inset = getInset(pos);
3690 return inset && inset->lyxCode() == NEWLINE_CODE;
3694 bool Paragraph::isEnvSeparator(pos_type pos) const
3696 Inset const * inset = getInset(pos);
3697 return inset && inset->lyxCode() == SEPARATOR_CODE;
3701 bool Paragraph::isLineSeparator(pos_type pos) const
3703 char_type const c = d->text_[pos];
3704 if (isLineSeparatorChar(c))
3706 Inset const * inset = getInset(pos);
3707 return inset && inset->isLineSeparator();
3711 bool Paragraph::isWordSeparator(pos_type pos, bool const ignore_deleted) const
3715 if (ignore_deleted && isDeleted(pos))
3717 if (Inset const * inset = getInset(pos))
3718 return !inset->isLetter();
3719 // if we have a hard hyphen (no en- or emdash) or apostrophe
3720 // we pass this to the spell checker
3721 // FIXME: this method is subject to change, visit
3722 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
3723 // to get an impression how complex this is.
3724 if (isHardHyphenOrApostrophe(pos))
3726 char_type const c = d->text_[pos];
3727 // We want to pass the escape chars to the spellchecker
3728 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
3729 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
3733 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
3735 pos_type const psize = size();
3738 char_type const c = d->text_[pos];
3739 if (c != '-' && c != '\'')
3741 int nextpos = pos + 1;
3742 int prevpos = pos > 0 ? pos - 1 : 0;
3743 if ((nextpos == psize || isSpace(nextpos))
3744 && (pos == 0 || isSpace(prevpos)))
3750 bool Paragraph::needsCProtection(bool const fragile) const
3752 // first check the layout of the paragraph, but only in insets
3753 InsetText const * textinset = inInset().asInsetText();
3754 bool const maintext = textinset
3755 ? textinset->text().isMainText()
3758 if (!maintext && layout().needcprotect) {
3759 // Environments need cprotection regardless the content
3760 if (layout().latextype == LATEX_ENVIRONMENT)
3763 // Commands need cprotection if they contain specific chars
3764 int const nchars_escape = 9;
3765 static char_type const chars_escape[nchars_escape] = {
3766 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
3768 docstring const pars = asString();
3769 for (int k = 0; k < nchars_escape; k++) {
3770 if (contains(pars, chars_escape[k]))
3775 // now check whether we have insets that need cprotection
3776 pos_type size = pos_type(d->text_.size());
3777 for (pos_type i = 0; i < size; ++i) {
3780 Inset const * ins = getInset(i);
3781 if (ins->needsCProtection(maintext, fragile))
3783 if (ins->getLayout().latextype() == InsetLayout::ENVIRONMENT)
3784 // Environments need cprotection regardless the content
3786 // Now check math environments
3787 InsetMath const * im = getInset(i)->asInsetMath();
3788 if (!im || im->cell(0).empty())
3790 switch(im->cell(0)[0]->lyxCode()) {
3791 case MATH_AMSARRAY_CODE:
3792 case MATH_SUBSTACK_CODE:
3794 case MATH_XYMATRIX_CODE:
3795 // these need cprotection
3806 FontSpan const & Paragraph::getSpellRange(pos_type pos) const
3808 return d->speller_state_.getRange(pos);
3812 bool Paragraph::isChar(pos_type pos) const
3814 if (Inset const * inset = getInset(pos))
3815 return inset->isChar();
3816 char_type const c = d->text_[pos];
3817 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
3821 bool Paragraph::isSpace(pos_type pos) const
3823 if (Inset const * inset = getInset(pos))
3824 return inset->isSpace();
3825 char_type const c = d->text_[pos];
3826 return lyx::isSpace(c);
3831 Paragraph::getParLanguage(BufferParams const & bparams) const
3834 return getFirstFontSettings(bparams).language();
3835 // FIXME: we should check the prev par as well (Lgb)
3836 return bparams.language;
3840 bool Paragraph::isRTL(BufferParams const & bparams) const
3842 return getParLanguage(bparams)->rightToLeft()
3843 && !inInset().getLayout().forceLTR();
3847 void Paragraph::changeLanguage(BufferParams const & bparams,
3848 Language const * from, Language const * to)
3850 // change language including dummy font change at the end
3851 for (pos_type i = 0; i <= size(); ++i) {
3852 Font font = getFontSettings(bparams, i);
3853 if (font.language() == from) {
3854 font.setLanguage(to);
3856 d->requestSpellCheck(i);
3862 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
3864 Language const * doc_language = bparams.language;
3865 for (auto const & f : d->fontlist_)
3866 if (f.font().language() != ignore_language &&
3867 f.font().language() != latex_language &&
3868 f.font().language() != doc_language)
3874 void Paragraph::getLanguages(std::set<Language const *> & langs) const
3876 for (auto const & f : d->fontlist_) {
3877 Language const * lang = f.font().language();
3878 if (lang != ignore_language &&
3879 lang != latex_language)
3885 docstring Paragraph::asString(int options) const
3887 return asString(0, size(), options);
3891 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
3893 odocstringstream os;
3896 && options & AS_STR_LABEL
3897 && !d->params_.labelString().empty())
3898 os << d->params_.labelString() << ' ';
3900 for (pos_type i = beg; i < end; ++i) {
3901 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
3903 char_type const c = d->text_[i];
3904 if (isPrintable(c) || c == '\t'
3905 || (c == '\n' && (options & AS_STR_NEWLINES)))
3907 else if (c == META_INSET && (options & AS_STR_INSETS)) {
3908 if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
3909 LASSERT(runparams != nullptr, return docstring());
3910 getInset(i)->plaintext(os, *runparams);
3912 getInset(i)->toString(os);
3921 void Paragraph::forOutliner(docstring & os, size_t const maxlen,
3922 bool const shorten, bool const label) const
3924 size_t tmplen = shorten ? maxlen + 1 : maxlen;
3925 if (label && !labelString().empty())
3926 os += labelString() + ' ';
3927 if (!layout().isTocCaption())
3929 for (pos_type i = 0; i < size() && os.length() < tmplen; ++i) {
3932 char_type const c = d->text_[i];
3935 else if (c == META_INSET)
3936 getInset(i)->forOutliner(os, tmplen, false);
3939 Text::shortenForOutliner(os, maxlen);
3943 void Paragraph::setInsetOwner(Inset const * inset)
3945 d->inset_owner_ = inset;
3949 int Paragraph::id() const
3955 void Paragraph::setId(int id)
3961 Layout const & Paragraph::layout() const
3967 void Paragraph::setLayout(Layout const & layout)
3969 d->layout_ = &layout;
3973 void Paragraph::setDefaultLayout(DocumentClass const & tc)
3975 setLayout(tc.defaultLayout());
3979 void Paragraph::setPlainLayout(DocumentClass const & tc)
3981 setLayout(tc.plainLayout());
3985 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
3987 if (usePlainLayout())
3988 setPlainLayout(tclass);
3990 setDefaultLayout(tclass);
3994 Inset const & Paragraph::inInset() const
3996 LBUFERR(d->inset_owner_);
3997 return *d->inset_owner_;
4001 ParagraphParameters & Paragraph::params()
4007 ParagraphParameters const & Paragraph::params() const
4013 bool Paragraph::isFreeSpacing() const
4015 if (d->layout_->free_spacing)
4017 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
4021 bool Paragraph::allowEmpty() const
4023 if (d->layout_->keepempty)
4025 return d->inset_owner_ && d->inset_owner_->allowEmpty();
4029 bool Paragraph::brokenBiblio() const
4031 // There is a problem if there is no bibitem at position 0 in
4032 // paragraphs that need one, if there is another bibitem in the
4033 // paragraph or if this paragraph is not supposed to have
4034 // a bibitem inset at all.
4035 return ((d->layout_->labeltype == LABEL_BIBLIO
4036 && (d->insetlist_.find(BIBITEM_CODE) != 0
4037 || d->insetlist_.find(BIBITEM_CODE, 1) > 0))
4038 || (d->layout_->labeltype != LABEL_BIBLIO
4039 && d->insetlist_.find(BIBITEM_CODE) != -1));
4043 int Paragraph::fixBiblio(Buffer const & buffer)
4045 // FIXME: when there was already an inset at 0, the return value is 1,
4046 // which does not tell whether another inset has been remove; the
4047 // cursor cannot be correctly updated.
4049 bool const track_changes = buffer.params().track_changes;
4050 int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
4052 // The case where paragraph is not BIBLIO
4053 if (d->layout_->labeltype != LABEL_BIBLIO) {
4054 if (bibitem_pos == -1)
4055 // No InsetBibitem => OK
4057 // There is an InsetBibitem: remove it!
4058 d->insetlist_.release(bibitem_pos);
4059 eraseChar(bibitem_pos, track_changes);
4060 return (bibitem_pos == 0) ? -1 : -bibitem_pos;
4063 bool const hasbibitem0 = bibitem_pos == 0;
4065 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
4066 // There was an InsetBibitem at pos 0,
4067 // and no other one => OK
4068 if (bibitem_pos == -1)
4070 // there is a bibitem at the 0 position, but since
4071 // there is a second one, we copy the second on the
4072 // first. We're assuming there are at most two of
4073 // these, which there should be.
4074 // FIXME: why does it make sense to do that rather
4075 // than keep the first? (JMarc)
4076 Inset * inset = releaseInset(bibitem_pos);
4077 d->insetlist_.begin()->inset = inset;
4078 return -bibitem_pos;
4081 // We need to create an inset at the beginning
4082 Inset * inset = nullptr;
4083 if (bibitem_pos > 0) {
4084 // there was one somewhere in the paragraph, let's move it
4085 inset = d->insetlist_.release(bibitem_pos);
4086 eraseChar(bibitem_pos, track_changes);
4089 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
4090 InsetCommandParams(BIBITEM_CODE));
4092 Font font(inherit_font, buffer.params().language);
4093 insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
4094 : Change::UNCHANGED));
4096 // This is needed to get the counters right
4097 buffer.updateBuffer();
4102 void Paragraph::checkAuthors(AuthorList const & authorList)
4104 d->changes_.checkAuthors(authorList);
4108 bool Paragraph::isChanged(pos_type pos) const
4110 return lookupChange(pos).changed();
4114 bool Paragraph::isInserted(pos_type pos) const
4116 return lookupChange(pos).inserted();
4120 bool Paragraph::isDeleted(pos_type pos) const
4122 return lookupChange(pos).deleted();
4126 InsetList const & Paragraph::insetList() const
4128 return d->insetlist_;
4132 void Paragraph::setInsetBuffers(Buffer & b)
4134 d->insetlist_.setBuffer(b);
4138 void Paragraph::resetBuffer()
4140 d->insetlist_.resetBuffer();
4144 Inset * Paragraph::releaseInset(pos_type pos)
4146 Inset * inset = d->insetlist_.release(pos);
4147 /// does not honour change tracking!
4148 eraseChar(pos, false);
4153 Inset * Paragraph::getInset(pos_type pos)
4155 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4156 ? d->insetlist_.get(pos) : nullptr;
4160 Inset const * Paragraph::getInset(pos_type pos) const
4162 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4163 ? d->insetlist_.get(pos) : nullptr;
4167 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
4168 pos_type & right, TextCase action)
4170 // process sequences of modified characters; in change
4171 // tracking mode, this approach results in much better
4172 // usability than changing case on a char-by-char basis
4173 // We also need to track the current font, since font
4174 // changes within sequences can occur.
4175 vector<pair<char_type, Font> > changes;
4177 bool const trackChanges = bparams.track_changes;
4179 bool capitalize = true;
4181 for (; pos < right; ++pos) {
4182 char_type oldChar = d->text_[pos];
4183 char_type newChar = oldChar;
4185 // ignore insets and don't play with deleted text!
4186 if (oldChar != META_INSET && !isDeleted(pos)) {
4188 case text_lowercase:
4189 newChar = lowercase(oldChar);
4191 case text_capitalization:
4193 newChar = uppercase(oldChar);
4197 case text_uppercase:
4198 newChar = uppercase(oldChar);
4203 if (isWordSeparator(pos) || isDeleted(pos)) {
4204 // permit capitalization again
4208 if (oldChar != newChar) {
4209 changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
4210 if (pos != right - 1)
4212 // step behind the changing area
4216 int erasePos = pos - changes.size();
4217 for (size_t i = 0; i < changes.size(); i++) {
4218 insertChar(pos, changes[i].first,
4221 if (!eraseChar(erasePos, trackChanges)) {
4224 ++right; // expand selection
4232 int Paragraph::find(docstring const & str, bool cs, bool mw,
4233 pos_type start_pos, bool del) const
4235 pos_type pos = start_pos;
4236 int const strsize = str.length();
4238 pos_type const parsize = d->text_.size();
4239 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
4240 // Ignore "invisible" letters such as ligature breaks
4241 // and hyphenation chars while searching
4242 while (pos < parsize - 1 && isInset(pos)) {
4243 odocstringstream os;
4244 getInset(pos)->toString(os);
4245 if (!getInset(pos)->isLetter() || !os.str().empty())
4249 if (cs && str[i] != d->text_[pos])
4251 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
4253 if (!del && isDeleted(pos))
4260 // if necessary, check whether string matches word
4262 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
4265 && !isWordSeparator(pos))
4269 return pos - start_pos;
4273 char_type Paragraph::getChar(pos_type pos) const
4275 return d->text_[pos];
4279 pos_type Paragraph::size() const
4281 return d->text_.size();
4285 bool Paragraph::empty() const
4287 return d->text_.empty();
4291 bool Paragraph::isInset(pos_type pos) const
4293 return d->text_[pos] == META_INSET;
4297 bool Paragraph::isSeparator(pos_type pos) const
4299 //FIXME: Are we sure this can be the only separator?
4300 return d->text_[pos] == ' ';
4304 void Paragraph::deregisterWords()
4306 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4307 Private::LangWordsMap::const_iterator ite = d->words_.end();
4308 for (; itl != ite; ++itl) {
4309 WordList & wl = theWordList(itl->first);
4310 Private::Words::const_iterator it = (itl->second).begin();
4311 Private::Words::const_iterator et = (itl->second).end();
4312 for (; it != et; ++it)
4319 void Paragraph::locateWord(pos_type & from, pos_type & to,
4320 word_location const loc, bool const ignore_deleted) const
4323 case WHOLE_WORD_STRICT:
4324 if (from == 0 || from == size()
4325 || isWordSeparator(from, ignore_deleted)
4326 || isWordSeparator(from - 1, ignore_deleted)) {
4333 // If we are already at the beginning of a word, do nothing
4334 if (!from || isWordSeparator(from - 1, ignore_deleted))
4339 // always move the cursor to the beginning of previous word
4340 while (from && !isWordSeparator(from - 1, ignore_deleted))
4344 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
4347 // no need to move the 'from' cursor
4351 while (to < size() && !isWordSeparator(to, ignore_deleted))
4356 void Paragraph::collectWords()
4358 for (pos_type pos = 0; pos < size(); ++pos) {
4359 if (isWordSeparator(pos))
4361 pos_type from = pos;
4362 locateWord(from, pos, WHOLE_WORD);
4363 // Work around MSVC warning: The statement
4364 // if (pos < from + lyxrc.completion_minlength)
4365 // triggers a signed vs. unsigned warning.
4366 // I don't know why this happens, it could be a MSVC bug, or
4367 // related to LLP64 (windows) vs. LP64 (unix) programming
4368 // model, or the C++ standard might be ambigous in the section
4369 // defining the "usual arithmetic conversions". However, using
4370 // a temporary variable is safe and works on all compilers.
4371 pos_type const endpos = from + lyxrc.completion_minlength;
4374 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
4375 if (cit == d->fontlist_.end())
4377 Language const * lang = cit->font().language();
4378 docstring const word = asString(from, pos, AS_STR_NONE);
4379 d->words_[lang->lang()].insert(word);
4384 void Paragraph::registerWords()
4386 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4387 Private::LangWordsMap::const_iterator ite = d->words_.end();
4388 for (; itl != ite; ++itl) {
4389 WordList & wl = theWordList(itl->first);
4390 Private::Words::const_iterator it = (itl->second).begin();
4391 Private::Words::const_iterator et = (itl->second).end();
4392 for (; it != et; ++it)
4398 void Paragraph::updateWords()
4406 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
4408 SkipPositionsIterator begin = skips.begin();
4409 SkipPositions::iterator end = skips.end();
4410 if (pos > 0 && begin < end) {
4412 if (end->last == pos - 1) {
4417 skips.insert(end, FontSpan(pos, pos));
4421 Language * Paragraph::Private::locateSpellRange(
4422 pos_type & from, pos_type & to,
4423 SkipPositions & skips) const
4425 // skip leading white space
4426 while (from < to && owner_->isWordSeparator(from))
4428 // don't check empty range
4431 // get current language
4432 Language * lang = getSpellLanguage(from);
4433 pos_type last = from;
4434 bool samelang = true;
4435 bool sameinset = true;
4436 while (last < to && samelang && sameinset) {
4437 // hop to end of word
4438 while (last < to && !owner_->isWordSeparator(last)) {
4439 if (owner_->getInset(last)) {
4440 appendSkipPosition(skips, last);
4441 } else if (owner_->isDeleted(last)) {
4442 appendSkipPosition(skips, last);
4446 // hop to next word while checking for insets
4447 while (sameinset && last < to && owner_->isWordSeparator(last)) {
4448 if (Inset const * inset = owner_->getInset(last))
4449 sameinset = inset->isChar() && inset->isLetter();
4450 if (sameinset && owner_->isDeleted(last)) {
4451 appendSkipPosition(skips, last);
4456 if (sameinset && last < to) {
4457 // now check for language change
4458 samelang = lang == getSpellLanguage(last);
4461 // if language change detected backstep is needed
4469 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
4472 const_cast<Language *>(owner_->getFontSettings(
4473 inset_owner_->buffer().params(), from).language());
4474 if (lang == inset_owner_->buffer().params().language
4475 && !lyxrc.spellchecker_alt_lang.empty()) {
4477 string const lang_variety =
4478 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
4479 lang->setCode(lang_code);
4480 lang->setVariety(lang_variety);
4486 void Paragraph::requestSpellCheck(pos_type pos)
4488 d->requestSpellCheck(pos);
4492 bool Paragraph::needsSpellCheck() const
4494 SpellChecker::ChangeNumber speller_change_number = 0;
4495 if (theSpellChecker())
4496 speller_change_number = theSpellChecker()->changeNumber();
4497 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
4498 d->speller_state_.needsCompleteRefresh(speller_change_number);
4500 return d->needsSpellCheck();
4504 bool Paragraph::Private::ignoreWord(docstring const & word) const
4506 // Ignore words with digits
4507 // FIXME: make this customizable
4508 // (note that some checkers ignore words with digits by default)
4509 docstring::const_iterator cit = word.begin();
4510 docstring::const_iterator const end = word.end();
4511 for (; cit != end; ++cit) {
4512 if (isNumber((*cit)))
4519 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
4520 WordLangTuple & wl, docstring_list & suggestions,
4521 bool do_suggestion, bool check_learned) const
4523 SpellChecker::Result result = SpellChecker::WORD_OK;
4524 SpellChecker * speller = theSpellChecker();
4528 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
4531 locateWord(from, to, WHOLE_WORD, true);
4532 if (from == to || from >= size())
4535 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4536 Language * lang = d->getSpellLanguage(from);
4538 if (getFontSettings(d->inset_owner_->buffer().params(), from).fontInfo().nospellcheck() == FONT_ON)
4541 wl = WordLangTuple(word, lang);
4546 if (needsSpellCheck() || check_learned) {
4548 if (!d->ignoreWord(word)) {
4549 bool const trailing_dot = to < size() && d->text_[to] == '.';
4550 result = speller->check(wl);
4551 if (SpellChecker::misspelled(result) && trailing_dot) {
4552 wl = WordLangTuple(word.append(from_ascii(".")), lang);
4553 result = speller->check(wl);
4554 if (!SpellChecker::misspelled(result)) {
4555 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
4557 from << ".." << to << "]");
4559 // spell check with dot appended failed too
4560 // restore original word/lang value
4561 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4562 wl = WordLangTuple(word, lang);
4566 if (!SpellChecker::misspelled(result)) {
4567 // area up to the begin of the next word is not misspelled
4568 while (end < size() && isWordSeparator(end))
4571 d->setMisspelled(from, end, result);
4573 result = d->speller_state_.getState(from);
4577 suggestions.clear();
4579 if (SpellChecker::misspelled(result)) {
4580 LYXERR(Debug::GUI, "misspelled word: \"" <<
4582 from << ".." << to << "]");
4584 speller->suggest(wl, suggestions);
4590 void Paragraph::anonymize()
4592 // This is a very crude anonymization for now
4593 for (char_type & c : d->text_)
4594 if (isLetterChar(c) || isNumber(c))
4599 void Paragraph::Private::markMisspelledWords(
4600 pos_type const & first, pos_type const & last,
4601 SpellChecker::Result result,
4602 docstring const & word,
4603 SkipPositions const & skips)
4605 if (!SpellChecker::misspelled(result)) {
4606 setMisspelled(first, last, SpellChecker::WORD_OK);
4610 SpellChecker * speller = theSpellChecker();
4611 // locate and enumerate the error positions
4612 int nerrors = speller->numMisspelledWords();
4614 SkipPositionsIterator it = skips.begin();
4615 SkipPositionsIterator et = skips.end();
4616 for (int index = 0; index < nerrors; ++index) {
4619 speller->misspelledWord(index, wstart, wlen);
4620 /// should not happen if speller supports range checks
4621 if (!wlen) continue;
4622 docstring const misspelled = word.substr(wstart, wlen);
4623 wstart += first + numskipped;
4624 if (snext < wstart) {
4625 /// mark the range of correct spelling
4626 numskipped += countSkips(it, et, wstart);
4627 setMisspelled(snext,
4628 wstart - 1, SpellChecker::WORD_OK);
4630 snext = wstart + wlen;
4631 numskipped += countSkips(it, et, snext);
4632 /// mark the range of misspelling
4633 setMisspelled(wstart, snext, result);
4634 LYXERR(Debug::GUI, "misspelled word: \"" <<
4635 misspelled << "\" [" <<
4636 wstart << ".." << (snext-1) << "]");
4639 if (snext <= last) {
4640 /// mark the range of correct spelling at end
4641 setMisspelled(snext, last, SpellChecker::WORD_OK);
4646 void Paragraph::spellCheck() const
4648 SpellChecker * speller = theSpellChecker();
4649 if (!speller || empty() ||!needsSpellCheck())
4653 d->rangeOfSpellCheck(start, endpos);
4654 if (speller->canCheckParagraph()) {
4655 // loop until we leave the range
4656 for (pos_type first = start; first < endpos; ) {
4657 pos_type last = endpos;
4658 Private::SkipPositions skips;
4659 Language * lang = d->locateSpellRange(first, last, skips);
4660 if (first >= endpos)
4662 // start the spell checker on the unit of meaning
4663 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
4664 WordLangTuple wl = WordLangTuple(word, lang);
4665 SpellChecker::Result result = word.size() ?
4666 speller->check(wl) : SpellChecker::WORD_OK;
4667 d->markMisspelledWords(first, last, result, word, skips);
4671 static docstring_list suggestions;
4672 pos_type to = endpos;
4673 while (start < endpos) {
4675 spellCheck(start, to, wl, suggestions, false);
4679 d->readySpellCheck();
4683 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
4685 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
4686 if (result || pos <= 0 || pos > size())
4688 if (check_boundary && (pos == size() || isWordSeparator(pos)))
4689 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
4694 string Paragraph::magicLabel() const
4697 ss << "magicparlabel-" << id();