2 * \file InsetMathMacro.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alejandro Aguilar Sierra
8 * \author Stefan Schimanski
10 * Full author contact details are available in file CREDITS.
15 #include "InsetMathMacro.h"
17 #include "InsetMathChar.h"
18 #include "InsetMathScript.h"
19 #include "MathCompletionList.h"
20 #include "MathExtern.h"
21 #include "MathFactory.h"
23 #include "MathStream.h"
24 #include "MathSupport.h"
27 #include "BufferView.h"
28 #include "CoordCache.h"
31 #include "FuncStatus.h"
32 #include "FuncRequest.h"
33 #include "LaTeXFeatures.h"
36 #include "MetricsInfo.h"
38 #include "frontends/alert.h"
39 #include "frontends/Painter.h"
41 #include "support/debug.h"
42 #include "support/gettext.h"
43 #include "support/lassert.h"
44 #include "support/lstrings.h"
45 #include "support/Changer.h"
46 #include "support/textutils.h"
51 using namespace lyx::support;
57 /// A proxy for the macro values
58 class InsetArgumentProxy : public InsetMath {
61 InsetArgumentProxy(InsetMathMacro * mathMacro, size_t idx)
62 : InsetMath(&mathMacro->buffer()), mathMacro_(mathMacro), idx_(idx),
63 def_(&mathMacro->buffer()) {}
65 InsetArgumentProxy(InsetMathMacro * mathMacro, size_t idx, docstring const & def)
66 : InsetMath(&mathMacro->buffer()), mathMacro_(mathMacro), idx_(idx),
67 def_(&mathMacro->buffer())
72 void setBuffer(Buffer & buffer) override
74 Inset::setBuffer(buffer);
75 def_.setBuffer(buffer);
78 void setOwner(InsetMathMacro * mathMacro) { mathMacro_ = mathMacro; }
80 InsetMathMacro const * owner() { return mathMacro_; }
82 marker_type marker(BufferView const *) const override { return marker_type::NO_MARKER; }
84 InsetCode lyxCode() const override { return ARGUMENT_PROXY_CODE; }
85 /// The math data to use for display
86 MathData const & displayCell(BufferView const * bv) const
88 // handle default macro arguments
89 bool use_def_arg = !mathMacro_->editMetrics(bv)
90 && mathMacro_->cell(idx_).empty();
91 return use_def_arg ? def_ : mathMacro_->cell(idx_);
94 bool addToMathRow(MathRow & mrow, MetricsInfo & mi) const override
96 // macro arguments are in macros
97 LATTEST(mathMacro_->nesting() > 0);
98 /// The macro nesting can change display of insets. Change it locally.
99 Changer chg = changeVar(mi.base.macro_nesting,
100 mathMacro_->nesting() == 1 ? 0 : mathMacro_->nesting());
102 MathRow::Element e_beg(mi, MathRow::BEGIN);
104 e_beg.ar = &mathMacro_->cell(idx_);
105 mrow.push_back(e_beg);
107 mathMacro_->macro()->unlock();
108 bool has_contents = displayCell(mi.base.bv).addToMathRow(mrow, mi);
109 mathMacro_->macro()->lock();
111 // if there was no contents, and the contents is editable,
112 // then we insert a box instead.
113 if (!has_contents && mathMacro_->nesting() == 1) {
114 // mathclass is ord because it should be spaced as a normal atom
115 MathRow::Element e(mi, MathRow::BOX, MC_ORD);
116 e.color = Color_mathline;
121 MathRow::Element e_end(mi, MathRow::END);
123 e_end.ar = &mathMacro_->cell(idx_);
124 mrow.push_back(e_end);
129 void beforeMetrics() const override
131 mathMacro_->macro()->unlock();
134 void afterMetrics() const override
136 mathMacro_->macro()->lock();
139 void beforeDraw(PainterInfo const & pi) const override
141 // if the macro is being edited, then the painter is in
143 if (mathMacro_->editMetrics(pi.base.bv))
144 pi.pain.leaveMonochromeMode();
147 void afterDraw(PainterInfo const & pi) const override
149 if (mathMacro_->editMetrics(pi.base.bv))
150 pi.pain.enterMonochromeMode(Color_mathmacroblend);
153 void metrics(MetricsInfo &, Dimension &) const override {
154 // This should never be invoked, since InsetArgumentProxy insets are linearized
158 void draw(PainterInfo &, int, int) const override {
159 // This should never be invoked, since InsetArgumentProxy insets are linearized
163 int kerning(BufferView const * bv) const override
165 return displayCell(bv).kerning(bv);
167 // write(), normalize(), infoize() and infoize2() are not needed since
168 // InsetMathMacro uses the definition and not the expanded cells.
170 void maple(MapleStream & ms) const override { ms << mathMacro_->cell(idx_); }
172 void maxima(MaximaStream & ms) const override { ms << mathMacro_->cell(idx_); }
174 void mathematica(MathematicaStream & ms) const override { ms << mathMacro_->cell(idx_); }
176 void mathmlize(MathMLStream & ms) const override { ms << mathMacro_->cell(idx_); }
178 void htmlize(HtmlStream & ms) const override { ms << mathMacro_->cell(idx_); }
180 void octave(OctaveStream & os) const override { os << mathMacro_->cell(idx_); }
182 MathClass mathClass() const override
185 // This can be refined once the pointer issues are fixed. I did not
186 // notice any immediate crash with the following code, but it is risky
188 //return mathMacro_->cell(idx_).mathClass();
193 Inset * clone() const override
195 return new InsetArgumentProxy(*this);
198 InsetMathMacro * mathMacro_;
206 /// Private implementation of InsetMathMacro
207 class InsetMathMacro::Private {
209 Private(Buffer * buf, docstring const & name)
210 : name_(name), displayMode_(DISPLAY_INIT),
211 expanded_(buf), definition_(buf), attachedArgsNum_(0),
212 optionals_(0), nextFoldMode_(true), macroBackup_(buf),
213 macro_(nullptr), needsUpdate_(false), isUpdating_(false),
214 appetite_(9), nesting_(0), limits_(AUTO_LIMITS)
217 /// Update the pointers to our owner of all expanded macros.
218 /// This needs to be called every time a copy of the owner is created
220 void updateChildren(InsetMathMacro * owner);
221 /// Recursively update the pointers of all expanded macros
222 /// appearing in the arguments of the current macro
223 void updateNestedChildren(InsetMathMacro * owner, InsetMathNest * ni);
226 /// current display mode
227 DisplayMode displayMode_;
228 /// expanded macro with ArgumentProxies
230 /// macro definition with #1,#2,.. insets
231 MathData definition_;
232 /// number of arguments that were really attached
233 size_t attachedArgsNum_;
234 /// optional argument attached? (only in DISPLAY_NORMAL mode)
236 /// fold mode to be set in next metrics call?
238 /// if macro_ == true, then here is a copy of the macro
239 /// don't use it for locking
240 MacroData macroBackup_;
241 /// if macroNotFound_ == false, then here is a reference to the macro
242 /// this might invalidate after metrics was called
243 MacroData const * macro_;
245 mutable std::map<BufferView const *, bool> editing_;
247 std::string required_;
248 /// update macro representation
252 /// maximal number of arguments the macro is greedy for
254 /// Level of nesting in macros (including this one)
261 void InsetMathMacro::Private::updateChildren(InsetMathMacro * owner)
263 for (size_t i = 0; i < expanded_.size(); ++i) {
264 InsetArgumentProxy * p = dynamic_cast<InsetArgumentProxy *>(expanded_[i].nucleus());
268 InsetMathNest * ni = expanded_[i].nucleus()->asNestInset();
270 updateNestedChildren(owner, ni);
274 // The macro_ pointer is updated when MathData::metrics() is
275 // called. However, when instant preview is on or the macro is
276 // not on screen, MathData::metrics() is not called and we may
277 // have a dangling pointer. As a safety measure, when a macro
278 // is copied, always let macro_ point to the backup copy of the
279 // MacroData structure. This backup is updated every time the
280 // macro is changed, so it will not become stale.
281 macro_ = ¯oBackup_;
286 void InsetMathMacro::Private::updateNestedChildren(InsetMathMacro * owner, InsetMathNest * ni)
288 for (size_t i = 0; i < ni->nargs(); ++i) {
289 MathData & ar = ni->cell(i);
290 for (size_t j = 0; j < ar.size(); ++j) {
291 InsetArgumentProxy * ap = dynamic_cast
292 <InsetArgumentProxy *>(ar[j].nucleus());
294 InsetMathMacro::Private * md = ap->owner()->d;
296 md->macro_ = &md->macroBackup_;
299 InsetMathNest * imn = ar[j].nucleus()->asNestInset();
301 updateNestedChildren(owner, imn);
307 InsetMathMacro::InsetMathMacro(Buffer * buf, docstring const & name)
308 : InsetMathNest(buf, 0), d(new Private(buf, name))
312 InsetMathMacro::InsetMathMacro(InsetMathMacro const & that)
313 : InsetMathNest(that), d(new Private(*that.d))
315 // FIXME This should not really be necessary, but when we are
316 // initializing the table of global macros, we create macros
317 // with no associated Buffer.
319 setBuffer(*that.buffer_);
320 d->updateChildren(this);
324 InsetMathMacro & InsetMathMacro::operator=(InsetMathMacro const & that)
328 InsetMathNest::operator=(that);
330 d->updateChildren(this);
335 InsetMathMacro::~InsetMathMacro()
341 bool InsetMathMacro::addToMathRow(MathRow & mrow, MetricsInfo & mi) const
343 // set edit mode for which we will have calculated row.
344 // This is the same as what is done in metrics().
345 d->editing_[mi.base.bv] = editMode(mi.base.bv);
347 // For now we do not linearize in the following cases (can be improved)
348 // - display mode different from normal
349 // - editing with parameter list
350 // - editing with box around macro
351 if (displayMode() != InsetMathMacro::DISPLAY_NORMAL
352 || (d->editing_[mi.base.bv] && lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST))
353 return InsetMath::addToMathRow(mrow, mi);
355 /// The macro nesting can change display of insets. Change it locally.
356 Changer chg = changeVar(mi.base.macro_nesting, d->nesting_);
358 MathRow::Element e_beg(mi, MathRow::BEGIN);
360 e_beg.marker = (d->nesting_ == 1) ? marker(mi.base.bv) : marker_type::NO_MARKER;
361 mrow.push_back(e_beg);
364 bool has_contents = d->expanded_.addToMathRow(mrow, mi);
367 // if there was no contents and the array is editable, then we
368 // insert a grey box instead.
369 if (!has_contents && mi.base.macro_nesting == 1) {
370 // mathclass is unknown because it is irrelevant for spacing
371 MathRow::Element e(mi, MathRow::BOX);
372 e.color = Color_mathmacroblend;
377 MathRow::Element e_end(mi, MathRow::END);
379 e_end.marker = (d->nesting_ == 1) ? marker(mi.base.bv) : marker_type::NO_MARKER;
380 mrow.push_back(e_end);
386 /// Whether the inset allows \(no)limits
387 bool InsetMathMacro::allowsLimitsChange() const
389 // similar to the code in mathClass(), except that we search for
390 // the right-side class.
391 MathClass mc = MC_UNKNOWN;
392 if (MacroData const * m = macroBackup()) {
393 // If it is a global macro and is defined explicitly
395 mc = string_to_class(m->symbol()->extra);
397 // Otherwise guess from the expanded macro
398 if (mc == MC_UNKNOWN)
399 mc = d->expanded_.lastMathClass();
405 Limits InsetMathMacro::defaultLimits(bool display) const
407 if (d->expanded_.empty())
409 // Guess from the expanded macro
410 InsetMath const * in = d->expanded_.back().nucleus();
411 Limits const lim = in->limits() == AUTO_LIMITS
412 ? in->defaultLimits(display) : in->limits();
413 LATTEST(lim != AUTO_LIMITS);
418 Limits InsetMathMacro::limits() const
424 void InsetMathMacro::limits(Limits lim)
430 void InsetMathMacro::beforeMetrics() const
436 void InsetMathMacro::afterMetrics() const
442 void InsetMathMacro::beforeDraw(PainterInfo const & pi) const
444 if (d->editing_[pi.base.bv])
445 pi.pain.enterMonochromeMode(Color_mathmacroblend);
449 void InsetMathMacro::afterDraw(PainterInfo const & pi) const
451 if (d->editing_[pi.base.bv])
452 pi.pain.leaveMonochromeMode();
456 Inset * InsetMathMacro::clone() const
458 InsetMathMacro * copy = new InsetMathMacro(*this);
459 copy->d->needsUpdate_ = true;
460 //copy->d->expanded_.clear();
465 void InsetMathMacro::normalize(NormalStream & os) const
467 os << "[macro " << name();
468 for (size_t i = 0; i < nargs(); ++i)
469 os << ' ' << cell(i);
474 InsetMathMacro::DisplayMode InsetMathMacro::displayMode() const
476 return d->displayMode_;
480 bool InsetMathMacro::extraBraces() const
482 return d->displayMode_ == DISPLAY_NORMAL && arity() > 0;
486 docstring InsetMathMacro::name() const
488 if (d->displayMode_ == DISPLAY_UNFOLDED)
489 return asString(cell(0));
495 docstring InsetMathMacro::macroName() const
501 int InsetMathMacro::nesting() const
507 void InsetMathMacro::cursorPos(BufferView const & bv,
508 CursorSlice const & sl, bool boundary, int & x, int & y) const
510 // We may have 0 arguments, but InsetMathNest requires at least one.
512 InsetMathNest::cursorPos(bv, sl, boundary, x, y);
516 bool InsetMathMacro::editMode(BufferView const * bv) const {
517 // find this in cursor trace
518 DocIterator const & cur =
519 // Do not move the reference while selecting with the mouse to avoid
520 // flicker due to changing metrics
521 bv->mouseSelecting() ? bv->cursor().realAnchor() : bv->cursor();
522 for (size_t i = 0; i != cur.depth(); ++i)
523 if (&cur[i].inset() == this) {
524 // look if there is no other macro in edit mode above
526 for (; i != cur.depth(); ++i) {
527 InsetMath * im = cur[i].asInsetMath();
529 InsetMathMacro const * macro = im->asMacro();
530 if (macro && macro->displayMode() == DISPLAY_NORMAL)
535 // ok, none found, I am the highest one
543 MacroData const * InsetMathMacro::macro() const
549 bool InsetMathMacro::editMetrics(BufferView const * bv) const
551 return d->editing_[bv];
555 marker_type InsetMathMacro::marker(BufferView const * bv) const
558 return marker_type::NO_MARKER;
560 switch (d->displayMode_) {
562 case DISPLAY_INTERACTIVE_INIT:
563 return marker_type::NO_MARKER;
564 case DISPLAY_UNFOLDED:
565 return marker_type::MARKER;
567 switch (lyxrc.macro_edit_style) {
568 case LyXRC::MACRO_EDIT_INLINE:
569 return marker_type::MARKER2;
570 case LyXRC::MACRO_EDIT_INLINE_BOX:
571 return d->editing_[bv] ? marker_type::BOX_MARKER : marker_type::MARKER2;
572 case LyXRC::MACRO_EDIT_LIST:
573 return marker_type::MARKER2;
577 return marker_type::NO_MARKER;
581 void InsetMathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
583 /// The macro nesting can change display of insets. Change it locally.
584 Changer chg = changeVar(mi.base.macro_nesting, d->nesting_);
586 // set edit mode for which we will have calculated metrics. But only
587 d->editing_[mi.base.bv] = editMode(mi.base.bv);
589 // calculate new metrics according to display mode
590 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
591 Changer dummy = mi.base.changeFontSet("lyxtex");
592 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
593 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
594 Changer dummy = mi.base.changeFontSet("lyxtex");
595 cell(0).metrics(mi, dim);
597 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
598 dim.wid += bsdim.width() + 1;
599 dim.asc = max(bsdim.ascent(), dim.ascent());
600 dim.des = max(bsdim.descent(), dim.descent());
601 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
602 && d->editing_[mi.base.bv]) {
603 // Macro will be edited in a old-style list mode here:
607 FontInfo labelFont = sane_font;
608 math_font_max_dim(labelFont, fontDim.asc, fontDim.des);
610 // get dimension of components of list view
612 nameDim.wid = mathed_string_width(mi.base.font, from_ascii("Macro \\") + name() + ": ");
613 nameDim.asc = fontDim.asc;
614 nameDim.des = fontDim.des;
617 argDim.wid = mathed_string_width(labelFont, from_ascii("#9: "));
618 argDim.asc = fontDim.asc;
619 argDim.des = fontDim.des;
622 d->definition_.metrics(mi, defDim);
625 dim.wid = nameDim.wid + defDim.wid;
626 dim.asc = max(nameDim.asc, defDim.asc);
627 dim.des = max(nameDim.des, defDim.des);
629 for (idx_type i = 0; i < nargs(); ++i) {
631 cell(i).metrics(mi, cdim);
632 dim.des += max(argDim.height(), cdim.height()) + 1;
633 dim.wid = max(dim.wid, argDim.wid + cdim.wid);
636 // make space for box and markers, 2 pixels
641 // We should not be here, since the macro is linearized in this case.
647 int InsetMathMacro::kerning(BufferView const * bv) const {
648 if (d->displayMode_ == DISPLAY_NORMAL && !d->editing_[bv])
649 return d->expanded_.kerning(bv);
655 void InsetMathMacro::updateMacro(MacroContext const & mc)
658 d->macro_ = mc.get(name());
659 if (d->macro_ && d->macroBackup_ != *d->macro_) {
660 d->macroBackup_ = *d->macro_;
661 d->needsUpdate_ = true;
669 class InsetMathMacro::UpdateLocker
672 explicit UpdateLocker(InsetMathMacro & mm) : mac(mm)
674 mac.d->isUpdating_ = true;
676 ~UpdateLocker() { mac.d->isUpdating_ = false; }
678 InsetMathMacro & mac;
680 /** Avoid wrong usage of UpdateLocker.
681 To avoid wrong usage:
682 UpdateLocker(...); // wrong
683 UpdateLocker locker(...); // right
685 #define UpdateLocker(x) unnamed_UpdateLocker;
686 // Tip gotten from Bobby Schmidt's column in C/C++ Users Journal
689 void InsetMathMacro::updateRepresentation(Cursor * cur, MacroContext const & mc,
690 UpdateType utype, int nesting)
692 // block recursive calls (bug 8999)
696 UpdateLocker locker(*this);
699 if (d->macro_ == nullptr)
702 // remember nesting level of this macro
703 d->nesting_ = nesting;
706 d->required_ = d->macro_->required();
709 // non-normal mode? We are done!
710 || (d->displayMode_ != DISPLAY_NORMAL))
713 d->needsUpdate_ = false;
715 // get default values of macro
716 vector<docstring> const & defaults = d->macro_->defaults();
718 // create MathMacroArgumentValue objects pointing to the cells of the macro
719 vector<MathData> values(nargs(), MathData(buffer_));
720 for (size_t i = 0; i < nargs(); ++i) {
721 InsetArgumentProxy * proxy;
722 if (i < defaults.size())
723 proxy = new InsetArgumentProxy(this, i, defaults[i]);
725 proxy = new InsetArgumentProxy(this, i);
726 values[i].insert(0, MathAtom(proxy));
728 // expanding macro with the values
729 // Only update the argument macros if anything was expanded or the LyX
730 // representation part does not contain the macro itself, otherwise we
731 // would get an endless loop (bugs 9140 and 11595). UpdateLocker does
732 // not work in this case, since MacroData::expand() creates new
733 // InsetMathMacro objects, so this would be a different recursion path
734 // than the one protected by UpdateLocker.
735 docstring const & display = d->macro_->display();
736 docstring const latexname = from_ascii("\\") + macroName();
737 bool const ret = d->macro_->expand(values, d->expanded_);
738 d->expanded_.setBuffer(buffer());
739 if (ret && !support::contains(display, latexname)) {
740 if (utype == OutputUpdate && !d->expanded_.empty())
741 d->expanded_.updateMacros(cur, mc, utype, nesting);
743 // get definition for list edit mode
744 asArray(display.empty() ? d->macro_->definition() : display,
745 d->definition_, Parse::QUIET | Parse::MACRODEF);
749 void InsetMathMacro::draw(PainterInfo & pi, int x, int y) const
751 Dimension const dim = dimension(*pi.base.bv);
756 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
757 Changer dummy = pi.base.changeFontSet("lyxtex");
758 pi.pain.text(x, y, from_ascii("\\") + name(), pi.base.font);
759 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
760 Changer dummy = pi.base.changeFontSet("lyxtex");
761 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
762 x += mathed_string_width(pi.base.font, from_ascii("\\")) + 1;
763 cell(0).draw(pi, x, y);
764 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
765 && d->editing_[pi.base.bv]) {
766 // Macro will be edited in a old-style list mode here:
768 CoordCache const & coords = pi.base.bv->coordCache();
769 FontInfo const & labelFont = sane_font;
771 // box needs one pixel
774 // get maximal font height
776 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
779 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
780 pi.pain.text(x, y, label, labelFont);
781 x += mathed_string_width(labelFont, label);
784 d->definition_.draw(pi, x, y);
785 Dimension const & defDim = coords.getArrays().dim(&d->definition_);
786 y += max(fontDim.des, defDim.des);
789 docstring str = from_ascii("#9");
790 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
791 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
793 for (idx_type i = 0; i < nargs(); ++i) {
795 Dimension const & cdim = coords.getArrays().dim(&cell(i));
797 y += max(fontDim.asc, cdim.asc) + 1;
801 pi.pain.text(x, y, str, labelFont);
803 pi.pain.text(x, y, from_ascii(":"), labelFont);
807 cell(i).draw(pi, x, y);
810 y += max(fontDim.des, cdim.des);
813 pi.pain.rectangle(expx, expy - dim.asc + 1, dim.wid - 1,
814 dim.height() - 2, Color_mathmacroframe);
816 // We should not be here, since the macro is linearized in this case.
820 // edit mode changed?
821 if (d->editing_[pi.base.bv] != editMode(pi.base.bv))
822 pi.base.bv->cursor().screenUpdateFlags(Update::SinglePar);
826 void InsetMathMacro::setDisplayMode(InsetMathMacro::DisplayMode mode, int appetite)
828 if (d->displayMode_ != mode) {
829 // transfer name if changing from or to DISPLAY_UNFOLDED
830 if (mode == DISPLAY_UNFOLDED) {
831 cells_.resize(1, MathData(buffer_));
832 asArray(d->name_, cell(0));
833 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
834 d->name_ = asString(cell(0));
838 d->displayMode_ = mode;
839 d->needsUpdate_ = true;
842 // the interactive init mode is non-greedy by default
844 d->appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
846 d->appetite_ = size_t(appetite);
850 InsetMathMacro::DisplayMode InsetMathMacro::computeDisplayMode() const
852 if (d->nextFoldMode_ && d->macro_ && !d->macro_->locked())
853 return DISPLAY_NORMAL;
855 return DISPLAY_UNFOLDED;
859 bool InsetMathMacro::validName() const
861 docstring n = name();
866 // converting back and force doesn't swallow anything?
869 if (asString(ma) != n)
874 for (char_type c : n) {
875 if (!(c >= 'a' && c <= 'z')
876 && !(c >= 'A' && c <= 'Z')
886 size_t InsetMathMacro::arity() const
888 if (d->displayMode_ == DISPLAY_NORMAL )
889 return cells_.size();
895 size_t InsetMathMacro::optionals() const
897 return d->optionals_;
901 void InsetMathMacro::setOptionals(int n)
903 if (n <= int(nargs()))
908 size_t InsetMathMacro::appetite() const
914 MathClass InsetMathMacro::mathClass() const
916 // This can be just a heuristic, since it is only considered for display
917 // when the macro is not linearised. Therefore it affects:
918 // * The spacing of the inset while being edited,
919 // * Intelligent splitting
920 // * Cursor word movement (Ctrl-Arrow).
921 if (MacroData const * m = macroBackup()) {
922 // If it is a global macro and is defined explicitly
924 MathClass mc = string_to_class(m->symbol()->extra);
925 if (mc != MC_UNKNOWN)
929 // Otherwise guess from the expanded macro
930 return d->expanded_.mathClass();
934 InsetMath::mode_type InsetMathMacro::currentMode() const
936 // User defined macros are always assumed to be mathmode macros.
937 // Only the global macros defined in lib/symbols may be textmode.
938 if (MacroData const * m = macroBackup()) {
939 if (m->symbol() && m->symbol()->extra == "textmode")
944 // Unknown macros are undecided.
945 return UNDECIDED_MODE;
949 MacroData const * InsetMathMacro::macroBackup() const
952 return &d->macroBackup_;
953 if (MacroData const * data = MacroTable::globalMacros().get(name()))
959 void InsetMathMacro::validate(LaTeXFeatures & features) const
961 // Immediately after a document is loaded, in some cases the MacroData
962 // of the global macros defined in the lib/symbols file may still not
963 // be known to the macro machinery because it will be set only after
964 // the first call to updateMacros(). This is not a problem unless
965 // instant preview is on for math, in which case we will be missing
966 // the corresponding requirements.
967 // In this case, we get the required info from the global macro table.
968 if (!d->required_.empty())
969 features.require(d->required_);
970 else if (!d->macro_) {
971 // Update requires for known global macros.
972 MacroData const * data = MacroTable::globalMacros().get(name());
973 if (data && !data->required().empty())
974 features.require(data->required());
977 // Validate the cells and the definition.
978 // However, don't validate the definition if the macro is
979 // from the symbols file and has not been redefined, because
980 // in this case the definition is only used for screen display.
981 MathWordList const & words = mathedWordList();
982 MathWordList::const_iterator it = words.find(name());
984 buffer().listMacroNames(macros);
985 if (it == words.end() || it->second.inset != "macro"
986 || macros.find(name()) != macros.end()) {
987 if (displayMode() == DISPLAY_NORMAL) {
988 d->definition_.validate(features);
989 } else if (displayMode() == DISPLAY_INIT) {
990 MathData ar(const_cast<Buffer *>(&buffer()));
991 MacroData const * data = buffer().getMacro(name());
993 // Avoid recursion on a recursive macro definition
994 docstring const & def = data->definition();
995 int pos = tokenPos(def, '\\', name());
996 char_type c = pos + name().size() < def.size()
997 ? def.at(pos + name().size()) : 0;
998 if (pos < 0 || (name().size() > 1 &&
999 ((c >= 'a' && c <= 'z') ||
1000 (c >= 'A' && c <= 'Z')))) {
1002 ar.validate(features);
1007 InsetMathNest::validate(features);
1011 void InsetMathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
1013 cur.screenUpdateFlags(Update::SinglePar);
1014 InsetMathNest::edit(cur, front, entry_from);
1018 Inset * InsetMathMacro::editXY(Cursor & cur, int x, int y)
1020 // We may have 0 arguments, but InsetMathNest requires at least one.
1022 cur.screenUpdateFlags(Update::SinglePar);
1023 return InsetMathNest::editXY(cur, x, y);
1029 void InsetMathMacro::removeArgument(pos_type pos) {
1030 if (d->displayMode_ == DISPLAY_NORMAL) {
1031 LASSERT(size_t(pos) < cells_.size(), return);
1032 cells_.erase(cells_.begin() + pos);
1033 if (size_t(pos) < d->attachedArgsNum_)
1034 --d->attachedArgsNum_;
1035 if (size_t(pos) < d->optionals_) {
1039 d->needsUpdate_ = true;
1044 void InsetMathMacro::insertArgument(pos_type pos) {
1045 if (d->displayMode_ == DISPLAY_NORMAL) {
1046 LASSERT(size_t(pos) <= cells_.size(), return);
1047 cells_.insert(cells_.begin() + pos, MathData(buffer_));
1048 if (size_t(pos) < d->attachedArgsNum_)
1049 ++d->attachedArgsNum_;
1050 if (size_t(pos) < d->optionals_)
1053 d->needsUpdate_ = true;
1058 void InsetMathMacro::detachArguments(vector<MathData> & args, bool strip)
1060 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
1063 // strip off empty cells, but not more than arity-attachedArgsNum_
1066 for (i = cells_.size(); i > d->attachedArgsNum_; --i)
1067 if (!cell(i - 1).empty()) break;
1068 args.erase(args.begin() + i, args.end());
1071 d->attachedArgsNum_ = 0;
1072 d->expanded_ = MathData(buffer_);
1075 d->needsUpdate_ = true;
1079 void InsetMathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
1081 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
1083 for (auto & cell : cells_)
1084 cell.setBuffer(*buffer_);
1085 d->attachedArgsNum_ = args.size();
1086 cells_.resize(arity, MathData(buffer_));
1087 d->expanded_ = MathData(buffer_);
1088 d->optionals_ = optionals;
1090 d->needsUpdate_ = true;
1094 bool InsetMathMacro::idxFirst(Cursor & cur) const
1096 cur.screenUpdateFlags(Update::SinglePar);
1097 return InsetMathNest::idxFirst(cur);
1101 bool InsetMathMacro::idxLast(Cursor & cur) const
1103 cur.screenUpdateFlags(Update::SinglePar);
1104 return InsetMathNest::idxLast(cur);
1108 bool InsetMathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
1110 if (d->displayMode_ == DISPLAY_UNFOLDED) {
1111 docstring const & unfolded_name = name();
1112 if (unfolded_name != d->name_) {
1113 // The macro name was changed
1114 Cursor inset_cursor = old;
1115 int macroSlice = inset_cursor.find(this);
1116 // returning true means the cursor is "now" invalid,
1118 LASSERT(macroSlice != -1, return true);
1119 inset_cursor.cutOff(macroSlice);
1120 inset_cursor.recordUndoInset();
1122 inset_cursor.cell().erase(inset_cursor.pos());
1123 inset_cursor.cell().insert(inset_cursor.pos(),
1124 createInsetMath(unfolded_name, cur.buffer()));
1126 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
1130 cur.screenUpdateFlags(Update::Force);
1131 return InsetMathNest::notifyCursorLeaves(old, cur);
1135 void InsetMathMacro::fold(Cursor & cur)
1137 if (!d->nextFoldMode_) {
1138 d->nextFoldMode_ = true;
1139 cur.screenUpdateFlags(Update::SinglePar);
1144 void InsetMathMacro::unfold(Cursor & cur)
1146 if (d->nextFoldMode_) {
1147 d->nextFoldMode_ = false;
1148 cur.screenUpdateFlags(Update::SinglePar);
1153 bool InsetMathMacro::folded() const
1155 return d->nextFoldMode_;
1159 void InsetMathMacro::write(TeXMathStream & os) const
1161 mode_type mode = currentMode();
1162 MathEnsurer ensurer(os, mode == MATH_MODE, true, mode == TEXT_MODE);
1164 // Check if the macro name is encodable. Otherwise we might crash (#11855).
1165 docstring const name_in = name();
1166 docstring name_recoded;
1167 docstring uncodable;
1168 for (char_type c : name_in) {
1169 if (!os.encoding()) {
1173 if (os.encoding()->encodable(c) || os.output() == TeXMathStream::wsSearchAdv)
1176 switch (os.output()) {
1177 case TeXMathStream::wsDryrun: {
1178 os << "<" << _("LyX Warning: ")
1179 << _("uncodable character") << " '";
1180 os << docstring(1, c);
1184 case TeXMathStream::wsPreview: {
1185 // indicate the encoding error by a boxed '?'
1186 os << "{\\fboxsep=1pt\\fbox{?}}";
1187 LYXERR0("Uncodable character" << " '"
1192 case TeXMathStream::wsDefault:
1194 // record for error message
1201 if (!uncodable.empty()) {
1202 frontend::Alert::warning(
1203 _("Uncodable characters in math macro"),
1204 support::bformat(_("The macro name '%1$s' contains a character\n"
1205 "that is not encodable in the current encoding (%2$s).\n"
1206 "Please fix this macro."), name_in, uncodable));
1210 if (d->displayMode_ != DISPLAY_NORMAL) {
1211 os << "\\" << name_recoded;
1212 if (name_recoded.size() != 1 || isAlphaASCII(name_recoded[0]))
1213 os.pendingSpace(true);
1218 // we should be ok to continue even if this fails.
1221 // Always protect macros in a fragile environment
1225 os << "\\" << name_recoded;
1228 // Optional arguments:
1229 // First find last non-empty optional argument
1230 idx_type emptyOptFrom = 0;
1232 for (; i < cells_.size() && i < d->optionals_; ++i) {
1233 if (!cell(i).empty())
1234 emptyOptFrom = i + 1;
1237 // print out optionals
1238 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
1240 // For correctly parsing it when a document is reloaded, we
1241 // need to enclose an optional argument in braces if it starts
1242 // with a script inset with empty nucleus or ends with a
1243 // delimiter-size-modifier macro (see #10497 and #11346).
1244 // We also need to do that when the optional argument
1245 // contains macros with optionals.
1246 bool braced = false;
1247 size_type last = cell(i).size() - 1;
1248 if (!cell(i).empty() && cell(i)[last]->asUnknownInset()) {
1249 latexkeys const * l = in_word_set(cell(i)[last]->name());
1250 braced = (l && l->inset == "big");
1251 } else if (!cell(i).empty() && cell(i)[0]->asScriptInset()) {
1252 braced = cell(i)[0]->asScriptInset()->nuc().empty();
1254 for (size_type j = 0; j < cell(i).size(); ++j) {
1255 InsetMathMacro const * ma = cell(i)[j]->asMacro();
1256 if (ma && ma->optionals()) {
1263 os << "[{" << cell(i) << "}]";
1265 os << "[" << cell(i) << "]";
1268 // skip the tailing empty optionals
1271 // Print remaining arguments
1272 for (; i < cells_.size(); ++i) {
1273 if (cell(i).size() == 1
1274 && cell(i)[0].nucleus()->asCharInset()
1275 && isASCII(cell(i)[0].nucleus()->asCharInset()->getChar())) {
1280 os << "{" << cell(i) << "}";
1284 // add space if there was no argument
1285 // or add braces if we have optionals but none are present and [ follows
1287 os.pendingSpace(true);
1288 os.useBraces(d->optionals_ > 0);
1291 // write \(no)limits modifiers if relevant
1296 void InsetMathMacro::maple(MapleStream & os) const
1298 lyx::maple(d->expanded_, os);
1302 void InsetMathMacro::maxima(MaximaStream & os) const
1304 lyx::maxima(d->expanded_, os);
1308 void InsetMathMacro::mathematica(MathematicaStream & os) const
1310 lyx::mathematica(d->expanded_, os);
1314 void InsetMathMacro::mathmlize(MathMLStream & ms) const
1316 // macro_ is 0 if this is an unknown macro
1317 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1319 docstring const xmlname = d->macro_->xmlname();
1320 if (!xmlname.empty()) {
1321 char const * type = d->macro_->MathMLtype();
1322 ms << MTagInline(type) << xmlname << ETagInline(type);
1326 if (d->expanded_.empty()) {
1327 // this means that we do not recognize the macro
1328 throw MathExportException();
1334 void InsetMathMacro::htmlize(HtmlStream & os) const
1336 // macro_ is 0 if this is an unknown macro
1337 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1339 docstring const xmlname = d->macro_->xmlname();
1340 if (!xmlname.empty()) {
1341 os << ' ' << xmlname << ' ';
1345 if (d->expanded_.empty()) {
1346 // this means that we do not recognize the macro
1347 throw MathExportException();
1353 void InsetMathMacro::octave(OctaveStream & os) const
1355 lyx::octave(d->expanded_, os);
1359 void InsetMathMacro::infoize(odocstream & os) const
1361 os << bformat(_("Macro: %1$s"), name());
1365 void InsetMathMacro::infoize2(odocstream & os) const
1367 os << bformat(_("Macro: %1$s"), name());
1371 bool InsetMathMacro::completionSupported(Cursor const & cur) const
1373 if (cur.buffer()->isReadonly())
1376 if (displayMode() != DISPLAY_UNFOLDED)
1377 return InsetMathNest::completionSupported(cur);
1379 return lyxrc.completion_popup_math
1380 && cur.bv().cursor().pos() == int(name().size());
1384 bool InsetMathMacro::inlineCompletionSupported(Cursor const & cur) const
1386 if (cur.buffer()->isReadonly())
1389 if (displayMode() != DISPLAY_UNFOLDED)
1390 return InsetMathNest::inlineCompletionSupported(cur);
1392 return lyxrc.completion_inline_math
1393 && cur.bv().cursor().pos() == int(name().size());
1397 bool InsetMathMacro::automaticInlineCompletion() const
1399 if (displayMode() != DISPLAY_UNFOLDED)
1400 return InsetMathNest::automaticInlineCompletion();
1402 return lyxrc.completion_inline_math;
1406 bool InsetMathMacro::automaticPopupCompletion() const
1408 if (displayMode() != DISPLAY_UNFOLDED)
1409 return InsetMathNest::automaticPopupCompletion();
1411 return lyxrc.completion_popup_math;
1415 CompletionList const *
1416 InsetMathMacro::createCompletionList(Cursor const & cur) const
1418 if (displayMode() != DISPLAY_UNFOLDED)
1419 return InsetMathNest::createCompletionList(cur);
1421 return new MathCompletionList(cur.bv().cursor());
1425 docstring InsetMathMacro::completionPrefix(Cursor const & cur) const
1427 if (displayMode() != DISPLAY_UNFOLDED)
1428 return InsetMathNest::completionPrefix(cur);
1430 return "\\" + name();
1434 bool InsetMathMacro::insertCompletion(Cursor & cur, docstring const & s, bool finished)
1436 if (cur.buffer()->isReadonly())
1439 if (displayMode() != DISPLAY_UNFOLDED)
1440 return InsetMathNest::insertCompletion(cur, s, finished);
1442 if (!completionSupported(cur))
1445 // Contrary to Text, the whole inset should be recorded (#12581).
1446 cur.recordUndoInset();
1448 // append completion
1449 docstring newName = name() + s;
1450 asArray(newName, cell(0));
1451 cur.bv().cursor().pos() = name().size();
1452 cur.screenUpdateFlags(Update::SinglePar);
1456 cur.bv().cursor().pop();
1457 ++cur.bv().cursor().pos();
1458 cur.screenUpdateFlags(Update::SinglePar);
1465 void InsetMathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
1466 Dimension & dim) const
1468 if (displayMode() != DISPLAY_UNFOLDED)
1469 InsetMathNest::completionPosAndDim(cur, x, y, dim);
1471 // get inset dimensions
1472 dim = cur.bv().coordCache().insets().dim(this);
1473 // FIXME: these 3 are no accurate, but should depend on the font.
1474 // Now the popup jumps down if you enter a char with descent > 0.
1480 = cur.bv().coordCache().insets().xy(this);
1486 void InsetMathMacro::setBuffer(Buffer & buffer)
1488 d->definition_.setBuffer(buffer);
1489 InsetMathNest::setBuffer(buffer);