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)
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 { return NO_MARKER; }
79 InsetCode lyxCode() const { 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
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
126 mathMacro_->macro()->unlock();
129 void afterMetrics() const
131 mathMacro_->macro()->lock();
134 void beforeDraw(PainterInfo const & pi) const
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
144 if (mathMacro_->editMetrics(pi.base.bv))
145 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
148 void metrics(MetricsInfo &, Dimension &) const {
149 // This should never be invoked, since InsetArgumentProxy insets are linearized
153 void draw(PainterInfo &, int, int) const {
154 // This should never be invoked, since InsetArgumentProxy insets are linearized
158 int kerning(BufferView const * bv) const
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 { ms << mathMacro_->cell(idx_); }
167 void maxima(MaximaStream & ms) const { ms << mathMacro_->cell(idx_); }
169 void mathematica(MathematicaStream & ms) const { ms << mathMacro_->cell(idx_); }
171 void mathmlize(MathStream & ms) const { ms << mathMacro_->cell(idx_); }
173 void htmlize(HtmlStream & ms) const { ms << mathMacro_->cell(idx_); }
175 void octave(OctaveStream & os) const { os << mathMacro_->cell(idx_); }
177 MathClass mathClass() const
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
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_(0), needsUpdate_(false), isUpdating_(false),
209 appetite_(9), nesting_(0)
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 requires_;
243 /// update macro representation
247 /// maximal number of arguments the macro is greedy for
249 /// Level of nesting in macros (including this one)
254 void InsetMathMacro::Private::updateChildren(InsetMathMacro * owner)
256 for (size_t i = 0; i < expanded_.size(); ++i) {
257 InsetArgumentProxy * p = dynamic_cast<InsetArgumentProxy *>(expanded_[i].nucleus());
261 InsetMathNest * ni = expanded_[i].nucleus()->asNestInset();
263 updateNestedChildren(owner, ni);
267 // The macro_ pointer is updated when MathData::metrics() is
268 // called. However, when instant preview is on or the macro is
269 // not on screen, MathData::metrics() is not called and we may
270 // have a dangling pointer. As a safety measure, when a macro
271 // is copied, always let macro_ point to the backup copy of the
272 // MacroData structure. This backup is updated every time the
273 // macro is changed, so it will not become stale.
274 macro_ = ¯oBackup_;
279 void InsetMathMacro::Private::updateNestedChildren(InsetMathMacro * owner, InsetMathNest * ni)
281 for (size_t i = 0; i < ni->nargs(); ++i) {
282 MathData & ar = ni->cell(i);
283 for (size_t j = 0; j < ar.size(); ++j) {
284 InsetArgumentProxy * ap = dynamic_cast
285 <InsetArgumentProxy *>(ar[j].nucleus());
287 InsetMathMacro::Private * md = ap->owner()->d;
289 md->macro_ = &md->macroBackup_;
292 InsetMathNest * imn = ar[j].nucleus()->asNestInset();
294 updateNestedChildren(owner, imn);
300 InsetMathMacro::InsetMathMacro(Buffer * buf, docstring const & name)
301 : InsetMathNest(buf, 0), d(new Private(buf, name))
305 InsetMathMacro::InsetMathMacro(InsetMathMacro const & that)
306 : InsetMathNest(that), d(new Private(*that.d))
308 setBuffer(*that.buffer_);
309 d->updateChildren(this);
313 InsetMathMacro & InsetMathMacro::operator=(InsetMathMacro const & that)
317 InsetMathNest::operator=(that);
319 d->updateChildren(this);
324 InsetMathMacro::~InsetMathMacro()
330 bool InsetMathMacro::addToMathRow(MathRow & mrow, MetricsInfo & mi) const
332 // set edit mode for which we will have calculated row.
333 // This is the same as what is done in metrics().
334 d->editing_[mi.base.bv] = editMode(mi.base.bv);
336 // For now we do not linearize in the following cases (can be improved)
337 // - display mode different from normal
338 // - editing with parameter list
339 // - editing with box around macro
340 if (displayMode() != InsetMathMacro::DISPLAY_NORMAL
341 || (d->editing_[mi.base.bv] && lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST))
342 return InsetMath::addToMathRow(mrow, mi);
344 /// The macro nesting can change display of insets. Change it locally.
345 Changer chg = make_change(mi.base.macro_nesting, d->nesting_);
347 MathRow::Element e_beg(mi, MathRow::BEGIN);
349 e_beg.marker = (d->nesting_ == 1) ? marker(mi.base.bv) : NO_MARKER;
350 mrow.push_back(e_beg);
353 bool has_contents = d->expanded_.addToMathRow(mrow, mi);
356 // if there was no contents and the array is editable, then we
357 // insert a grey box instead.
358 if (!has_contents && mi.base.macro_nesting == 1) {
359 // mathclass is unknown because it is irrelevant for spacing
360 MathRow::Element e(mi, MathRow::BOX);
361 e.color = Color_mathmacroblend;
366 MathRow::Element e_end(mi, MathRow::END);
368 e_end.marker = (d->nesting_ == 1) ? marker(mi.base.bv) : NO_MARKER;
369 mrow.push_back(e_end);
374 void InsetMathMacro::beforeMetrics() const
380 void InsetMathMacro::afterMetrics() const
386 void InsetMathMacro::beforeDraw(PainterInfo const & pi) const
388 if (d->editing_[pi.base.bv])
389 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
393 void InsetMathMacro::afterDraw(PainterInfo const & pi) const
395 if (d->editing_[pi.base.bv])
396 pi.pain.leaveMonochromeMode();
400 Inset * InsetMathMacro::clone() const
402 InsetMathMacro * copy = new InsetMathMacro(*this);
403 copy->d->needsUpdate_ = true;
404 //copy->d->expanded_.clear();
409 void InsetMathMacro::normalize(NormalStream & os) const
411 os << "[macro " << name();
412 for (size_t i = 0; i < nargs(); ++i)
413 os << ' ' << cell(i);
418 InsetMathMacro::DisplayMode InsetMathMacro::displayMode() const
420 return d->displayMode_;
424 bool InsetMathMacro::extraBraces() const
426 return d->displayMode_ == DISPLAY_NORMAL && arity() > 0;
430 docstring InsetMathMacro::name() const
432 if (d->displayMode_ == DISPLAY_UNFOLDED)
433 return asString(cell(0));
439 docstring InsetMathMacro::macroName() const
445 int InsetMathMacro::nesting() const
451 void InsetMathMacro::cursorPos(BufferView const & bv,
452 CursorSlice const & sl, bool boundary, int & x, int & y) const
454 // We may have 0 arguments, but InsetMathNest requires at least one.
456 InsetMathNest::cursorPos(bv, sl, boundary, x, y);
460 bool InsetMathMacro::editMode(BufferView const * bv) const {
461 // find this in cursor trace
462 Cursor const & cur = bv->cursor();
463 for (size_t i = 0; i != cur.depth(); ++i)
464 if (&cur[i].inset() == this) {
465 // look if there is no other macro in edit mode above
467 for (; i != cur.depth(); ++i) {
468 InsetMath * im = cur[i].asInsetMath();
470 InsetMathMacro const * macro = im->asMacro();
471 if (macro && macro->displayMode() == DISPLAY_NORMAL)
476 // ok, none found, I am the highest one
484 MacroData const * InsetMathMacro::macro() const
490 bool InsetMathMacro::editMetrics(BufferView const * bv) const
492 return d->editing_[bv];
496 InsetMath::marker_type InsetMathMacro::marker(BufferView const * bv) const
501 switch (d->displayMode_) {
503 case DISPLAY_INTERACTIVE_INIT:
505 case DISPLAY_UNFOLDED:
508 switch (lyxrc.macro_edit_style) {
509 case LyXRC::MACRO_EDIT_INLINE:
511 case LyXRC::MACRO_EDIT_INLINE_BOX:
512 return d->editing_[bv] ? BOX_MARKER : MARKER2;
513 case LyXRC::MACRO_EDIT_LIST:
522 void InsetMathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
524 /// The macro nesting can change display of insets. Change it locally.
525 Changer chg = make_change(mi.base.macro_nesting, d->nesting_);
527 // set edit mode for which we will have calculated metrics. But only
528 d->editing_[mi.base.bv] = editMode(mi.base.bv);
530 // calculate new metrics according to display mode
531 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
532 Changer dummy = mi.base.changeFontSet("lyxtex");
533 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
534 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
535 Changer dummy = mi.base.changeFontSet("lyxtex");
536 cell(0).metrics(mi, dim);
538 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
539 dim.wid += bsdim.width() + 1;
540 dim.asc = max(bsdim.ascent(), dim.ascent());
541 dim.des = max(bsdim.descent(), dim.descent());
542 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
543 && d->editing_[mi.base.bv]) {
544 // Macro will be edited in a old-style list mode here:
548 FontInfo labelFont = sane_font;
549 math_font_max_dim(labelFont, fontDim.asc, fontDim.des);
551 // get dimension of components of list view
553 nameDim.wid = mathed_string_width(mi.base.font, from_ascii("Macro \\") + name() + ": ");
554 nameDim.asc = fontDim.asc;
555 nameDim.des = fontDim.des;
558 argDim.wid = mathed_string_width(labelFont, from_ascii("#9: "));
559 argDim.asc = fontDim.asc;
560 argDim.des = fontDim.des;
563 d->definition_.metrics(mi, defDim);
566 dim.wid = nameDim.wid + defDim.wid;
567 dim.asc = max(nameDim.asc, defDim.asc);
568 dim.des = max(nameDim.des, defDim.des);
570 for (idx_type i = 0; i < nargs(); ++i) {
572 cell(i).metrics(mi, cdim);
573 dim.des += max(argDim.height(), cdim.height()) + 1;
574 dim.wid = max(dim.wid, argDim.wid + cdim.wid);
577 // make space for box and markers, 2 pixels
582 // We should not be here, since the macro is linearized in this case.
588 int InsetMathMacro::kerning(BufferView const * bv) const {
589 if (d->displayMode_ == DISPLAY_NORMAL && !d->editing_[bv])
590 return d->expanded_.kerning(bv);
596 void InsetMathMacro::updateMacro(MacroContext const & mc)
599 d->macro_ = mc.get(name());
600 if (d->macro_ && d->macroBackup_ != *d->macro_) {
601 d->macroBackup_ = *d->macro_;
602 d->needsUpdate_ = true;
610 class InsetMathMacro::UpdateLocker
613 explicit UpdateLocker(InsetMathMacro & mm) : mac(mm)
615 mac.d->isUpdating_ = true;
617 ~UpdateLocker() { mac.d->isUpdating_ = false; }
619 InsetMathMacro & mac;
621 /** Avoid wrong usage of UpdateLocker.
622 To avoid wrong usage:
623 UpdateLocker(...); // wrong
624 UpdateLocker locker(...); // right
626 #define UpdateLocker(x) unnamed_UpdateLocker;
627 // Tip gotten from Bobby Schmidt's column in C/C++ Users Journal
630 void InsetMathMacro::updateRepresentation(Cursor * cur, MacroContext const & mc,
631 UpdateType utype, int nesting)
633 // block recursive calls (bug 8999)
637 UpdateLocker locker(*this);
643 // remember nesting level of this macro
644 d->nesting_ = nesting;
647 d->requires_ = d->macro_->required();
650 // non-normal mode? We are done!
651 || (d->displayMode_ != DISPLAY_NORMAL))
654 d->needsUpdate_ = false;
656 // get default values of macro
657 vector<docstring> const & defaults = d->macro_->defaults();
659 // create MathMacroArgumentValue objects pointing to the cells of the macro
660 vector<MathData> values(nargs());
661 for (size_t i = 0; i < nargs(); ++i) {
662 InsetArgumentProxy * proxy;
663 if (i < defaults.size())
664 proxy = new InsetArgumentProxy(this, i, defaults[i]);
666 proxy = new InsetArgumentProxy(this, i);
667 values[i].insert(0, MathAtom(proxy));
669 // expanding macro with the values
670 // Only update the argument macros if anything was expanded or the LyX
671 // representation part does not contain the macro itself, otherwise we
672 // would get an endless loop (bugs 9140 and 11595). UpdateLocker does
673 // not work in this case, since MacroData::expand() creates new
674 // InsetMathMacro objects, so this would be a different recursion path
675 // than the one protected by UpdateLocker.
676 docstring const & display = d->macro_->display();
677 docstring const latexname = from_ascii("\\") + macroName();
678 bool const ret = d->macro_->expand(values, d->expanded_);
679 d->expanded_.setBuffer(buffer());
680 if (ret && !support::contains(display, latexname)) {
681 if (utype == OutputUpdate && !d->expanded_.empty())
682 d->expanded_.updateMacros(cur, mc, utype, nesting);
684 // get definition for list edit mode
685 asArray(display.empty() ? d->macro_->definition() : display,
686 d->definition_, Parse::QUIET | Parse::MACRODEF);
690 void InsetMathMacro::draw(PainterInfo & pi, int x, int y) const
692 Dimension const dim = dimension(*pi.base.bv);
697 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
698 Changer dummy = pi.base.changeFontSet("lyxtex");
699 pi.pain.text(x, y, from_ascii("\\") + name(), pi.base.font);
700 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
701 Changer dummy = pi.base.changeFontSet("lyxtex");
702 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
703 x += mathed_string_width(pi.base.font, from_ascii("\\")) + 1;
704 cell(0).draw(pi, x, y);
705 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
706 && d->editing_[pi.base.bv]) {
707 // Macro will be edited in a old-style list mode here:
709 CoordCache const & coords = pi.base.bv->coordCache();
710 FontInfo const & labelFont = sane_font;
712 // box needs one pixel
715 // get maximal font height
717 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
720 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
721 pi.pain.text(x, y, label, labelFont);
722 x += mathed_string_width(labelFont, label);
725 d->definition_.draw(pi, x, y);
726 Dimension const & defDim = coords.getArrays().dim(&d->definition_);
727 y += max(fontDim.des, defDim.des);
730 docstring str = from_ascii("#9");
731 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
732 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
734 for (idx_type i = 0; i < nargs(); ++i) {
736 Dimension const & cdim = coords.getArrays().dim(&cell(i));
738 y += max(fontDim.asc, cdim.asc) + 1;
742 pi.pain.text(x, y, str, labelFont);
744 pi.pain.text(x, y, from_ascii(":"), labelFont);
748 cell(i).draw(pi, x, y);
751 y += max(fontDim.des, cdim.des);
754 pi.pain.rectangle(expx, expy - dim.asc + 1, dim.wid - 1,
755 dim.height() - 2, Color_mathmacroframe);
757 // We should not be here, since the macro is linearized in this case.
761 // edit mode changed?
762 if (d->editing_[pi.base.bv] != editMode(pi.base.bv))
763 pi.base.bv->cursor().screenUpdateFlags(Update::SinglePar);
767 void InsetMathMacro::setDisplayMode(InsetMathMacro::DisplayMode mode, int appetite)
769 if (d->displayMode_ != mode) {
770 // transfer name if changing from or to DISPLAY_UNFOLDED
771 if (mode == DISPLAY_UNFOLDED) {
773 asArray(d->name_, cell(0));
774 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
775 d->name_ = asString(cell(0));
779 d->displayMode_ = mode;
780 d->needsUpdate_ = true;
783 // the interactive init mode is non-greedy by default
785 d->appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
787 d->appetite_ = size_t(appetite);
791 InsetMathMacro::DisplayMode InsetMathMacro::computeDisplayMode() const
793 if (d->nextFoldMode_ == true && d->macro_ && !d->macro_->locked())
794 return DISPLAY_NORMAL;
796 return DISPLAY_UNFOLDED;
800 bool InsetMathMacro::validName() const
802 docstring n = name();
807 // converting back and force doesn't swallow anything?
810 if (asString(ma) != n)
815 for (size_t i = 0; i<n.size(); ++i) {
816 if (!(n[i] >= 'a' && n[i] <= 'z')
817 && !(n[i] >= 'A' && n[i] <= 'Z')
827 size_t InsetMathMacro::arity() const
829 if (d->displayMode_ == DISPLAY_NORMAL )
830 return cells_.size();
836 size_t InsetMathMacro::optionals() const
838 return d->optionals_;
842 void InsetMathMacro::setOptionals(int n)
844 if (n <= int(nargs()))
849 size_t InsetMathMacro::appetite() const
855 MathClass InsetMathMacro::mathClass() const
857 // This can be just a heuristic, since it is only considered for display
858 // when the macro is not linearised. Therefore it affects:
859 // * The spacing of the inset while being edited,
860 // * Intelligent splitting
861 // * Cursor word movement (Ctrl-Arrow).
862 if (MacroData const * m = macroBackup()) {
863 // If it is a global macro and is defined explicitly
865 MathClass mc = string_to_class(m->symbol()->extra);
866 if (mc != MC_UNKNOWN)
870 // Otherwise guess from the expanded macro
871 return d->expanded_.mathClass();
875 InsetMath::mode_type InsetMathMacro::currentMode() const
877 // User defined macros are always assumed to be mathmode macros.
878 // Only the global macros defined in lib/symbols may be textmode.
879 if (MacroData const * m = macroBackup()) {
880 if (m->symbol() && m->symbol()->extra == "textmode")
885 // Unknown macros are undecided.
886 return UNDECIDED_MODE;
890 MacroData const * InsetMathMacro::macroBackup() const
893 return &d->macroBackup_;
894 if (MacroData const * data = MacroTable::globalMacros().get(name()))
900 void InsetMathMacro::validate(LaTeXFeatures & features) const
902 // Immediately after a document is loaded, in some cases the MacroData
903 // of the global macros defined in the lib/symbols file may still not
904 // be known to the macro machinery because it will be set only after
905 // the first call to updateMacros(). This is not a problem unless
906 // instant preview is on for math, in which case we will be missing
907 // the corresponding requirements.
908 // In this case, we get the required info from the global macro table.
909 if (!d->requires_.empty())
910 features.require(d->requires_);
911 else if (!d->macro_) {
912 // Update requires for known global macros.
913 MacroData const * data = MacroTable::globalMacros().get(name());
914 if (data && !data->required().empty())
915 features.require(data->required());
918 if (name() == "binom")
919 features.require("binom");
921 // validate the cells and the definition
922 if (displayMode() == DISPLAY_NORMAL) {
923 d->definition_.validate(features);
924 InsetMathNest::validate(features);
929 void InsetMathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
931 cur.screenUpdateFlags(Update::SinglePar);
932 InsetMathNest::edit(cur, front, entry_from);
936 Inset * InsetMathMacro::editXY(Cursor & cur, int x, int y)
938 // We may have 0 arguments, but InsetMathNest requires at least one.
940 cur.screenUpdateFlags(Update::SinglePar);
941 return InsetMathNest::editXY(cur, x, y);
947 void InsetMathMacro::removeArgument(Inset::pos_type pos) {
948 if (d->displayMode_ == DISPLAY_NORMAL) {
949 LASSERT(size_t(pos) < cells_.size(), return);
950 cells_.erase(cells_.begin() + pos);
951 if (size_t(pos) < d->attachedArgsNum_)
952 --d->attachedArgsNum_;
953 if (size_t(pos) < d->optionals_) {
957 d->needsUpdate_ = true;
962 void InsetMathMacro::insertArgument(Inset::pos_type pos) {
963 if (d->displayMode_ == DISPLAY_NORMAL) {
964 LASSERT(size_t(pos) <= cells_.size(), return);
965 cells_.insert(cells_.begin() + pos, MathData());
966 if (size_t(pos) < d->attachedArgsNum_)
967 ++d->attachedArgsNum_;
968 if (size_t(pos) < d->optionals_)
971 d->needsUpdate_ = true;
976 void InsetMathMacro::detachArguments(vector<MathData> & args, bool strip)
978 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
981 // strip off empty cells, but not more than arity-attachedArgsNum_
984 for (i = cells_.size(); i > d->attachedArgsNum_; --i)
985 if (!cell(i - 1).empty()) break;
989 d->attachedArgsNum_ = 0;
990 d->expanded_ = MathData();
993 d->needsUpdate_ = true;
997 void InsetMathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
999 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
1001 d->attachedArgsNum_ = args.size();
1002 cells_.resize(arity);
1003 d->expanded_ = MathData();
1004 d->optionals_ = optionals;
1006 d->needsUpdate_ = true;
1010 bool InsetMathMacro::idxFirst(Cursor & cur) const
1012 cur.screenUpdateFlags(Update::SinglePar);
1013 return InsetMathNest::idxFirst(cur);
1017 bool InsetMathMacro::idxLast(Cursor & cur) const
1019 cur.screenUpdateFlags(Update::SinglePar);
1020 return InsetMathNest::idxLast(cur);
1024 bool InsetMathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
1026 if (d->displayMode_ == DISPLAY_UNFOLDED) {
1027 docstring const & unfolded_name = name();
1028 if (unfolded_name != d->name_) {
1029 // The macro name was changed
1030 Cursor inset_cursor = old;
1031 int macroSlice = inset_cursor.find(this);
1032 // returning true means the cursor is "now" invalid,
1034 LASSERT(macroSlice != -1, return true);
1035 inset_cursor.cutOff(macroSlice);
1036 inset_cursor.recordUndoInset();
1038 inset_cursor.cell().erase(inset_cursor.pos());
1039 inset_cursor.cell().insert(inset_cursor.pos(),
1040 createInsetMath(unfolded_name, cur.buffer()));
1042 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
1046 cur.screenUpdateFlags(Update::Force);
1047 return InsetMathNest::notifyCursorLeaves(old, cur);
1051 void InsetMathMacro::fold(Cursor & cur)
1053 if (!d->nextFoldMode_) {
1054 d->nextFoldMode_ = true;
1055 cur.screenUpdateFlags(Update::SinglePar);
1060 void InsetMathMacro::unfold(Cursor & cur)
1062 if (d->nextFoldMode_) {
1063 d->nextFoldMode_ = false;
1064 cur.screenUpdateFlags(Update::SinglePar);
1069 bool InsetMathMacro::folded() const
1071 return d->nextFoldMode_;
1075 void InsetMathMacro::write(WriteStream & os) const
1077 mode_type mode = currentMode();
1078 MathEnsurer ensurer(os, mode == MATH_MODE, true, mode == TEXT_MODE);
1081 if (d->displayMode_ != DISPLAY_NORMAL) {
1082 os << "\\" << name();
1083 if (name().size() != 1 || isAlphaASCII(name()[0]))
1084 os.pendingSpace(true);
1089 // we should be ok to continue even if this fails.
1092 // Always protect macros in a fragile environment
1096 os << "\\" << name();
1099 // Optional arguments:
1100 // First find last non-empty optional argument
1101 idx_type emptyOptFrom = 0;
1103 for (; i < cells_.size() && i < d->optionals_; ++i) {
1104 if (!cell(i).empty())
1105 emptyOptFrom = i + 1;
1108 // print out optionals
1109 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
1111 // For correctly parsing it when a document is reloaded, we
1112 // need to enclose an optional argument in braces if it starts
1113 // with a script inset with empty nucleus or ends with a
1114 // delimiter-size-modifier macro (see #10497 and #11346).
1115 // We also need to do that when the optional argument
1116 // contains macros with optionals.
1117 bool braced = false;
1118 size_type last = cell(i).size() - 1;
1119 if (cell(i).size() && cell(i)[last]->asUnknownInset()) {
1120 latexkeys const * l = in_word_set(cell(i)[last]->name());
1121 braced = (l && l->inset == "big");
1122 } else if (cell(i).size() && cell(i)[0]->asScriptInset()) {
1123 braced = cell(i)[0]->asScriptInset()->nuc().empty();
1125 for (size_type j = 0; j < cell(i).size(); ++j) {
1126 InsetMathMacro const * ma = cell(i)[j]->asMacro();
1127 if (ma && ma->optionals()) {
1134 os << "[{" << cell(i) << "}]";
1136 os << "[" << cell(i) << "]";
1139 // skip the tailing empty optionals
1142 // Print remaining arguments
1143 for (; i < cells_.size(); ++i) {
1144 if (cell(i).size() == 1
1145 && cell(i)[0].nucleus()->asCharInset()
1146 && isASCII(cell(i)[0].nucleus()->asCharInset()->getChar())) {
1151 os << "{" << cell(i) << "}";
1155 // add space if there was no argument
1157 os.pendingSpace(true);
1161 void InsetMathMacro::maple(MapleStream & os) const
1163 lyx::maple(d->expanded_, os);
1167 void InsetMathMacro::maxima(MaximaStream & os) const
1169 lyx::maxima(d->expanded_, os);
1173 void InsetMathMacro::mathematica(MathematicaStream & os) const
1175 lyx::mathematica(d->expanded_, os);
1179 void InsetMathMacro::mathmlize(MathStream & os) const
1181 // macro_ is 0 if this is an unknown macro
1182 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1184 docstring const xmlname = d->macro_->xmlname();
1185 if (!xmlname.empty()) {
1186 char const * type = d->macro_->MathMLtype();
1187 os << '<' << type << "> " << xmlname << " </"
1192 if (d->expanded_.empty()) {
1193 // this means that we do not recognize the macro
1194 throw MathExportException();
1200 void InsetMathMacro::htmlize(HtmlStream & os) const
1202 // macro_ is 0 if this is an unknown macro
1203 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1205 docstring const xmlname = d->macro_->xmlname();
1206 if (!xmlname.empty()) {
1207 os << ' ' << xmlname << ' ';
1211 if (d->expanded_.empty()) {
1212 // this means that we do not recognize the macro
1213 throw MathExportException();
1219 void InsetMathMacro::octave(OctaveStream & os) const
1221 lyx::octave(d->expanded_, os);
1225 void InsetMathMacro::infoize(odocstream & os) const
1227 os << bformat(_("Macro: %1$s"), name());
1231 void InsetMathMacro::infoize2(odocstream & os) const
1233 os << bformat(_("Macro: %1$s"), name());
1237 bool InsetMathMacro::completionSupported(Cursor const & cur) const
1239 if (displayMode() != DISPLAY_UNFOLDED)
1240 return InsetMathNest::completionSupported(cur);
1242 return lyxrc.completion_popup_math
1243 && cur.bv().cursor().pos() == int(name().size());
1247 bool InsetMathMacro::inlineCompletionSupported(Cursor const & cur) const
1249 if (displayMode() != DISPLAY_UNFOLDED)
1250 return InsetMathNest::inlineCompletionSupported(cur);
1252 return lyxrc.completion_inline_math
1253 && cur.bv().cursor().pos() == int(name().size());
1257 bool InsetMathMacro::automaticInlineCompletion() const
1259 if (displayMode() != DISPLAY_UNFOLDED)
1260 return InsetMathNest::automaticInlineCompletion();
1262 return lyxrc.completion_inline_math;
1266 bool InsetMathMacro::automaticPopupCompletion() const
1268 if (displayMode() != DISPLAY_UNFOLDED)
1269 return InsetMathNest::automaticPopupCompletion();
1271 return lyxrc.completion_popup_math;
1275 CompletionList const *
1276 InsetMathMacro::createCompletionList(Cursor const & cur) const
1278 if (displayMode() != DISPLAY_UNFOLDED)
1279 return InsetMathNest::createCompletionList(cur);
1281 return new MathCompletionList(cur.bv().cursor());
1285 docstring InsetMathMacro::completionPrefix(Cursor const & cur) const
1287 if (displayMode() != DISPLAY_UNFOLDED)
1288 return InsetMathNest::completionPrefix(cur);
1290 if (!completionSupported(cur))
1293 return "\\" + name();
1297 bool InsetMathMacro::insertCompletion(Cursor & cur, docstring const & s,
1300 if (displayMode() != DISPLAY_UNFOLDED)
1301 return InsetMathNest::insertCompletion(cur, s, finished);
1303 if (!completionSupported(cur))
1306 // append completion
1307 docstring newName = name() + s;
1308 asArray(newName, cell(0));
1309 cur.bv().cursor().pos() = name().size();
1310 cur.screenUpdateFlags(Update::SinglePar);
1314 cur.bv().cursor().pop();
1315 ++cur.bv().cursor().pos();
1316 cur.screenUpdateFlags(Update::SinglePar);
1323 void InsetMathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
1324 Dimension & dim) const
1326 if (displayMode() != DISPLAY_UNFOLDED)
1327 InsetMathNest::completionPosAndDim(cur, x, y, dim);
1329 // get inset dimensions
1330 dim = cur.bv().coordCache().insets().dim(this);
1331 // FIXME: these 3 are no accurate, but should depend on the font.
1332 // Now the popup jumps down if you enter a char with descent > 0.
1338 = cur.bv().coordCache().insets().xy(this);
1344 void InsetMathMacro::setBuffer(Buffer & buffer)
1346 d->definition_.setBuffer(buffer);
1347 InsetMathNest::setBuffer(buffer);