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_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 required_;
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 /// Whether the inset allows \(no)limits
375 bool InsetMathMacro::allowsLimitsChange() const
377 // similar to the code in mathClass(), except that we search for
378 // the right-side class.
379 MathClass mc = MC_UNKNOWN;
380 if (MacroData const * m = macroBackup()) {
381 // If it is a global macro and is defined explicitly
383 mc = string_to_class(m->symbol()->extra);
385 // Otherwise guess from the expanded macro
386 if (mc == MC_UNKNOWN)
387 mc = d->expanded_.lastMathClass();
393 Limits InsetMathMacro::defaultLimits() const
395 if (d->expanded_.empty())
397 // Guess from the expanded macro
398 InsetMath const * in = d->expanded_.back().nucleus();
399 Limits const lim = in->limits() == AUTO_LIMITS
400 ? in->defaultLimits() : in->limits();
401 LATTEST(lim != AUTO_LIMITS);
406 void InsetMathMacro::beforeMetrics() const
412 void InsetMathMacro::afterMetrics() const
418 void InsetMathMacro::beforeDraw(PainterInfo const & pi) const
420 if (d->editing_[pi.base.bv])
421 pi.pain.enterMonochromeMode(Color_mathmacroblend);
425 void InsetMathMacro::afterDraw(PainterInfo const & pi) const
427 if (d->editing_[pi.base.bv])
428 pi.pain.leaveMonochromeMode();
432 Inset * InsetMathMacro::clone() const
434 InsetMathMacro * copy = new InsetMathMacro(*this);
435 copy->d->needsUpdate_ = true;
436 //copy->d->expanded_.clear();
441 void InsetMathMacro::normalize(NormalStream & os) const
443 os << "[macro " << name();
444 for (size_t i = 0; i < nargs(); ++i)
445 os << ' ' << cell(i);
450 InsetMathMacro::DisplayMode InsetMathMacro::displayMode() const
452 return d->displayMode_;
456 bool InsetMathMacro::extraBraces() const
458 return d->displayMode_ == DISPLAY_NORMAL && arity() > 0;
462 docstring InsetMathMacro::name() const
464 if (d->displayMode_ == DISPLAY_UNFOLDED)
465 return asString(cell(0));
471 docstring InsetMathMacro::macroName() const
477 int InsetMathMacro::nesting() const
483 void InsetMathMacro::cursorPos(BufferView const & bv,
484 CursorSlice const & sl, bool boundary, int & x, int & y) const
486 // We may have 0 arguments, but InsetMathNest requires at least one.
488 InsetMathNest::cursorPos(bv, sl, boundary, x, y);
492 bool InsetMathMacro::editMode(BufferView const * bv) const {
493 // find this in cursor trace
494 Cursor const & cur = bv->cursor();
495 for (size_t i = 0; i != cur.depth(); ++i)
496 if (&cur[i].inset() == this) {
497 // look if there is no other macro in edit mode above
499 for (; i != cur.depth(); ++i) {
500 InsetMath * im = cur[i].asInsetMath();
502 InsetMathMacro const * macro = im->asMacro();
503 if (macro && macro->displayMode() == DISPLAY_NORMAL)
508 // ok, none found, I am the highest one
516 MacroData const * InsetMathMacro::macro() const
522 bool InsetMathMacro::editMetrics(BufferView const * bv) const
524 return d->editing_[bv];
528 InsetMath::marker_type InsetMathMacro::marker(BufferView const * bv) const
533 switch (d->displayMode_) {
535 case DISPLAY_INTERACTIVE_INIT:
537 case DISPLAY_UNFOLDED:
540 switch (lyxrc.macro_edit_style) {
541 case LyXRC::MACRO_EDIT_INLINE:
543 case LyXRC::MACRO_EDIT_INLINE_BOX:
544 return d->editing_[bv] ? BOX_MARKER : MARKER2;
545 case LyXRC::MACRO_EDIT_LIST:
554 void InsetMathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
556 /// The macro nesting can change display of insets. Change it locally.
557 Changer chg = make_change(mi.base.macro_nesting, d->nesting_);
559 // set edit mode for which we will have calculated metrics. But only
560 d->editing_[mi.base.bv] = editMode(mi.base.bv);
562 // calculate new metrics according to display mode
563 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
564 Changer dummy = mi.base.changeFontSet("lyxtex");
565 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
566 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
567 Changer dummy = mi.base.changeFontSet("lyxtex");
568 cell(0).metrics(mi, dim);
570 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
571 dim.wid += bsdim.width() + 1;
572 dim.asc = max(bsdim.ascent(), dim.ascent());
573 dim.des = max(bsdim.descent(), dim.descent());
574 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
575 && d->editing_[mi.base.bv]) {
576 // Macro will be edited in a old-style list mode here:
580 FontInfo labelFont = sane_font;
581 math_font_max_dim(labelFont, fontDim.asc, fontDim.des);
583 // get dimension of components of list view
585 nameDim.wid = mathed_string_width(mi.base.font, from_ascii("Macro \\") + name() + ": ");
586 nameDim.asc = fontDim.asc;
587 nameDim.des = fontDim.des;
590 argDim.wid = mathed_string_width(labelFont, from_ascii("#9: "));
591 argDim.asc = fontDim.asc;
592 argDim.des = fontDim.des;
595 d->definition_.metrics(mi, defDim);
598 dim.wid = nameDim.wid + defDim.wid;
599 dim.asc = max(nameDim.asc, defDim.asc);
600 dim.des = max(nameDim.des, defDim.des);
602 for (idx_type i = 0; i < nargs(); ++i) {
604 cell(i).metrics(mi, cdim);
605 dim.des += max(argDim.height(), cdim.height()) + 1;
606 dim.wid = max(dim.wid, argDim.wid + cdim.wid);
609 // make space for box and markers, 2 pixels
614 // We should not be here, since the macro is linearized in this case.
620 int InsetMathMacro::kerning(BufferView const * bv) const {
621 if (d->displayMode_ == DISPLAY_NORMAL && !d->editing_[bv])
622 return d->expanded_.kerning(bv);
628 void InsetMathMacro::updateMacro(MacroContext const & mc)
631 d->macro_ = mc.get(name());
632 if (d->macro_ && d->macroBackup_ != *d->macro_) {
633 d->macroBackup_ = *d->macro_;
634 d->needsUpdate_ = true;
642 class InsetMathMacro::UpdateLocker
645 explicit UpdateLocker(InsetMathMacro & mm) : mac(mm)
647 mac.d->isUpdating_ = true;
649 ~UpdateLocker() { mac.d->isUpdating_ = false; }
651 InsetMathMacro & mac;
653 /** Avoid wrong usage of UpdateLocker.
654 To avoid wrong usage:
655 UpdateLocker(...); // wrong
656 UpdateLocker locker(...); // right
658 #define UpdateLocker(x) unnamed_UpdateLocker;
659 // Tip gotten from Bobby Schmidt's column in C/C++ Users Journal
662 void InsetMathMacro::updateRepresentation(Cursor * cur, MacroContext const & mc,
663 UpdateType utype, int nesting)
665 // block recursive calls (bug 8999)
669 UpdateLocker locker(*this);
675 // remember nesting level of this macro
676 d->nesting_ = nesting;
679 d->required_ = d->macro_->required();
682 // non-normal mode? We are done!
683 || (d->displayMode_ != DISPLAY_NORMAL))
686 d->needsUpdate_ = false;
688 // get default values of macro
689 vector<docstring> const & defaults = d->macro_->defaults();
691 // create MathMacroArgumentValue objects pointing to the cells of the macro
692 vector<MathData> values(nargs());
693 for (size_t i = 0; i < nargs(); ++i) {
694 InsetArgumentProxy * proxy;
695 if (i < defaults.size())
696 proxy = new InsetArgumentProxy(this, i, defaults[i]);
698 proxy = new InsetArgumentProxy(this, i);
699 values[i].insert(0, MathAtom(proxy));
701 // expanding macro with the values
702 // Only update the argument macros if anything was expanded or the LyX
703 // representation part does not contain the macro itself, otherwise we
704 // would get an endless loop (bugs 9140 and 11595). UpdateLocker does
705 // not work in this case, since MacroData::expand() creates new
706 // InsetMathMacro objects, so this would be a different recursion path
707 // than the one protected by UpdateLocker.
708 docstring const & display = d->macro_->display();
709 docstring const latexname = from_ascii("\\") + macroName();
710 bool const ret = d->macro_->expand(values, d->expanded_);
711 d->expanded_.setBuffer(buffer());
712 if (ret && !support::contains(display, latexname)) {
713 if (utype == OutputUpdate && !d->expanded_.empty())
714 d->expanded_.updateMacros(cur, mc, utype, nesting);
716 // get definition for list edit mode
717 asArray(display.empty() ? d->macro_->definition() : display,
718 d->definition_, Parse::QUIET | Parse::MACRODEF);
722 void InsetMathMacro::draw(PainterInfo & pi, int x, int y) const
724 Dimension const dim = dimension(*pi.base.bv);
729 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
730 Changer dummy = pi.base.changeFontSet("lyxtex");
731 pi.pain.text(x, y, from_ascii("\\") + name(), pi.base.font);
732 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
733 Changer dummy = pi.base.changeFontSet("lyxtex");
734 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
735 x += mathed_string_width(pi.base.font, from_ascii("\\")) + 1;
736 cell(0).draw(pi, x, y);
737 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
738 && d->editing_[pi.base.bv]) {
739 // Macro will be edited in a old-style list mode here:
741 CoordCache const & coords = pi.base.bv->coordCache();
742 FontInfo const & labelFont = sane_font;
744 // box needs one pixel
747 // get maximal font height
749 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
752 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
753 pi.pain.text(x, y, label, labelFont);
754 x += mathed_string_width(labelFont, label);
757 d->definition_.draw(pi, x, y);
758 Dimension const & defDim = coords.getArrays().dim(&d->definition_);
759 y += max(fontDim.des, defDim.des);
762 docstring str = from_ascii("#9");
763 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
764 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
766 for (idx_type i = 0; i < nargs(); ++i) {
768 Dimension const & cdim = coords.getArrays().dim(&cell(i));
770 y += max(fontDim.asc, cdim.asc) + 1;
774 pi.pain.text(x, y, str, labelFont);
776 pi.pain.text(x, y, from_ascii(":"), labelFont);
780 cell(i).draw(pi, x, y);
783 y += max(fontDim.des, cdim.des);
786 pi.pain.rectangle(expx, expy - dim.asc + 1, dim.wid - 1,
787 dim.height() - 2, Color_mathmacroframe);
789 // We should not be here, since the macro is linearized in this case.
793 // edit mode changed?
794 if (d->editing_[pi.base.bv] != editMode(pi.base.bv))
795 pi.base.bv->cursor().screenUpdateFlags(Update::SinglePar);
799 void InsetMathMacro::setDisplayMode(InsetMathMacro::DisplayMode mode, int appetite)
801 if (d->displayMode_ != mode) {
802 // transfer name if changing from or to DISPLAY_UNFOLDED
803 if (mode == DISPLAY_UNFOLDED) {
805 asArray(d->name_, cell(0));
806 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
807 d->name_ = asString(cell(0));
811 d->displayMode_ = mode;
812 d->needsUpdate_ = true;
815 // the interactive init mode is non-greedy by default
817 d->appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
819 d->appetite_ = size_t(appetite);
823 InsetMathMacro::DisplayMode InsetMathMacro::computeDisplayMode() const
825 if (d->nextFoldMode_ == true && d->macro_ && !d->macro_->locked())
826 return DISPLAY_NORMAL;
828 return DISPLAY_UNFOLDED;
832 bool InsetMathMacro::validName() const
834 docstring n = name();
839 // converting back and force doesn't swallow anything?
842 if (asString(ma) != n)
847 for (size_t i = 0; i<n.size(); ++i) {
848 if (!(n[i] >= 'a' && n[i] <= 'z')
849 && !(n[i] >= 'A' && n[i] <= 'Z')
859 size_t InsetMathMacro::arity() const
861 if (d->displayMode_ == DISPLAY_NORMAL )
862 return cells_.size();
868 size_t InsetMathMacro::optionals() const
870 return d->optionals_;
874 void InsetMathMacro::setOptionals(int n)
876 if (n <= int(nargs()))
881 size_t InsetMathMacro::appetite() const
887 MathClass InsetMathMacro::mathClass() const
889 // This can be just a heuristic, since it is only considered for display
890 // when the macro is not linearised. Therefore it affects:
891 // * The spacing of the inset while being edited,
892 // * Intelligent splitting
893 // * Cursor word movement (Ctrl-Arrow).
894 if (MacroData const * m = macroBackup()) {
895 // If it is a global macro and is defined explicitly
897 MathClass mc = string_to_class(m->symbol()->extra);
898 if (mc != MC_UNKNOWN)
902 // Otherwise guess from the expanded macro
903 return d->expanded_.mathClass();
907 InsetMath::mode_type InsetMathMacro::currentMode() const
909 // User defined macros are always assumed to be mathmode macros.
910 // Only the global macros defined in lib/symbols may be textmode.
911 if (MacroData const * m = macroBackup()) {
912 if (m->symbol() && m->symbol()->extra == "textmode")
917 // Unknown macros are undecided.
918 return UNDECIDED_MODE;
922 MacroData const * InsetMathMacro::macroBackup() const
925 return &d->macroBackup_;
926 if (MacroData const * data = MacroTable::globalMacros().get(name()))
932 void InsetMathMacro::validate(LaTeXFeatures & features) const
934 // Immediately after a document is loaded, in some cases the MacroData
935 // of the global macros defined in the lib/symbols file may still not
936 // be known to the macro machinery because it will be set only after
937 // the first call to updateMacros(). This is not a problem unless
938 // instant preview is on for math, in which case we will be missing
939 // the corresponding requirements.
940 // In this case, we get the required info from the global macro table.
941 if (!d->required_.empty())
942 features.require(d->required_);
943 else if (!d->macro_) {
944 // Update requires for known global macros.
945 MacroData const * data = MacroTable::globalMacros().get(name());
946 if (data && !data->required().empty())
947 features.require(data->required());
950 if (name() == "binom")
951 features.require("binom");
953 // validate the cells and the definition
954 if (displayMode() == DISPLAY_NORMAL) {
955 d->definition_.validate(features);
956 InsetMathNest::validate(features);
961 void InsetMathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
963 cur.screenUpdateFlags(Update::SinglePar);
964 InsetMathNest::edit(cur, front, entry_from);
968 Inset * InsetMathMacro::editXY(Cursor & cur, int x, int y)
970 // We may have 0 arguments, but InsetMathNest requires at least one.
972 cur.screenUpdateFlags(Update::SinglePar);
973 return InsetMathNest::editXY(cur, x, y);
979 void InsetMathMacro::removeArgument(Inset::pos_type pos) {
980 if (d->displayMode_ == DISPLAY_NORMAL) {
981 LASSERT(size_t(pos) < cells_.size(), return);
982 cells_.erase(cells_.begin() + pos);
983 if (size_t(pos) < d->attachedArgsNum_)
984 --d->attachedArgsNum_;
985 if (size_t(pos) < d->optionals_) {
989 d->needsUpdate_ = true;
994 void InsetMathMacro::insertArgument(Inset::pos_type pos) {
995 if (d->displayMode_ == DISPLAY_NORMAL) {
996 LASSERT(size_t(pos) <= cells_.size(), return);
997 cells_.insert(cells_.begin() + pos, MathData());
998 if (size_t(pos) < d->attachedArgsNum_)
999 ++d->attachedArgsNum_;
1000 if (size_t(pos) < d->optionals_)
1003 d->needsUpdate_ = true;
1008 void InsetMathMacro::detachArguments(vector<MathData> & args, bool strip)
1010 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
1013 // strip off empty cells, but not more than arity-attachedArgsNum_
1016 for (i = cells_.size(); i > d->attachedArgsNum_; --i)
1017 if (!cell(i - 1).empty()) break;
1021 d->attachedArgsNum_ = 0;
1022 d->expanded_ = MathData();
1025 d->needsUpdate_ = true;
1029 void InsetMathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
1031 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
1033 d->attachedArgsNum_ = args.size();
1034 cells_.resize(arity);
1035 d->expanded_ = MathData();
1036 d->optionals_ = optionals;
1038 d->needsUpdate_ = true;
1042 bool InsetMathMacro::idxFirst(Cursor & cur) const
1044 cur.screenUpdateFlags(Update::SinglePar);
1045 return InsetMathNest::idxFirst(cur);
1049 bool InsetMathMacro::idxLast(Cursor & cur) const
1051 cur.screenUpdateFlags(Update::SinglePar);
1052 return InsetMathNest::idxLast(cur);
1056 bool InsetMathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
1058 if (d->displayMode_ == DISPLAY_UNFOLDED) {
1059 docstring const & unfolded_name = name();
1060 if (unfolded_name != d->name_) {
1061 // The macro name was changed
1062 Cursor inset_cursor = old;
1063 int macroSlice = inset_cursor.find(this);
1064 // returning true means the cursor is "now" invalid,
1066 LASSERT(macroSlice != -1, return true);
1067 inset_cursor.cutOff(macroSlice);
1068 inset_cursor.recordUndoInset();
1070 inset_cursor.cell().erase(inset_cursor.pos());
1071 inset_cursor.cell().insert(inset_cursor.pos(),
1072 createInsetMath(unfolded_name, cur.buffer()));
1074 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
1078 cur.screenUpdateFlags(Update::Force);
1079 return InsetMathNest::notifyCursorLeaves(old, cur);
1083 void InsetMathMacro::fold(Cursor & cur)
1085 if (!d->nextFoldMode_) {
1086 d->nextFoldMode_ = true;
1087 cur.screenUpdateFlags(Update::SinglePar);
1092 void InsetMathMacro::unfold(Cursor & cur)
1094 if (d->nextFoldMode_) {
1095 d->nextFoldMode_ = false;
1096 cur.screenUpdateFlags(Update::SinglePar);
1101 bool InsetMathMacro::folded() const
1103 return d->nextFoldMode_;
1107 void InsetMathMacro::write(WriteStream & os) const
1109 mode_type mode = currentMode();
1110 MathEnsurer ensurer(os, mode == MATH_MODE, true, mode == TEXT_MODE);
1113 if (d->displayMode_ != DISPLAY_NORMAL) {
1114 os << "\\" << name();
1115 if (name().size() != 1 || isAlphaASCII(name()[0]))
1116 os.pendingSpace(true);
1121 // we should be ok to continue even if this fails.
1124 // Always protect macros in a fragile environment
1128 os << "\\" << name();
1131 // Optional arguments:
1132 // First find last non-empty optional argument
1133 idx_type emptyOptFrom = 0;
1135 for (; i < cells_.size() && i < d->optionals_; ++i) {
1136 if (!cell(i).empty())
1137 emptyOptFrom = i + 1;
1140 // print out optionals
1141 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
1143 // For correctly parsing it when a document is reloaded, we
1144 // need to enclose an optional argument in braces if it starts
1145 // with a script inset with empty nucleus or ends with a
1146 // delimiter-size-modifier macro (see #10497 and #11346).
1147 // We also need to do that when the optional argument
1148 // contains macros with optionals.
1149 bool braced = false;
1150 size_type last = cell(i).size() - 1;
1151 if (cell(i).size() && cell(i)[last]->asUnknownInset()) {
1152 latexkeys const * l = in_word_set(cell(i)[last]->name());
1153 braced = (l && l->inset == "big");
1154 } else if (cell(i).size() && cell(i)[0]->asScriptInset()) {
1155 braced = cell(i)[0]->asScriptInset()->nuc().empty();
1157 for (size_type j = 0; j < cell(i).size(); ++j) {
1158 InsetMathMacro const * ma = cell(i)[j]->asMacro();
1159 if (ma && ma->optionals()) {
1166 os << "[{" << cell(i) << "}]";
1168 os << "[" << cell(i) << "]";
1171 // skip the tailing empty optionals
1174 // Print remaining arguments
1175 for (; i < cells_.size(); ++i) {
1176 if (cell(i).size() == 1
1177 && cell(i)[0].nucleus()->asCharInset()
1178 && isASCII(cell(i)[0].nucleus()->asCharInset()->getChar())) {
1183 os << "{" << cell(i) << "}";
1187 // add space if there was no argument
1189 os.pendingSpace(true);
1191 // write \(no)limits modifiers if relevant
1196 void InsetMathMacro::maple(MapleStream & os) const
1198 lyx::maple(d->expanded_, os);
1202 void InsetMathMacro::maxima(MaximaStream & os) const
1204 lyx::maxima(d->expanded_, os);
1208 void InsetMathMacro::mathematica(MathematicaStream & os) const
1210 lyx::mathematica(d->expanded_, os);
1214 void InsetMathMacro::mathmlize(MathStream & ms) const
1216 // macro_ is 0 if this is an unknown macro
1217 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1219 docstring const xmlname = (ms.xmlMode()) ? d->macro_->xmlname() : d->macro_->htmlname();
1220 if (!xmlname.empty()) {
1221 char const * type = d->macro_->MathMLtype();
1222 ms << "<" << from_ascii(ms.namespacedTag(type)) << ">"
1224 << "</" << from_ascii(ms.namespacedTag(type)) << ">";
1228 if (d->expanded_.empty()) {
1229 // this means that we do not recognize the macro
1230 throw MathExportException();
1236 void InsetMathMacro::htmlize(HtmlStream & os) const
1238 // macro_ is 0 if this is an unknown macro
1239 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1241 docstring const xmlname = d->macro_->htmlname();
1242 if (!xmlname.empty()) {
1243 os << ' ' << xmlname << ' ';
1247 if (d->expanded_.empty()) {
1248 // this means that we do not recognize the macro
1249 throw MathExportException();
1255 void InsetMathMacro::octave(OctaveStream & os) const
1257 lyx::octave(d->expanded_, os);
1261 void InsetMathMacro::infoize(odocstream & os) const
1263 os << bformat(_("Macro: %1$s"), name());
1267 void InsetMathMacro::infoize2(odocstream & os) const
1269 os << bformat(_("Macro: %1$s"), name());
1273 bool InsetMathMacro::completionSupported(Cursor const & cur) const
1275 if (displayMode() != DISPLAY_UNFOLDED)
1276 return InsetMathNest::completionSupported(cur);
1278 return lyxrc.completion_popup_math
1279 && cur.bv().cursor().pos() == int(name().size());
1283 bool InsetMathMacro::inlineCompletionSupported(Cursor const & cur) const
1285 if (displayMode() != DISPLAY_UNFOLDED)
1286 return InsetMathNest::inlineCompletionSupported(cur);
1288 return lyxrc.completion_inline_math
1289 && cur.bv().cursor().pos() == int(name().size());
1293 bool InsetMathMacro::automaticInlineCompletion() const
1295 if (displayMode() != DISPLAY_UNFOLDED)
1296 return InsetMathNest::automaticInlineCompletion();
1298 return lyxrc.completion_inline_math;
1302 bool InsetMathMacro::automaticPopupCompletion() const
1304 if (displayMode() != DISPLAY_UNFOLDED)
1305 return InsetMathNest::automaticPopupCompletion();
1307 return lyxrc.completion_popup_math;
1311 CompletionList const *
1312 InsetMathMacro::createCompletionList(Cursor const & cur) const
1314 if (displayMode() != DISPLAY_UNFOLDED)
1315 return InsetMathNest::createCompletionList(cur);
1317 return new MathCompletionList(cur.bv().cursor());
1321 docstring InsetMathMacro::completionPrefix(Cursor const & cur) const
1323 if (displayMode() != DISPLAY_UNFOLDED)
1324 return InsetMathNest::completionPrefix(cur);
1326 if (!completionSupported(cur))
1329 return "\\" + name();
1333 bool InsetMathMacro::insertCompletion(Cursor & cur, docstring const & s,
1336 if (displayMode() != DISPLAY_UNFOLDED)
1337 return InsetMathNest::insertCompletion(cur, s, finished);
1339 if (!completionSupported(cur))
1342 // append completion
1343 docstring newName = name() + s;
1344 asArray(newName, cell(0));
1345 cur.bv().cursor().pos() = name().size();
1346 cur.screenUpdateFlags(Update::SinglePar);
1350 cur.bv().cursor().pop();
1351 ++cur.bv().cursor().pos();
1352 cur.screenUpdateFlags(Update::SinglePar);
1359 void InsetMathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
1360 Dimension & dim) const
1362 if (displayMode() != DISPLAY_UNFOLDED)
1363 InsetMathNest::completionPosAndDim(cur, x, y, dim);
1365 // get inset dimensions
1366 dim = cur.bv().coordCache().insets().dim(this);
1367 // FIXME: these 3 are no accurate, but should depend on the font.
1368 // Now the popup jumps down if you enter a char with descent > 0.
1374 = cur.bv().coordCache().insets().xy(this);
1380 void InsetMathMacro::setBuffer(Buffer & buffer)
1382 d->definition_.setBuffer(buffer);
1383 InsetMathNest::setBuffer(buffer);