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"
22 #include "MathStream.h"
23 #include "MathSupport.h"
26 #include "BufferView.h"
27 #include "CoordCache.h"
29 #include "FuncStatus.h"
30 #include "FuncRequest.h"
31 #include "LaTeXFeatures.h"
34 #include "MetricsInfo.h"
36 #include "frontends/Painter.h"
38 #include "support/debug.h"
39 #include "support/gettext.h"
40 #include "support/lassert.h"
41 #include "support/lstrings.h"
42 #include "support/Changer.h"
43 #include "support/textutils.h"
48 using namespace lyx::support;
54 /// A proxy for the macro values
55 class InsetArgumentProxy : public InsetMath {
58 InsetArgumentProxy(InsetMathMacro * mathMacro, size_t idx)
59 : mathMacro_(mathMacro), idx_(idx) {}
61 InsetArgumentProxy(InsetMathMacro * mathMacro, size_t idx, docstring const & def)
62 : mathMacro_(mathMacro), idx_(idx)
67 void setBuffer(Buffer & buffer) override
69 Inset::setBuffer(buffer);
70 def_.setBuffer(buffer);
73 void setOwner(InsetMathMacro * mathMacro) { mathMacro_ = mathMacro; }
75 InsetMathMacro const * owner() { return mathMacro_; }
77 marker_type marker(BufferView const *) const override { return NO_MARKER; }
79 InsetCode lyxCode() const override { return ARGUMENT_PROXY_CODE; }
80 /// The math data to use for display
81 MathData const & displayCell(BufferView const * bv) const
83 // handle default macro arguments
84 bool use_def_arg = !mathMacro_->editMetrics(bv)
85 && mathMacro_->cell(idx_).empty();
86 return use_def_arg ? def_ : mathMacro_->cell(idx_);
89 bool addToMathRow(MathRow & mrow, MetricsInfo & mi) const override
91 // macro arguments are in macros
92 LATTEST(mathMacro_->nesting() > 0);
93 /// The macro nesting can change display of insets. Change it locally.
94 Changer chg = changeVar(mi.base.macro_nesting,
95 mathMacro_->nesting() == 1 ? 0 : mathMacro_->nesting());
97 MathRow::Element e_beg(mi, MathRow::BEGIN);
99 e_beg.ar = &mathMacro_->cell(idx_);
100 mrow.push_back(e_beg);
102 mathMacro_->macro()->unlock();
103 bool has_contents = displayCell(mi.base.bv).addToMathRow(mrow, mi);
104 mathMacro_->macro()->lock();
106 // if there was no contents, and the contents is editable,
107 // then we insert a box instead.
108 if (!has_contents && mathMacro_->nesting() == 1) {
109 // mathclass is ord because it should be spaced as a normal atom
110 MathRow::Element e(mi, MathRow::BOX, MC_ORD);
111 e.color = Color_mathline;
116 MathRow::Element e_end(mi, MathRow::END);
118 e_end.ar = &mathMacro_->cell(idx_);
119 mrow.push_back(e_end);
124 void beforeMetrics() const override
126 mathMacro_->macro()->unlock();
129 void afterMetrics() const override
131 mathMacro_->macro()->lock();
134 void beforeDraw(PainterInfo const & pi) const override
136 // if the macro is being edited, then the painter is in
138 if (mathMacro_->editMetrics(pi.base.bv))
139 pi.pain.leaveMonochromeMode();
142 void afterDraw(PainterInfo const & pi) const override
144 if (mathMacro_->editMetrics(pi.base.bv))
145 pi.pain.enterMonochromeMode(Color_mathmacroblend);
148 void metrics(MetricsInfo &, Dimension &) const override {
149 // This should never be invoked, since InsetArgumentProxy insets are linearized
153 void draw(PainterInfo &, int, int) const override {
154 // This should never be invoked, since InsetArgumentProxy insets are linearized
158 int kerning(BufferView const * bv) const override
160 return displayCell(bv).kerning(bv);
162 // write(), normalize(), infoize() and infoize2() are not needed since
163 // InsetMathMacro uses the definition and not the expanded cells.
165 void maple(MapleStream & ms) const override { ms << mathMacro_->cell(idx_); }
167 void maxima(MaximaStream & ms) const override { ms << mathMacro_->cell(idx_); }
169 void mathematica(MathematicaStream & ms) const override { ms << mathMacro_->cell(idx_); }
171 void mathmlize(MathStream & ms) const override { ms << mathMacro_->cell(idx_); }
173 void htmlize(HtmlStream & ms) const override { ms << mathMacro_->cell(idx_); }
175 void octave(OctaveStream & os) const override { os << mathMacro_->cell(idx_); }
177 MathClass mathClass() const override
180 // This can be refined once the pointer issues are fixed. I did not
181 // notice any immediate crash with the following code, but it is risky
183 //return mathMacro_->cell(idx_).mathClass();
188 Inset * clone() const override
190 return new InsetArgumentProxy(*this);
193 InsetMathMacro * mathMacro_;
201 /// Private implementation of InsetMathMacro
202 class InsetMathMacro::Private {
204 Private(Buffer * buf, docstring const & name)
205 : name_(name), displayMode_(DISPLAY_INIT),
206 expanded_(buf), definition_(buf), attachedArgsNum_(0),
207 optionals_(0), nextFoldMode_(true), macroBackup_(buf),
208 macro_(nullptr), needsUpdate_(false), isUpdating_(false),
209 appetite_(9), nesting_(0), limits_(AUTO_LIMITS)
212 /// Update the pointers to our owner of all expanded macros.
213 /// This needs to be called every time a copy of the owner is created
215 void updateChildren(InsetMathMacro * owner);
216 /// Recursively update the pointers of all expanded macros
217 /// appearing in the arguments of the current macro
218 void updateNestedChildren(InsetMathMacro * owner, InsetMathNest * ni);
221 /// current display mode
222 DisplayMode displayMode_;
223 /// expanded macro with ArgumentProxies
225 /// macro definition with #1,#2,.. insets
226 MathData definition_;
227 /// number of arguments that were really attached
228 size_t attachedArgsNum_;
229 /// optional argument attached? (only in DISPLAY_NORMAL mode)
231 /// fold mode to be set in next metrics call?
233 /// if macro_ == true, then here is a copy of the macro
234 /// don't use it for locking
235 MacroData macroBackup_;
236 /// if macroNotFound_ == false, then here is a reference to the macro
237 /// this might invalidate after metrics was called
238 MacroData const * macro_;
240 mutable std::map<BufferView const *, bool> editing_;
242 std::string required_;
243 /// update macro representation
247 /// maximal number of arguments the macro is greedy for
249 /// Level of nesting in macros (including this one)
256 void InsetMathMacro::Private::updateChildren(InsetMathMacro * owner)
258 for (size_t i = 0; i < expanded_.size(); ++i) {
259 InsetArgumentProxy * p = dynamic_cast<InsetArgumentProxy *>(expanded_[i].nucleus());
263 InsetMathNest * ni = expanded_[i].nucleus()->asNestInset();
265 updateNestedChildren(owner, ni);
269 // The macro_ pointer is updated when MathData::metrics() is
270 // called. However, when instant preview is on or the macro is
271 // not on screen, MathData::metrics() is not called and we may
272 // have a dangling pointer. As a safety measure, when a macro
273 // is copied, always let macro_ point to the backup copy of the
274 // MacroData structure. This backup is updated every time the
275 // macro is changed, so it will not become stale.
276 macro_ = ¯oBackup_;
281 void InsetMathMacro::Private::updateNestedChildren(InsetMathMacro * owner, InsetMathNest * ni)
283 for (size_t i = 0; i < ni->nargs(); ++i) {
284 MathData & ar = ni->cell(i);
285 for (size_t j = 0; j < ar.size(); ++j) {
286 InsetArgumentProxy * ap = dynamic_cast
287 <InsetArgumentProxy *>(ar[j].nucleus());
289 InsetMathMacro::Private * md = ap->owner()->d;
291 md->macro_ = &md->macroBackup_;
294 InsetMathNest * imn = ar[j].nucleus()->asNestInset();
296 updateNestedChildren(owner, imn);
302 InsetMathMacro::InsetMathMacro(Buffer * buf, docstring const & name)
303 : InsetMathNest(buf, 0), d(new Private(buf, name))
307 InsetMathMacro::InsetMathMacro(InsetMathMacro const & that)
308 : InsetMathNest(that), d(new Private(*that.d))
310 // FIXME This should not really be necessary, but when we are
311 // initializing the table of global macros, we create macros
312 // with no associated Buffer.
314 setBuffer(*that.buffer_);
315 d->updateChildren(this);
319 InsetMathMacro & InsetMathMacro::operator=(InsetMathMacro const & that)
323 InsetMathNest::operator=(that);
325 d->updateChildren(this);
330 InsetMathMacro::~InsetMathMacro()
336 bool InsetMathMacro::addToMathRow(MathRow & mrow, MetricsInfo & mi) const
338 // set edit mode for which we will have calculated row.
339 // This is the same as what is done in metrics().
340 d->editing_[mi.base.bv] = editMode(mi.base.bv);
342 // For now we do not linearize in the following cases (can be improved)
343 // - display mode different from normal
344 // - editing with parameter list
345 // - editing with box around macro
346 if (displayMode() != InsetMathMacro::DISPLAY_NORMAL
347 || (d->editing_[mi.base.bv] && lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST))
348 return InsetMath::addToMathRow(mrow, mi);
350 /// The macro nesting can change display of insets. Change it locally.
351 Changer chg = changeVar(mi.base.macro_nesting, d->nesting_);
353 MathRow::Element e_beg(mi, MathRow::BEGIN);
355 e_beg.marker = (d->nesting_ == 1) ? marker(mi.base.bv) : NO_MARKER;
356 mrow.push_back(e_beg);
359 bool has_contents = d->expanded_.addToMathRow(mrow, mi);
362 // if there was no contents and the array is editable, then we
363 // insert a grey box instead.
364 if (!has_contents && mi.base.macro_nesting == 1) {
365 // mathclass is unknown because it is irrelevant for spacing
366 MathRow::Element e(mi, MathRow::BOX);
367 e.color = Color_mathmacroblend;
372 MathRow::Element e_end(mi, MathRow::END);
374 e_end.marker = (d->nesting_ == 1) ? marker(mi.base.bv) : NO_MARKER;
375 mrow.push_back(e_end);
381 /// Whether the inset allows \(no)limits
382 bool InsetMathMacro::allowsLimitsChange() const
384 // similar to the code in mathClass(), except that we search for
385 // the right-side class.
386 MathClass mc = MC_UNKNOWN;
387 if (MacroData const * m = macroBackup()) {
388 // If it is a global macro and is defined explicitly
390 mc = string_to_class(m->symbol()->extra);
392 // Otherwise guess from the expanded macro
393 if (mc == MC_UNKNOWN)
394 mc = d->expanded_.lastMathClass();
400 Limits InsetMathMacro::defaultLimits() const
402 if (d->expanded_.empty())
404 // Guess from the expanded macro
405 InsetMath const * in = d->expanded_.back().nucleus();
406 Limits const lim = in->limits() == AUTO_LIMITS
407 ? in->defaultLimits() : in->limits();
408 LATTEST(lim != AUTO_LIMITS);
413 Limits InsetMathMacro::limits() const
419 void InsetMathMacro::limits(Limits lim)
425 void InsetMathMacro::beforeMetrics() const
431 void InsetMathMacro::afterMetrics() const
437 void InsetMathMacro::beforeDraw(PainterInfo const & pi) const
439 if (d->editing_[pi.base.bv])
440 pi.pain.enterMonochromeMode(Color_mathmacroblend);
444 void InsetMathMacro::afterDraw(PainterInfo const & pi) const
446 if (d->editing_[pi.base.bv])
447 pi.pain.leaveMonochromeMode();
451 Inset * InsetMathMacro::clone() const
453 InsetMathMacro * copy = new InsetMathMacro(*this);
454 copy->d->needsUpdate_ = true;
455 //copy->d->expanded_.clear();
460 void InsetMathMacro::normalize(NormalStream & os) const
462 os << "[macro " << name();
463 for (size_t i = 0; i < nargs(); ++i)
464 os << ' ' << cell(i);
469 InsetMathMacro::DisplayMode InsetMathMacro::displayMode() const
471 return d->displayMode_;
475 bool InsetMathMacro::extraBraces() const
477 return d->displayMode_ == DISPLAY_NORMAL && arity() > 0;
481 docstring InsetMathMacro::name() const
483 if (d->displayMode_ == DISPLAY_UNFOLDED)
484 return asString(cell(0));
490 docstring InsetMathMacro::macroName() const
496 int InsetMathMacro::nesting() const
502 void InsetMathMacro::cursorPos(BufferView const & bv,
503 CursorSlice const & sl, bool boundary, int & x, int & y) const
505 // We may have 0 arguments, but InsetMathNest requires at least one.
507 InsetMathNest::cursorPos(bv, sl, boundary, x, y);
511 bool InsetMathMacro::editMode(BufferView const * bv) const {
512 // find this in cursor trace
513 Cursor const & cur = bv->cursor();
514 for (size_t i = 0; i != cur.depth(); ++i)
515 if (&cur[i].inset() == this) {
516 // look if there is no other macro in edit mode above
518 for (; i != cur.depth(); ++i) {
519 InsetMath * im = cur[i].asInsetMath();
521 InsetMathMacro const * macro = im->asMacro();
522 if (macro && macro->displayMode() == DISPLAY_NORMAL)
527 // ok, none found, I am the highest one
535 MacroData const * InsetMathMacro::macro() const
541 bool InsetMathMacro::editMetrics(BufferView const * bv) const
543 return d->editing_[bv];
547 InsetMath::marker_type InsetMathMacro::marker(BufferView const * bv) const
552 switch (d->displayMode_) {
554 case DISPLAY_INTERACTIVE_INIT:
556 case DISPLAY_UNFOLDED:
559 switch (lyxrc.macro_edit_style) {
560 case LyXRC::MACRO_EDIT_INLINE:
562 case LyXRC::MACRO_EDIT_INLINE_BOX:
563 return d->editing_[bv] ? BOX_MARKER : MARKER2;
564 case LyXRC::MACRO_EDIT_LIST:
573 void InsetMathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
575 /// The macro nesting can change display of insets. Change it locally.
576 Changer chg = changeVar(mi.base.macro_nesting, d->nesting_);
578 // set edit mode for which we will have calculated metrics. But only
579 d->editing_[mi.base.bv] = editMode(mi.base.bv);
581 // calculate new metrics according to display mode
582 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
583 Changer dummy = mi.base.changeFontSet("lyxtex");
584 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
585 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
586 Changer dummy = mi.base.changeFontSet("lyxtex");
587 cell(0).metrics(mi, dim);
589 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
590 dim.wid += bsdim.width() + 1;
591 dim.asc = max(bsdim.ascent(), dim.ascent());
592 dim.des = max(bsdim.descent(), dim.descent());
593 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
594 && d->editing_[mi.base.bv]) {
595 // Macro will be edited in a old-style list mode here:
599 FontInfo labelFont = sane_font;
600 math_font_max_dim(labelFont, fontDim.asc, fontDim.des);
602 // get dimension of components of list view
604 nameDim.wid = mathed_string_width(mi.base.font, from_ascii("Macro \\") + name() + ": ");
605 nameDim.asc = fontDim.asc;
606 nameDim.des = fontDim.des;
609 argDim.wid = mathed_string_width(labelFont, from_ascii("#9: "));
610 argDim.asc = fontDim.asc;
611 argDim.des = fontDim.des;
614 d->definition_.metrics(mi, defDim);
617 dim.wid = nameDim.wid + defDim.wid;
618 dim.asc = max(nameDim.asc, defDim.asc);
619 dim.des = max(nameDim.des, defDim.des);
621 for (idx_type i = 0; i < nargs(); ++i) {
623 cell(i).metrics(mi, cdim);
624 dim.des += max(argDim.height(), cdim.height()) + 1;
625 dim.wid = max(dim.wid, argDim.wid + cdim.wid);
628 // make space for box and markers, 2 pixels
633 // We should not be here, since the macro is linearized in this case.
639 int InsetMathMacro::kerning(BufferView const * bv) const {
640 if (d->displayMode_ == DISPLAY_NORMAL && !d->editing_[bv])
641 return d->expanded_.kerning(bv);
647 void InsetMathMacro::updateMacro(MacroContext const & mc)
650 d->macro_ = mc.get(name());
651 if (d->macro_ && d->macroBackup_ != *d->macro_) {
652 d->macroBackup_ = *d->macro_;
653 d->needsUpdate_ = true;
661 class InsetMathMacro::UpdateLocker
664 explicit UpdateLocker(InsetMathMacro & mm) : mac(mm)
666 mac.d->isUpdating_ = true;
668 ~UpdateLocker() { mac.d->isUpdating_ = false; }
670 InsetMathMacro & mac;
672 /** Avoid wrong usage of UpdateLocker.
673 To avoid wrong usage:
674 UpdateLocker(...); // wrong
675 UpdateLocker locker(...); // right
677 #define UpdateLocker(x) unnamed_UpdateLocker;
678 // Tip gotten from Bobby Schmidt's column in C/C++ Users Journal
681 void InsetMathMacro::updateRepresentation(Cursor * cur, MacroContext const & mc,
682 UpdateType utype, int nesting)
684 // block recursive calls (bug 8999)
688 UpdateLocker locker(*this);
691 if (d->macro_ == nullptr)
694 // remember nesting level of this macro
695 d->nesting_ = nesting;
698 d->required_ = d->macro_->required();
701 // non-normal mode? We are done!
702 || (d->displayMode_ != DISPLAY_NORMAL))
705 d->needsUpdate_ = false;
707 // get default values of macro
708 vector<docstring> const & defaults = d->macro_->defaults();
710 // create MathMacroArgumentValue objects pointing to the cells of the macro
711 vector<MathData> values(nargs());
712 for (size_t i = 0; i < nargs(); ++i) {
713 InsetArgumentProxy * proxy;
714 if (i < defaults.size())
715 proxy = new InsetArgumentProxy(this, i, defaults[i]);
717 proxy = new InsetArgumentProxy(this, i);
718 values[i].insert(0, MathAtom(proxy));
720 // expanding macro with the values
721 // Only update the argument macros if anything was expanded or the LyX
722 // representation part does not contain the macro itself, otherwise we
723 // would get an endless loop (bugs 9140 and 11595). UpdateLocker does
724 // not work in this case, since MacroData::expand() creates new
725 // InsetMathMacro objects, so this would be a different recursion path
726 // than the one protected by UpdateLocker.
727 docstring const & display = d->macro_->display();
728 docstring const latexname = from_ascii("\\") + macroName();
729 bool const ret = d->macro_->expand(values, d->expanded_);
730 d->expanded_.setBuffer(buffer());
731 if (ret && !support::contains(display, latexname)) {
732 if (utype == OutputUpdate && !d->expanded_.empty())
733 d->expanded_.updateMacros(cur, mc, utype, nesting);
735 // get definition for list edit mode
736 asArray(display.empty() ? d->macro_->definition() : display,
737 d->definition_, Parse::QUIET | Parse::MACRODEF);
741 void InsetMathMacro::draw(PainterInfo & pi, int x, int y) const
743 Dimension const dim = dimension(*pi.base.bv);
748 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
749 Changer dummy = pi.base.changeFontSet("lyxtex");
750 pi.pain.text(x, y, from_ascii("\\") + name(), pi.base.font);
751 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
752 Changer dummy = pi.base.changeFontSet("lyxtex");
753 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
754 x += mathed_string_width(pi.base.font, from_ascii("\\")) + 1;
755 cell(0).draw(pi, x, y);
756 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
757 && d->editing_[pi.base.bv]) {
758 // Macro will be edited in a old-style list mode here:
760 CoordCache const & coords = pi.base.bv->coordCache();
761 FontInfo const & labelFont = sane_font;
763 // box needs one pixel
766 // get maximal font height
768 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
771 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
772 pi.pain.text(x, y, label, labelFont);
773 x += mathed_string_width(labelFont, label);
776 d->definition_.draw(pi, x, y);
777 Dimension const & defDim = coords.getArrays().dim(&d->definition_);
778 y += max(fontDim.des, defDim.des);
781 docstring str = from_ascii("#9");
782 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
783 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
785 for (idx_type i = 0; i < nargs(); ++i) {
787 Dimension const & cdim = coords.getArrays().dim(&cell(i));
789 y += max(fontDim.asc, cdim.asc) + 1;
793 pi.pain.text(x, y, str, labelFont);
795 pi.pain.text(x, y, from_ascii(":"), labelFont);
799 cell(i).draw(pi, x, y);
802 y += max(fontDim.des, cdim.des);
805 pi.pain.rectangle(expx, expy - dim.asc + 1, dim.wid - 1,
806 dim.height() - 2, Color_mathmacroframe);
808 // We should not be here, since the macro is linearized in this case.
812 // edit mode changed?
813 if (d->editing_[pi.base.bv] != editMode(pi.base.bv))
814 pi.base.bv->cursor().screenUpdateFlags(Update::SinglePar);
818 void InsetMathMacro::setDisplayMode(InsetMathMacro::DisplayMode mode, int appetite)
820 if (d->displayMode_ != mode) {
821 // transfer name if changing from or to DISPLAY_UNFOLDED
822 if (mode == DISPLAY_UNFOLDED) {
824 asArray(d->name_, cell(0));
825 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
826 d->name_ = asString(cell(0));
830 d->displayMode_ = mode;
831 d->needsUpdate_ = true;
834 // the interactive init mode is non-greedy by default
836 d->appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
838 d->appetite_ = size_t(appetite);
842 InsetMathMacro::DisplayMode InsetMathMacro::computeDisplayMode() const
844 if (d->nextFoldMode_ && d->macro_ && !d->macro_->locked())
845 return DISPLAY_NORMAL;
847 return DISPLAY_UNFOLDED;
851 bool InsetMathMacro::validName() const
853 docstring n = name();
858 // converting back and force doesn't swallow anything?
861 if (asString(ma) != n)
866 for (char_type c : n) {
867 if (!(c >= 'a' && c <= 'z')
868 && !(c >= 'A' && c <= 'Z')
878 size_t InsetMathMacro::arity() const
880 if (d->displayMode_ == DISPLAY_NORMAL )
881 return cells_.size();
887 size_t InsetMathMacro::optionals() const
889 return d->optionals_;
893 void InsetMathMacro::setOptionals(int n)
895 if (n <= int(nargs()))
900 size_t InsetMathMacro::appetite() const
906 MathClass InsetMathMacro::mathClass() const
908 // This can be just a heuristic, since it is only considered for display
909 // when the macro is not linearised. Therefore it affects:
910 // * The spacing of the inset while being edited,
911 // * Intelligent splitting
912 // * Cursor word movement (Ctrl-Arrow).
913 if (MacroData const * m = macroBackup()) {
914 // If it is a global macro and is defined explicitly
916 MathClass mc = string_to_class(m->symbol()->extra);
917 if (mc != MC_UNKNOWN)
921 // Otherwise guess from the expanded macro
922 return d->expanded_.mathClass();
926 InsetMath::mode_type InsetMathMacro::currentMode() const
928 // User defined macros are always assumed to be mathmode macros.
929 // Only the global macros defined in lib/symbols may be textmode.
930 if (MacroData const * m = macroBackup()) {
931 if (m->symbol() && m->symbol()->extra == "textmode")
936 // Unknown macros are undecided.
937 return UNDECIDED_MODE;
941 MacroData const * InsetMathMacro::macroBackup() const
944 return &d->macroBackup_;
945 if (MacroData const * data = MacroTable::globalMacros().get(name()))
951 void InsetMathMacro::validate(LaTeXFeatures & features) const
953 // Immediately after a document is loaded, in some cases the MacroData
954 // of the global macros defined in the lib/symbols file may still not
955 // be known to the macro machinery because it will be set only after
956 // the first call to updateMacros(). This is not a problem unless
957 // instant preview is on for math, in which case we will be missing
958 // the corresponding requirements.
959 // In this case, we get the required info from the global macro table.
960 if (!d->required_.empty())
961 features.require(d->required_);
962 else if (!d->macro_) {
963 // Update requires for known global macros.
964 MacroData const * data = MacroTable::globalMacros().get(name());
965 if (data && !data->required().empty())
966 features.require(data->required());
969 if (name() == "binom")
970 features.require("binom");
972 // validate the cells and the definition
973 if (displayMode() == DISPLAY_NORMAL) {
974 // Don't update requirements if the macro comes from
975 // the symbols file and has not been redefined.
976 MathWordList const & words = mathedWordList();
977 MathWordList::const_iterator it = words.find(name());
979 buffer().listMacroNames(macros);
980 if (it == words.end() || it->second.inset != "macro"
981 || macros.find(name()) != macros.end()) {
982 d->definition_.validate(features);
984 InsetMathNest::validate(features);
989 void InsetMathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
991 cur.screenUpdateFlags(Update::SinglePar);
992 InsetMathNest::edit(cur, front, entry_from);
996 Inset * InsetMathMacro::editXY(Cursor & cur, int x, int y)
998 // We may have 0 arguments, but InsetMathNest requires at least one.
1000 cur.screenUpdateFlags(Update::SinglePar);
1001 return InsetMathNest::editXY(cur, x, y);
1007 void InsetMathMacro::removeArgument(pos_type pos) {
1008 if (d->displayMode_ == DISPLAY_NORMAL) {
1009 LASSERT(size_t(pos) < cells_.size(), return);
1010 cells_.erase(cells_.begin() + pos);
1011 if (size_t(pos) < d->attachedArgsNum_)
1012 --d->attachedArgsNum_;
1013 if (size_t(pos) < d->optionals_) {
1017 d->needsUpdate_ = true;
1022 void InsetMathMacro::insertArgument(pos_type pos) {
1023 if (d->displayMode_ == DISPLAY_NORMAL) {
1024 LASSERT(size_t(pos) <= cells_.size(), return);
1025 cells_.insert(cells_.begin() + pos, MathData());
1026 if (size_t(pos) < d->attachedArgsNum_)
1027 ++d->attachedArgsNum_;
1028 if (size_t(pos) < d->optionals_)
1031 d->needsUpdate_ = true;
1036 void InsetMathMacro::detachArguments(vector<MathData> & args, bool strip)
1038 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
1041 // strip off empty cells, but not more than arity-attachedArgsNum_
1044 for (i = cells_.size(); i > d->attachedArgsNum_; --i)
1045 if (!cell(i - 1).empty()) break;
1049 d->attachedArgsNum_ = 0;
1050 d->expanded_ = MathData();
1053 d->needsUpdate_ = true;
1057 void InsetMathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
1059 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
1061 d->attachedArgsNum_ = args.size();
1062 cells_.resize(arity);
1063 d->expanded_ = MathData();
1064 d->optionals_ = optionals;
1066 d->needsUpdate_ = true;
1070 bool InsetMathMacro::idxFirst(Cursor & cur) const
1072 cur.screenUpdateFlags(Update::SinglePar);
1073 return InsetMathNest::idxFirst(cur);
1077 bool InsetMathMacro::idxLast(Cursor & cur) const
1079 cur.screenUpdateFlags(Update::SinglePar);
1080 return InsetMathNest::idxLast(cur);
1084 bool InsetMathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
1086 if (d->displayMode_ == DISPLAY_UNFOLDED) {
1087 docstring const & unfolded_name = name();
1088 if (unfolded_name != d->name_) {
1089 // The macro name was changed
1090 Cursor inset_cursor = old;
1091 int macroSlice = inset_cursor.find(this);
1092 // returning true means the cursor is "now" invalid,
1094 LASSERT(macroSlice != -1, return true);
1095 inset_cursor.cutOff(macroSlice);
1096 inset_cursor.recordUndoInset();
1098 inset_cursor.cell().erase(inset_cursor.pos());
1099 inset_cursor.cell().insert(inset_cursor.pos(),
1100 createInsetMath(unfolded_name, cur.buffer()));
1102 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
1106 cur.screenUpdateFlags(Update::Force);
1107 return InsetMathNest::notifyCursorLeaves(old, cur);
1111 void InsetMathMacro::fold(Cursor & cur)
1113 if (!d->nextFoldMode_) {
1114 d->nextFoldMode_ = true;
1115 cur.screenUpdateFlags(Update::SinglePar);
1120 void InsetMathMacro::unfold(Cursor & cur)
1122 if (d->nextFoldMode_) {
1123 d->nextFoldMode_ = false;
1124 cur.screenUpdateFlags(Update::SinglePar);
1129 bool InsetMathMacro::folded() const
1131 return d->nextFoldMode_;
1135 void InsetMathMacro::write(WriteStream & os) const
1137 mode_type mode = currentMode();
1138 MathEnsurer ensurer(os, mode == MATH_MODE, true, mode == TEXT_MODE);
1141 if (d->displayMode_ != DISPLAY_NORMAL) {
1142 os << "\\" << name();
1143 if (name().size() != 1 || isAlphaASCII(name()[0]))
1144 os.pendingSpace(true);
1149 // we should be ok to continue even if this fails.
1152 // Always protect macros in a fragile environment
1156 os << "\\" << name();
1159 // Optional arguments:
1160 // First find last non-empty optional argument
1161 idx_type emptyOptFrom = 0;
1163 for (; i < cells_.size() && i < d->optionals_; ++i) {
1164 if (!cell(i).empty())
1165 emptyOptFrom = i + 1;
1168 // print out optionals
1169 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
1171 // For correctly parsing it when a document is reloaded, we
1172 // need to enclose an optional argument in braces if it starts
1173 // with a script inset with empty nucleus or ends with a
1174 // delimiter-size-modifier macro (see #10497 and #11346).
1175 // We also need to do that when the optional argument
1176 // contains macros with optionals.
1177 bool braced = false;
1178 size_type last = cell(i).size() - 1;
1179 if (!cell(i).empty() && cell(i)[last]->asUnknownInset()) {
1180 latexkeys const * l = in_word_set(cell(i)[last]->name());
1181 braced = (l && l->inset == "big");
1182 } else if (!cell(i).empty() && cell(i)[0]->asScriptInset()) {
1183 braced = cell(i)[0]->asScriptInset()->nuc().empty();
1185 for (size_type j = 0; j < cell(i).size(); ++j) {
1186 InsetMathMacro const * ma = cell(i)[j]->asMacro();
1187 if (ma && ma->optionals()) {
1194 os << "[{" << cell(i) << "}]";
1196 os << "[" << cell(i) << "]";
1199 // skip the tailing empty optionals
1202 // Print remaining arguments
1203 for (; i < cells_.size(); ++i) {
1204 if (cell(i).size() == 1
1205 && cell(i)[0].nucleus()->asCharInset()
1206 && isASCII(cell(i)[0].nucleus()->asCharInset()->getChar())) {
1211 os << "{" << cell(i) << "}";
1215 // add space if there was no argument
1217 os.pendingSpace(true);
1219 // write \(no)limits modifiers if relevant
1224 void InsetMathMacro::maple(MapleStream & os) const
1226 lyx::maple(d->expanded_, os);
1230 void InsetMathMacro::maxima(MaximaStream & os) const
1232 lyx::maxima(d->expanded_, os);
1236 void InsetMathMacro::mathematica(MathematicaStream & os) const
1238 lyx::mathematica(d->expanded_, os);
1242 void InsetMathMacro::mathmlize(MathStream & ms) const
1244 // macro_ is 0 if this is an unknown macro
1245 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1247 docstring const xmlname = (ms.xmlMode()) ? d->macro_->xmlname() : d->macro_->htmlname();
1248 if (!xmlname.empty()) {
1249 char const * type = d->macro_->MathMLtype();
1250 ms << "<" << from_ascii(ms.namespacedTag(type)) << ">"
1252 << "</" << from_ascii(ms.namespacedTag(type)) << ">";
1256 if (d->expanded_.empty()) {
1257 // this means that we do not recognize the macro
1258 throw MathExportException();
1264 void InsetMathMacro::htmlize(HtmlStream & os) const
1266 // macro_ is 0 if this is an unknown macro
1267 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1269 docstring const xmlname = d->macro_->htmlname();
1270 if (!xmlname.empty()) {
1271 os << ' ' << xmlname << ' ';
1275 if (d->expanded_.empty()) {
1276 // this means that we do not recognize the macro
1277 throw MathExportException();
1283 void InsetMathMacro::octave(OctaveStream & os) const
1285 lyx::octave(d->expanded_, os);
1289 void InsetMathMacro::infoize(odocstream & os) const
1291 os << bformat(_("Macro: %1$s"), name());
1295 void InsetMathMacro::infoize2(odocstream & os) const
1297 os << bformat(_("Macro: %1$s"), name());
1301 bool InsetMathMacro::completionSupported(Cursor const & cur) const
1303 if (displayMode() != DISPLAY_UNFOLDED)
1304 return InsetMathNest::completionSupported(cur);
1306 return lyxrc.completion_popup_math
1307 && cur.bv().cursor().pos() == int(name().size());
1311 bool InsetMathMacro::inlineCompletionSupported(Cursor const & cur) const
1313 if (displayMode() != DISPLAY_UNFOLDED)
1314 return InsetMathNest::inlineCompletionSupported(cur);
1316 return lyxrc.completion_inline_math
1317 && cur.bv().cursor().pos() == int(name().size());
1321 bool InsetMathMacro::automaticInlineCompletion() const
1323 if (displayMode() != DISPLAY_UNFOLDED)
1324 return InsetMathNest::automaticInlineCompletion();
1326 return lyxrc.completion_inline_math;
1330 bool InsetMathMacro::automaticPopupCompletion() const
1332 if (displayMode() != DISPLAY_UNFOLDED)
1333 return InsetMathNest::automaticPopupCompletion();
1335 return lyxrc.completion_popup_math;
1339 CompletionList const *
1340 InsetMathMacro::createCompletionList(Cursor const & cur) const
1342 if (displayMode() != DISPLAY_UNFOLDED)
1343 return InsetMathNest::createCompletionList(cur);
1345 return new MathCompletionList(cur.bv().cursor());
1349 docstring InsetMathMacro::completionPrefix(Cursor const & cur) const
1351 if (displayMode() != DISPLAY_UNFOLDED)
1352 return InsetMathNest::completionPrefix(cur);
1354 if (!completionSupported(cur))
1357 return "\\" + name();
1361 bool InsetMathMacro::insertCompletion(Cursor & cur, docstring const & s,
1364 if (displayMode() != DISPLAY_UNFOLDED)
1365 return InsetMathNest::insertCompletion(cur, s, finished);
1367 if (!completionSupported(cur))
1370 // append completion
1371 docstring newName = name() + s;
1372 asArray(newName, cell(0));
1373 cur.bv().cursor().pos() = name().size();
1374 cur.screenUpdateFlags(Update::SinglePar);
1378 cur.bv().cursor().pop();
1379 ++cur.bv().cursor().pos();
1380 cur.screenUpdateFlags(Update::SinglePar);
1387 void InsetMathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
1388 Dimension & dim) const
1390 if (displayMode() != DISPLAY_UNFOLDED)
1391 InsetMathNest::completionPosAndDim(cur, x, y, dim);
1393 // get inset dimensions
1394 dim = cur.bv().coordCache().insets().dim(this);
1395 // FIXME: these 3 are no accurate, but should depend on the font.
1396 // Now the popup jumps down if you enter a char with descent > 0.
1402 = cur.bv().coordCache().insets().xy(this);
1408 void InsetMathMacro::setBuffer(Buffer & buffer)
1410 d->definition_.setBuffer(buffer);
1411 InsetMathNest::setBuffer(buffer);