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/RefChanger.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 = make_change(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 setBuffer(*that.buffer_);
311 d->updateChildren(this);
315 InsetMathMacro & InsetMathMacro::operator=(InsetMathMacro const & that)
319 InsetMathNest::operator=(that);
321 d->updateChildren(this);
326 InsetMathMacro::~InsetMathMacro()
332 bool InsetMathMacro::addToMathRow(MathRow & mrow, MetricsInfo & mi) const
334 // set edit mode for which we will have calculated row.
335 // This is the same as what is done in metrics().
336 d->editing_[mi.base.bv] = editMode(mi.base.bv);
338 // For now we do not linearize in the following cases (can be improved)
339 // - display mode different from normal
340 // - editing with parameter list
341 // - editing with box around macro
342 if (displayMode() != InsetMathMacro::DISPLAY_NORMAL
343 || (d->editing_[mi.base.bv] && lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST))
344 return InsetMath::addToMathRow(mrow, mi);
346 /// The macro nesting can change display of insets. Change it locally.
347 Changer chg = make_change(mi.base.macro_nesting, d->nesting_);
349 MathRow::Element e_beg(mi, MathRow::BEGIN);
351 e_beg.marker = (d->nesting_ == 1) ? marker(mi.base.bv) : NO_MARKER;
352 mrow.push_back(e_beg);
355 bool has_contents = d->expanded_.addToMathRow(mrow, mi);
358 // if there was no contents and the array is editable, then we
359 // insert a grey box instead.
360 if (!has_contents && mi.base.macro_nesting == 1) {
361 // mathclass is unknown because it is irrelevant for spacing
362 MathRow::Element e(mi, MathRow::BOX);
363 e.color = Color_mathmacroblend;
368 MathRow::Element e_end(mi, MathRow::END);
370 e_end.marker = (d->nesting_ == 1) ? marker(mi.base.bv) : NO_MARKER;
371 mrow.push_back(e_end);
377 /// Whether the inset allows \(no)limits
378 bool InsetMathMacro::allowsLimitsChange() const
380 // similar to the code in mathClass(), except that we search for
381 // the right-side class.
382 MathClass mc = MC_UNKNOWN;
383 if (MacroData const * m = macroBackup()) {
384 // If it is a global macro and is defined explicitly
386 mc = string_to_class(m->symbol()->extra);
388 // Otherwise guess from the expanded macro
389 if (mc == MC_UNKNOWN)
390 mc = d->expanded_.lastMathClass();
396 Limits InsetMathMacro::defaultLimits() const
398 if (d->expanded_.empty())
400 // Guess from the expanded macro
401 InsetMath const * in = d->expanded_.back().nucleus();
402 Limits const lim = in->limits() == AUTO_LIMITS
403 ? in->defaultLimits() : in->limits();
404 LATTEST(lim != AUTO_LIMITS);
409 Limits InsetMathMacro::limits() const
415 void InsetMathMacro::limits(Limits lim)
421 void InsetMathMacro::beforeMetrics() const
427 void InsetMathMacro::afterMetrics() const
433 void InsetMathMacro::beforeDraw(PainterInfo const & pi) const
435 if (d->editing_[pi.base.bv])
436 pi.pain.enterMonochromeMode(Color_mathmacroblend);
440 void InsetMathMacro::afterDraw(PainterInfo const & pi) const
442 if (d->editing_[pi.base.bv])
443 pi.pain.leaveMonochromeMode();
447 Inset * InsetMathMacro::clone() const
449 InsetMathMacro * copy = new InsetMathMacro(*this);
450 copy->d->needsUpdate_ = true;
451 //copy->d->expanded_.clear();
456 void InsetMathMacro::normalize(NormalStream & os) const
458 os << "[macro " << name();
459 for (size_t i = 0; i < nargs(); ++i)
460 os << ' ' << cell(i);
465 InsetMathMacro::DisplayMode InsetMathMacro::displayMode() const
467 return d->displayMode_;
471 bool InsetMathMacro::extraBraces() const
473 return d->displayMode_ == DISPLAY_NORMAL && arity() > 0;
477 docstring InsetMathMacro::name() const
479 if (d->displayMode_ == DISPLAY_UNFOLDED)
480 return asString(cell(0));
486 docstring InsetMathMacro::macroName() const
492 int InsetMathMacro::nesting() const
498 void InsetMathMacro::cursorPos(BufferView const & bv,
499 CursorSlice const & sl, bool boundary, int & x, int & y) const
501 // We may have 0 arguments, but InsetMathNest requires at least one.
503 InsetMathNest::cursorPos(bv, sl, boundary, x, y);
507 bool InsetMathMacro::editMode(BufferView const * bv) const {
508 // find this in cursor trace
509 Cursor const & cur = bv->cursor();
510 for (size_t i = 0; i != cur.depth(); ++i)
511 if (&cur[i].inset() == this) {
512 // look if there is no other macro in edit mode above
514 for (; i != cur.depth(); ++i) {
515 InsetMath * im = cur[i].asInsetMath();
517 InsetMathMacro const * macro = im->asMacro();
518 if (macro && macro->displayMode() == DISPLAY_NORMAL)
523 // ok, none found, I am the highest one
531 MacroData const * InsetMathMacro::macro() const
537 bool InsetMathMacro::editMetrics(BufferView const * bv) const
539 return d->editing_[bv];
543 InsetMath::marker_type InsetMathMacro::marker(BufferView const * bv) const
548 switch (d->displayMode_) {
550 case DISPLAY_INTERACTIVE_INIT:
552 case DISPLAY_UNFOLDED:
555 switch (lyxrc.macro_edit_style) {
556 case LyXRC::MACRO_EDIT_INLINE:
558 case LyXRC::MACRO_EDIT_INLINE_BOX:
559 return d->editing_[bv] ? BOX_MARKER : MARKER2;
560 case LyXRC::MACRO_EDIT_LIST:
569 void InsetMathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
571 /// The macro nesting can change display of insets. Change it locally.
572 Changer chg = make_change(mi.base.macro_nesting, d->nesting_);
574 // set edit mode for which we will have calculated metrics. But only
575 d->editing_[mi.base.bv] = editMode(mi.base.bv);
577 // calculate new metrics according to display mode
578 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
579 Changer dummy = mi.base.changeFontSet("lyxtex");
580 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
581 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
582 Changer dummy = mi.base.changeFontSet("lyxtex");
583 cell(0).metrics(mi, dim);
585 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
586 dim.wid += bsdim.width() + 1;
587 dim.asc = max(bsdim.ascent(), dim.ascent());
588 dim.des = max(bsdim.descent(), dim.descent());
589 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
590 && d->editing_[mi.base.bv]) {
591 // Macro will be edited in a old-style list mode here:
595 FontInfo labelFont = sane_font;
596 math_font_max_dim(labelFont, fontDim.asc, fontDim.des);
598 // get dimension of components of list view
600 nameDim.wid = mathed_string_width(mi.base.font, from_ascii("Macro \\") + name() + ": ");
601 nameDim.asc = fontDim.asc;
602 nameDim.des = fontDim.des;
605 argDim.wid = mathed_string_width(labelFont, from_ascii("#9: "));
606 argDim.asc = fontDim.asc;
607 argDim.des = fontDim.des;
610 d->definition_.metrics(mi, defDim);
613 dim.wid = nameDim.wid + defDim.wid;
614 dim.asc = max(nameDim.asc, defDim.asc);
615 dim.des = max(nameDim.des, defDim.des);
617 for (idx_type i = 0; i < nargs(); ++i) {
619 cell(i).metrics(mi, cdim);
620 dim.des += max(argDim.height(), cdim.height()) + 1;
621 dim.wid = max(dim.wid, argDim.wid + cdim.wid);
624 // make space for box and markers, 2 pixels
629 // We should not be here, since the macro is linearized in this case.
635 int InsetMathMacro::kerning(BufferView const * bv) const {
636 if (d->displayMode_ == DISPLAY_NORMAL && !d->editing_[bv])
637 return d->expanded_.kerning(bv);
643 void InsetMathMacro::updateMacro(MacroContext const & mc)
646 d->macro_ = mc.get(name());
647 if (d->macro_ && d->macroBackup_ != *d->macro_) {
648 d->macroBackup_ = *d->macro_;
649 d->needsUpdate_ = true;
657 class InsetMathMacro::UpdateLocker
660 explicit UpdateLocker(InsetMathMacro & mm) : mac(mm)
662 mac.d->isUpdating_ = true;
664 ~UpdateLocker() { mac.d->isUpdating_ = false; }
666 InsetMathMacro & mac;
668 /** Avoid wrong usage of UpdateLocker.
669 To avoid wrong usage:
670 UpdateLocker(...); // wrong
671 UpdateLocker locker(...); // right
673 #define UpdateLocker(x) unnamed_UpdateLocker;
674 // Tip gotten from Bobby Schmidt's column in C/C++ Users Journal
677 void InsetMathMacro::updateRepresentation(Cursor * cur, MacroContext const & mc,
678 UpdateType utype, int nesting)
680 // block recursive calls (bug 8999)
684 UpdateLocker locker(*this);
687 if (d->macro_ == nullptr)
690 // remember nesting level of this macro
691 d->nesting_ = nesting;
694 d->required_ = d->macro_->required();
697 // non-normal mode? We are done!
698 || (d->displayMode_ != DISPLAY_NORMAL))
701 d->needsUpdate_ = false;
703 // get default values of macro
704 vector<docstring> const & defaults = d->macro_->defaults();
706 // create MathMacroArgumentValue objects pointing to the cells of the macro
707 vector<MathData> values(nargs());
708 for (size_t i = 0; i < nargs(); ++i) {
709 InsetArgumentProxy * proxy;
710 if (i < defaults.size())
711 proxy = new InsetArgumentProxy(this, i, defaults[i]);
713 proxy = new InsetArgumentProxy(this, i);
714 values[i].insert(0, MathAtom(proxy));
716 // expanding macro with the values
717 // Only update the argument macros if anything was expanded or the LyX
718 // representation part does not contain the macro itself, otherwise we
719 // would get an endless loop (bugs 9140 and 11595). UpdateLocker does
720 // not work in this case, since MacroData::expand() creates new
721 // InsetMathMacro objects, so this would be a different recursion path
722 // than the one protected by UpdateLocker.
723 docstring const & display = d->macro_->display();
724 docstring const latexname = from_ascii("\\") + macroName();
725 bool const ret = d->macro_->expand(values, d->expanded_);
726 d->expanded_.setBuffer(buffer());
727 if (ret && !support::contains(display, latexname)) {
728 if (utype == OutputUpdate && !d->expanded_.empty())
729 d->expanded_.updateMacros(cur, mc, utype, nesting);
731 // get definition for list edit mode
732 asArray(display.empty() ? d->macro_->definition() : display,
733 d->definition_, Parse::QUIET | Parse::MACRODEF);
737 void InsetMathMacro::draw(PainterInfo & pi, int x, int y) const
739 Dimension const dim = dimension(*pi.base.bv);
744 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
745 Changer dummy = pi.base.changeFontSet("lyxtex");
746 pi.pain.text(x, y, from_ascii("\\") + name(), pi.base.font);
747 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
748 Changer dummy = pi.base.changeFontSet("lyxtex");
749 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
750 x += mathed_string_width(pi.base.font, from_ascii("\\")) + 1;
751 cell(0).draw(pi, x, y);
752 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
753 && d->editing_[pi.base.bv]) {
754 // Macro will be edited in a old-style list mode here:
756 CoordCache const & coords = pi.base.bv->coordCache();
757 FontInfo const & labelFont = sane_font;
759 // box needs one pixel
762 // get maximal font height
764 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
767 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
768 pi.pain.text(x, y, label, labelFont);
769 x += mathed_string_width(labelFont, label);
772 d->definition_.draw(pi, x, y);
773 Dimension const & defDim = coords.getArrays().dim(&d->definition_);
774 y += max(fontDim.des, defDim.des);
777 docstring str = from_ascii("#9");
778 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
779 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
781 for (idx_type i = 0; i < nargs(); ++i) {
783 Dimension const & cdim = coords.getArrays().dim(&cell(i));
785 y += max(fontDim.asc, cdim.asc) + 1;
789 pi.pain.text(x, y, str, labelFont);
791 pi.pain.text(x, y, from_ascii(":"), labelFont);
795 cell(i).draw(pi, x, y);
798 y += max(fontDim.des, cdim.des);
801 pi.pain.rectangle(expx, expy - dim.asc + 1, dim.wid - 1,
802 dim.height() - 2, Color_mathmacroframe);
804 // We should not be here, since the macro is linearized in this case.
808 // edit mode changed?
809 if (d->editing_[pi.base.bv] != editMode(pi.base.bv))
810 pi.base.bv->cursor().screenUpdateFlags(Update::SinglePar);
814 void InsetMathMacro::setDisplayMode(InsetMathMacro::DisplayMode mode, int appetite)
816 if (d->displayMode_ != mode) {
817 // transfer name if changing from or to DISPLAY_UNFOLDED
818 if (mode == DISPLAY_UNFOLDED) {
820 asArray(d->name_, cell(0));
821 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
822 d->name_ = asString(cell(0));
826 d->displayMode_ = mode;
827 d->needsUpdate_ = true;
830 // the interactive init mode is non-greedy by default
832 d->appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
834 d->appetite_ = size_t(appetite);
838 InsetMathMacro::DisplayMode InsetMathMacro::computeDisplayMode() const
840 if (d->nextFoldMode_ && d->macro_ && !d->macro_->locked())
841 return DISPLAY_NORMAL;
843 return DISPLAY_UNFOLDED;
847 bool InsetMathMacro::validName() const
849 docstring n = name();
854 // converting back and force doesn't swallow anything?
857 if (asString(ma) != n)
862 for (size_t i = 0; i<n.size(); ++i) {
863 if (!(n[i] >= 'a' && n[i] <= 'z')
864 && !(n[i] >= 'A' && n[i] <= 'Z')
874 size_t InsetMathMacro::arity() const
876 if (d->displayMode_ == DISPLAY_NORMAL )
877 return cells_.size();
883 size_t InsetMathMacro::optionals() const
885 return d->optionals_;
889 void InsetMathMacro::setOptionals(int n)
891 if (n <= int(nargs()))
896 size_t InsetMathMacro::appetite() const
902 MathClass InsetMathMacro::mathClass() const
904 // This can be just a heuristic, since it is only considered for display
905 // when the macro is not linearised. Therefore it affects:
906 // * The spacing of the inset while being edited,
907 // * Intelligent splitting
908 // * Cursor word movement (Ctrl-Arrow).
909 if (MacroData const * m = macroBackup()) {
910 // If it is a global macro and is defined explicitly
912 MathClass mc = string_to_class(m->symbol()->extra);
913 if (mc != MC_UNKNOWN)
917 // Otherwise guess from the expanded macro
918 return d->expanded_.mathClass();
922 InsetMath::mode_type InsetMathMacro::currentMode() const
924 // User defined macros are always assumed to be mathmode macros.
925 // Only the global macros defined in lib/symbols may be textmode.
926 if (MacroData const * m = macroBackup()) {
927 if (m->symbol() && m->symbol()->extra == "textmode")
932 // Unknown macros are undecided.
933 return UNDECIDED_MODE;
937 MacroData const * InsetMathMacro::macroBackup() const
940 return &d->macroBackup_;
941 if (MacroData const * data = MacroTable::globalMacros().get(name()))
947 void InsetMathMacro::validate(LaTeXFeatures & features) const
949 // Immediately after a document is loaded, in some cases the MacroData
950 // of the global macros defined in the lib/symbols file may still not
951 // be known to the macro machinery because it will be set only after
952 // the first call to updateMacros(). This is not a problem unless
953 // instant preview is on for math, in which case we will be missing
954 // the corresponding requirements.
955 // In this case, we get the required info from the global macro table.
956 if (!d->required_.empty())
957 features.require(d->required_);
958 else if (!d->macro_) {
959 // Update requires for known global macros.
960 MacroData const * data = MacroTable::globalMacros().get(name());
961 if (data && !data->required().empty())
962 features.require(data->required());
965 if (name() == "binom")
966 features.require("binom");
968 // validate the cells and the definition
969 if (displayMode() == DISPLAY_NORMAL) {
970 // Don't update requirements if the macro comes from
971 // the symbols file and has not been redefined.
972 MathWordList const & words = mathedWordList();
973 MathWordList::const_iterator it = words.find(name());
975 buffer().listMacroNames(macros);
976 if (it == words.end() || it->second.inset != "macro"
977 || macros.find(name()) != macros.end()) {
978 d->definition_.validate(features);
980 InsetMathNest::validate(features);
985 void InsetMathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
987 cur.screenUpdateFlags(Update::SinglePar);
988 InsetMathNest::edit(cur, front, entry_from);
992 Inset * InsetMathMacro::editXY(Cursor & cur, int x, int y)
994 // We may have 0 arguments, but InsetMathNest requires at least one.
996 cur.screenUpdateFlags(Update::SinglePar);
997 return InsetMathNest::editXY(cur, x, y);
1003 void InsetMathMacro::removeArgument(Inset::pos_type pos) {
1004 if (d->displayMode_ == DISPLAY_NORMAL) {
1005 LASSERT(size_t(pos) < cells_.size(), return);
1006 cells_.erase(cells_.begin() + pos);
1007 if (size_t(pos) < d->attachedArgsNum_)
1008 --d->attachedArgsNum_;
1009 if (size_t(pos) < d->optionals_) {
1013 d->needsUpdate_ = true;
1018 void InsetMathMacro::insertArgument(Inset::pos_type pos) {
1019 if (d->displayMode_ == DISPLAY_NORMAL) {
1020 LASSERT(size_t(pos) <= cells_.size(), return);
1021 cells_.insert(cells_.begin() + pos, MathData());
1022 if (size_t(pos) < d->attachedArgsNum_)
1023 ++d->attachedArgsNum_;
1024 if (size_t(pos) < d->optionals_)
1027 d->needsUpdate_ = true;
1032 void InsetMathMacro::detachArguments(vector<MathData> & args, bool strip)
1034 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
1037 // strip off empty cells, but not more than arity-attachedArgsNum_
1040 for (i = cells_.size(); i > d->attachedArgsNum_; --i)
1041 if (!cell(i - 1).empty()) break;
1045 d->attachedArgsNum_ = 0;
1046 d->expanded_ = MathData();
1049 d->needsUpdate_ = true;
1053 void InsetMathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
1055 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
1057 d->attachedArgsNum_ = args.size();
1058 cells_.resize(arity);
1059 d->expanded_ = MathData();
1060 d->optionals_ = optionals;
1062 d->needsUpdate_ = true;
1066 bool InsetMathMacro::idxFirst(Cursor & cur) const
1068 cur.screenUpdateFlags(Update::SinglePar);
1069 return InsetMathNest::idxFirst(cur);
1073 bool InsetMathMacro::idxLast(Cursor & cur) const
1075 cur.screenUpdateFlags(Update::SinglePar);
1076 return InsetMathNest::idxLast(cur);
1080 bool InsetMathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
1082 if (d->displayMode_ == DISPLAY_UNFOLDED) {
1083 docstring const & unfolded_name = name();
1084 if (unfolded_name != d->name_) {
1085 // The macro name was changed
1086 Cursor inset_cursor = old;
1087 int macroSlice = inset_cursor.find(this);
1088 // returning true means the cursor is "now" invalid,
1090 LASSERT(macroSlice != -1, return true);
1091 inset_cursor.cutOff(macroSlice);
1092 inset_cursor.recordUndoInset();
1094 inset_cursor.cell().erase(inset_cursor.pos());
1095 inset_cursor.cell().insert(inset_cursor.pos(),
1096 createInsetMath(unfolded_name, cur.buffer()));
1098 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
1102 cur.screenUpdateFlags(Update::Force);
1103 return InsetMathNest::notifyCursorLeaves(old, cur);
1107 void InsetMathMacro::fold(Cursor & cur)
1109 if (!d->nextFoldMode_) {
1110 d->nextFoldMode_ = true;
1111 cur.screenUpdateFlags(Update::SinglePar);
1116 void InsetMathMacro::unfold(Cursor & cur)
1118 if (d->nextFoldMode_) {
1119 d->nextFoldMode_ = false;
1120 cur.screenUpdateFlags(Update::SinglePar);
1125 bool InsetMathMacro::folded() const
1127 return d->nextFoldMode_;
1131 void InsetMathMacro::write(WriteStream & os) const
1133 mode_type mode = currentMode();
1134 MathEnsurer ensurer(os, mode == MATH_MODE, true, mode == TEXT_MODE);
1137 if (d->displayMode_ != DISPLAY_NORMAL) {
1138 os << "\\" << name();
1139 if (name().size() != 1 || isAlphaASCII(name()[0]))
1140 os.pendingSpace(true);
1145 // we should be ok to continue even if this fails.
1148 // Always protect macros in a fragile environment
1152 os << "\\" << name();
1155 // Optional arguments:
1156 // First find last non-empty optional argument
1157 idx_type emptyOptFrom = 0;
1159 for (; i < cells_.size() && i < d->optionals_; ++i) {
1160 if (!cell(i).empty())
1161 emptyOptFrom = i + 1;
1164 // print out optionals
1165 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
1167 // For correctly parsing it when a document is reloaded, we
1168 // need to enclose an optional argument in braces if it starts
1169 // with a script inset with empty nucleus or ends with a
1170 // delimiter-size-modifier macro (see #10497 and #11346).
1171 // We also need to do that when the optional argument
1172 // contains macros with optionals.
1173 bool braced = false;
1174 size_type last = cell(i).size() - 1;
1175 if (!cell(i).empty() && cell(i)[last]->asUnknownInset()) {
1176 latexkeys const * l = in_word_set(cell(i)[last]->name());
1177 braced = (l && l->inset == "big");
1178 } else if (!cell(i).empty() && cell(i)[0]->asScriptInset()) {
1179 braced = cell(i)[0]->asScriptInset()->nuc().empty();
1181 for (size_type j = 0; j < cell(i).size(); ++j) {
1182 InsetMathMacro const * ma = cell(i)[j]->asMacro();
1183 if (ma && ma->optionals()) {
1190 os << "[{" << cell(i) << "}]";
1192 os << "[" << cell(i) << "]";
1195 // skip the tailing empty optionals
1198 // Print remaining arguments
1199 for (; i < cells_.size(); ++i) {
1200 if (cell(i).size() == 1
1201 && cell(i)[0].nucleus()->asCharInset()
1202 && isASCII(cell(i)[0].nucleus()->asCharInset()->getChar())) {
1207 os << "{" << cell(i) << "}";
1211 // add space if there was no argument
1213 os.pendingSpace(true);
1215 // write \(no)limits modifiers if relevant
1220 void InsetMathMacro::maple(MapleStream & os) const
1222 lyx::maple(d->expanded_, os);
1226 void InsetMathMacro::maxima(MaximaStream & os) const
1228 lyx::maxima(d->expanded_, os);
1232 void InsetMathMacro::mathematica(MathematicaStream & os) const
1234 lyx::mathematica(d->expanded_, os);
1238 void InsetMathMacro::mathmlize(MathStream & ms) const
1240 // macro_ is 0 if this is an unknown macro
1241 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1243 docstring const xmlname = (ms.xmlMode()) ? d->macro_->xmlname() : d->macro_->htmlname();
1244 if (!xmlname.empty()) {
1245 char const * type = d->macro_->MathMLtype();
1246 ms << "<" << from_ascii(ms.namespacedTag(type)) << ">"
1248 << "</" << from_ascii(ms.namespacedTag(type)) << ">";
1252 if (d->expanded_.empty()) {
1253 // this means that we do not recognize the macro
1254 throw MathExportException();
1260 void InsetMathMacro::htmlize(HtmlStream & os) const
1262 // macro_ is 0 if this is an unknown macro
1263 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1265 docstring const xmlname = d->macro_->htmlname();
1266 if (!xmlname.empty()) {
1267 os << ' ' << xmlname << ' ';
1271 if (d->expanded_.empty()) {
1272 // this means that we do not recognize the macro
1273 throw MathExportException();
1279 void InsetMathMacro::octave(OctaveStream & os) const
1281 lyx::octave(d->expanded_, os);
1285 void InsetMathMacro::infoize(odocstream & os) const
1287 os << bformat(_("Macro: %1$s"), name());
1291 void InsetMathMacro::infoize2(odocstream & os) const
1293 os << bformat(_("Macro: %1$s"), name());
1297 bool InsetMathMacro::completionSupported(Cursor const & cur) const
1299 if (displayMode() != DISPLAY_UNFOLDED)
1300 return InsetMathNest::completionSupported(cur);
1302 return lyxrc.completion_popup_math
1303 && cur.bv().cursor().pos() == int(name().size());
1307 bool InsetMathMacro::inlineCompletionSupported(Cursor const & cur) const
1309 if (displayMode() != DISPLAY_UNFOLDED)
1310 return InsetMathNest::inlineCompletionSupported(cur);
1312 return lyxrc.completion_inline_math
1313 && cur.bv().cursor().pos() == int(name().size());
1317 bool InsetMathMacro::automaticInlineCompletion() const
1319 if (displayMode() != DISPLAY_UNFOLDED)
1320 return InsetMathNest::automaticInlineCompletion();
1322 return lyxrc.completion_inline_math;
1326 bool InsetMathMacro::automaticPopupCompletion() const
1328 if (displayMode() != DISPLAY_UNFOLDED)
1329 return InsetMathNest::automaticPopupCompletion();
1331 return lyxrc.completion_popup_math;
1335 CompletionList const *
1336 InsetMathMacro::createCompletionList(Cursor const & cur) const
1338 if (displayMode() != DISPLAY_UNFOLDED)
1339 return InsetMathNest::createCompletionList(cur);
1341 return new MathCompletionList(cur.bv().cursor());
1345 docstring InsetMathMacro::completionPrefix(Cursor const & cur) const
1347 if (displayMode() != DISPLAY_UNFOLDED)
1348 return InsetMathNest::completionPrefix(cur);
1350 if (!completionSupported(cur))
1353 return "\\" + name();
1357 bool InsetMathMacro::insertCompletion(Cursor & cur, docstring const & s,
1360 if (displayMode() != DISPLAY_UNFOLDED)
1361 return InsetMathNest::insertCompletion(cur, s, finished);
1363 if (!completionSupported(cur))
1366 // append completion
1367 docstring newName = name() + s;
1368 asArray(newName, cell(0));
1369 cur.bv().cursor().pos() = name().size();
1370 cur.screenUpdateFlags(Update::SinglePar);
1374 cur.bv().cursor().pop();
1375 ++cur.bv().cursor().pos();
1376 cur.screenUpdateFlags(Update::SinglePar);
1383 void InsetMathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
1384 Dimension & dim) const
1386 if (displayMode() != DISPLAY_UNFOLDED)
1387 InsetMathNest::completionPosAndDim(cur, x, y, dim);
1389 // get inset dimensions
1390 dim = cur.bv().coordCache().insets().dim(this);
1391 // FIXME: these 3 are no accurate, but should depend on the font.
1392 // Now the popup jumps down if you enter a char with descent > 0.
1398 = cur.bv().coordCache().insets().xy(this);
1404 void InsetMathMacro::setBuffer(Buffer & buffer)
1406 d->definition_.setBuffer(buffer);
1407 InsetMathNest::setBuffer(buffer);