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 setOwner(InsetMathMacro * mathMacro) { mathMacro_ = mathMacro; }
69 InsetMathMacro const * owner() { return mathMacro_; }
71 marker_type marker(BufferView const *) const { return NO_MARKER; }
73 InsetCode lyxCode() const { return ARGUMENT_PROXY_CODE; }
74 /// The math data to use for display
75 MathData const & displayCell(BufferView const * bv) const
77 // handle default macro arguments
78 bool use_def_arg = !mathMacro_->editMetrics(bv)
79 && mathMacro_->cell(idx_).empty();
80 return use_def_arg ? def_ : mathMacro_->cell(idx_);
83 bool addToMathRow(MathRow & mrow, MetricsInfo & mi) const
85 // macro arguments are in macros
86 LATTEST(mathMacro_->nesting() > 0);
87 /// The macro nesting can change display of insets. Change it locally.
88 Changer chg = make_change(mi.base.macro_nesting,
89 mathMacro_->nesting() == 1 ? 0 : mathMacro_->nesting());
91 MathRow::Element e_beg(mi, MathRow::BEGIN);
93 e_beg.ar = &mathMacro_->cell(idx_);
94 mrow.push_back(e_beg);
96 mathMacro_->macro()->unlock();
97 bool has_contents = displayCell(mi.base.bv).addToMathRow(mrow, mi);
98 mathMacro_->macro()->lock();
100 // if there was no contents, and the contents is editable,
101 // then we insert a box instead.
102 if (!has_contents && mathMacro_->nesting() == 1) {
103 // mathclass is ord because it should be spaced as a normal atom
104 MathRow::Element e(mi, MathRow::BOX, MC_ORD);
105 e.color = Color_mathline;
110 MathRow::Element e_end(mi, MathRow::END);
112 e_end.ar = &mathMacro_->cell(idx_);
113 mrow.push_back(e_end);
118 void beforeMetrics() const
120 mathMacro_->macro()->unlock();
123 void afterMetrics() const
125 mathMacro_->macro()->lock();
128 void beforeDraw(PainterInfo const & pi) const
130 // if the macro is being edited, then the painter is in
132 if (mathMacro_->editMetrics(pi.base.bv))
133 pi.pain.leaveMonochromeMode();
136 void afterDraw(PainterInfo const & pi) const
138 if (mathMacro_->editMetrics(pi.base.bv))
139 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
142 void metrics(MetricsInfo &, Dimension &) const {
143 // This should never be invoked, since InsetArgumentProxy insets are linearized
147 void draw(PainterInfo &, int, int) const {
148 // This should never be invoked, since InsetArgumentProxy insets are linearized
152 int kerning(BufferView const * bv) const
154 return displayCell(bv).kerning(bv);
156 // write(), normalize(), infoize() and infoize2() are not needed since
157 // InsetMathMacro uses the definition and not the expanded cells.
159 void maple(MapleStream & ms) const { ms << mathMacro_->cell(idx_); }
161 void maxima(MaximaStream & ms) const { ms << mathMacro_->cell(idx_); }
163 void mathematica(MathematicaStream & ms) const { ms << mathMacro_->cell(idx_); }
165 void mathmlize(MathStream & ms) const { ms << mathMacro_->cell(idx_); }
167 void htmlize(HtmlStream & ms) const { ms << mathMacro_->cell(idx_); }
169 void octave(OctaveStream & os) const { os << mathMacro_->cell(idx_); }
171 MathClass mathClass() const
174 // This can be refined once the pointer issues are fixed. I did not
175 // notice any immediate crash with the following code, but it is risky
177 //return mathMacro_->cell(idx_).mathClass();
182 Inset * clone() const
184 return new InsetArgumentProxy(*this);
187 InsetMathMacro * mathMacro_;
195 /// Private implementation of InsetMathMacro
196 class InsetMathMacro::Private {
198 Private(Buffer * buf, docstring const & name)
199 : name_(name), displayMode_(DISPLAY_INIT),
200 expanded_(buf), definition_(buf), attachedArgsNum_(0),
201 optionals_(0), nextFoldMode_(true), macroBackup_(buf),
202 macro_(0), needsUpdate_(false), isUpdating_(false),
203 appetite_(9), nesting_(0)
206 /// Update the pointers to our owner of all expanded macros.
207 /// This needs to be called every time a copy of the owner is created
209 void updateChildren(InsetMathMacro * owner);
210 /// Recursively update the pointers of all expanded macros
211 /// appearing in the arguments of the current macro
212 void updateNestedChildren(InsetMathMacro * owner, InsetMathNest * ni);
215 /// current display mode
216 DisplayMode displayMode_;
217 /// expanded macro with ArgumentProxies
219 /// macro definition with #1,#2,.. insets
220 MathData definition_;
221 /// number of arguments that were really attached
222 size_t attachedArgsNum_;
223 /// optional argument attached? (only in DISPLAY_NORMAL mode)
225 /// fold mode to be set in next metrics call?
227 /// if macro_ == true, then here is a copy of the macro
228 /// don't use it for locking
229 MacroData macroBackup_;
230 /// if macroNotFound_ == false, then here is a reference to the macro
231 /// this might invalidate after metrics was called
232 MacroData const * macro_;
234 mutable std::map<BufferView const *, bool> editing_;
236 std::string requires_;
237 /// update macro representation
241 /// maximal number of arguments the macro is greedy for
243 /// Level of nesting in macros (including this one)
248 void InsetMathMacro::Private::updateChildren(InsetMathMacro * owner)
250 for (size_t i = 0; i < expanded_.size(); ++i) {
251 InsetArgumentProxy * p = dynamic_cast<InsetArgumentProxy *>(expanded_[i].nucleus());
255 InsetMathNest * ni = expanded_[i].nucleus()->asNestInset();
257 updateNestedChildren(owner, ni);
261 // The macro_ pointer is updated when MathData::metrics() is
262 // called. However, when instant preview is on or the macro is
263 // not on screen, MathData::metrics() is not called and we may
264 // have a dangling pointer. As a safety measure, when a macro
265 // is copied, always let macro_ point to the backup copy of the
266 // MacroData structure. This backup is updated every time the
267 // macro is changed, so it will not become stale.
268 macro_ = ¯oBackup_;
273 void InsetMathMacro::Private::updateNestedChildren(InsetMathMacro * owner, InsetMathNest * ni)
275 for (size_t i = 0; i < ni->nargs(); ++i) {
276 MathData & ar = ni->cell(i);
277 for (size_t j = 0; j < ar.size(); ++j) {
278 InsetArgumentProxy * ap = dynamic_cast
279 <InsetArgumentProxy *>(ar[j].nucleus());
281 InsetMathMacro::Private * md = ap->owner()->d;
283 md->macro_ = &md->macroBackup_;
286 InsetMathNest * imn = ar[j].nucleus()->asNestInset();
288 updateNestedChildren(owner, imn);
294 InsetMathMacro::InsetMathMacro(Buffer * buf, docstring const & name)
295 : InsetMathNest(buf, 0), d(new Private(buf, name))
299 InsetMathMacro::InsetMathMacro(InsetMathMacro const & that)
300 : InsetMathNest(that), d(new Private(*that.d))
302 setBuffer(*that.buffer_);
303 d->updateChildren(this);
307 InsetMathMacro & InsetMathMacro::operator=(InsetMathMacro const & that)
311 InsetMathNest::operator=(that);
313 d->updateChildren(this);
318 InsetMathMacro::~InsetMathMacro()
324 bool InsetMathMacro::addToMathRow(MathRow & mrow, MetricsInfo & mi) const
326 // set edit mode for which we will have calculated row.
327 // This is the same as what is done in metrics().
328 d->editing_[mi.base.bv] = editMode(mi.base.bv);
330 // For now we do not linearize in the following cases (can be improved)
331 // - display mode different from normal
332 // - editing with parameter list
333 // - editing with box around macro
334 if (displayMode() != InsetMathMacro::DISPLAY_NORMAL
335 || (d->editing_[mi.base.bv] && lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST))
336 return InsetMath::addToMathRow(mrow, mi);
338 /// The macro nesting can change display of insets. Change it locally.
339 Changer chg = make_change(mi.base.macro_nesting, d->nesting_);
341 MathRow::Element e_beg(mi, MathRow::BEGIN);
343 e_beg.marker = (d->nesting_ == 1) ? marker(mi.base.bv) : NO_MARKER;
344 mrow.push_back(e_beg);
347 bool has_contents = d->expanded_.addToMathRow(mrow, mi);
350 // if there was no contents and the array is editable, then we
351 // insert a grey box instead.
352 if (!has_contents && mi.base.macro_nesting == 1) {
353 // mathclass is unknown because it is irrelevant for spacing
354 MathRow::Element e(mi, MathRow::BOX);
355 e.color = Color_mathmacroblend;
360 MathRow::Element e_end(mi, MathRow::END);
362 e_end.marker = (d->nesting_ == 1) ? marker(mi.base.bv) : NO_MARKER;
363 mrow.push_back(e_end);
368 void InsetMathMacro::beforeMetrics() const
374 void InsetMathMacro::afterMetrics() const
380 void InsetMathMacro::beforeDraw(PainterInfo const & pi) const
382 if (d->editing_[pi.base.bv])
383 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
387 void InsetMathMacro::afterDraw(PainterInfo const & pi) const
389 if (d->editing_[pi.base.bv])
390 pi.pain.leaveMonochromeMode();
394 Inset * InsetMathMacro::clone() const
396 InsetMathMacro * copy = new InsetMathMacro(*this);
397 copy->d->needsUpdate_ = true;
398 //copy->d->expanded_.clear();
403 void InsetMathMacro::normalize(NormalStream & os) const
405 os << "[macro " << name();
406 for (size_t i = 0; i < nargs(); ++i)
407 os << ' ' << cell(i);
412 InsetMathMacro::DisplayMode InsetMathMacro::displayMode() const
414 return d->displayMode_;
418 bool InsetMathMacro::extraBraces() const
420 return d->displayMode_ == DISPLAY_NORMAL && arity() > 0;
424 docstring InsetMathMacro::name() const
426 if (d->displayMode_ == DISPLAY_UNFOLDED)
427 return asString(cell(0));
433 docstring InsetMathMacro::macroName() const
439 int InsetMathMacro::nesting() const
445 void InsetMathMacro::cursorPos(BufferView const & bv,
446 CursorSlice const & sl, bool boundary, int & x, int & y) const
448 // We may have 0 arguments, but InsetMathNest requires at least one.
450 InsetMathNest::cursorPos(bv, sl, boundary, x, y);
454 bool InsetMathMacro::editMode(BufferView const * bv) const {
455 // find this in cursor trace
456 Cursor const & cur = bv->cursor();
457 for (size_t i = 0; i != cur.depth(); ++i)
458 if (&cur[i].inset() == this) {
459 // look if there is no other macro in edit mode above
461 for (; i != cur.depth(); ++i) {
462 InsetMath * im = cur[i].asInsetMath();
464 InsetMathMacro const * macro = im->asMacro();
465 if (macro && macro->displayMode() == DISPLAY_NORMAL)
470 // ok, none found, I am the highest one
478 MacroData const * InsetMathMacro::macro() const
484 bool InsetMathMacro::editMetrics(BufferView const * bv) const
486 return d->editing_[bv];
490 InsetMath::marker_type InsetMathMacro::marker(BufferView const * bv) const
495 switch (d->displayMode_) {
497 case DISPLAY_INTERACTIVE_INIT:
499 case DISPLAY_UNFOLDED:
502 switch (lyxrc.macro_edit_style) {
503 case LyXRC::MACRO_EDIT_INLINE:
505 case LyXRC::MACRO_EDIT_INLINE_BOX:
506 return d->editing_[bv] ? BOX_MARKER : MARKER2;
507 case LyXRC::MACRO_EDIT_LIST:
516 void InsetMathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
518 /// The macro nesting can change display of insets. Change it locally.
519 Changer chg = make_change(mi.base.macro_nesting, d->nesting_);
521 // set edit mode for which we will have calculated metrics. But only
522 d->editing_[mi.base.bv] = editMode(mi.base.bv);
524 // calculate new metrics according to display mode
525 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
526 Changer dummy = mi.base.changeFontSet("lyxtex");
527 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
528 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
529 Changer dummy = mi.base.changeFontSet("lyxtex");
530 cell(0).metrics(mi, dim);
532 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
533 dim.wid += bsdim.width() + 1;
534 dim.asc = max(bsdim.ascent(), dim.ascent());
535 dim.des = max(bsdim.descent(), dim.descent());
536 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
537 && d->editing_[mi.base.bv]) {
538 // Macro will be edited in a old-style list mode here:
542 FontInfo labelFont = sane_font;
543 math_font_max_dim(labelFont, fontDim.asc, fontDim.des);
545 // get dimension of components of list view
547 nameDim.wid = mathed_string_width(mi.base.font, from_ascii("Macro \\") + name() + ": ");
548 nameDim.asc = fontDim.asc;
549 nameDim.des = fontDim.des;
552 argDim.wid = mathed_string_width(labelFont, from_ascii("#9: "));
553 argDim.asc = fontDim.asc;
554 argDim.des = fontDim.des;
557 d->definition_.metrics(mi, defDim);
560 dim.wid = nameDim.wid + defDim.wid;
561 dim.asc = max(nameDim.asc, defDim.asc);
562 dim.des = max(nameDim.des, defDim.des);
564 for (idx_type i = 0; i < nargs(); ++i) {
566 cell(i).metrics(mi, cdim);
567 dim.des += max(argDim.height(), cdim.height()) + 1;
568 dim.wid = max(dim.wid, argDim.wid + cdim.wid);
571 // make space for box and markers, 2 pixels
576 // We should not be here, since the macro is linearized in this case.
582 int InsetMathMacro::kerning(BufferView const * bv) const {
583 if (d->displayMode_ == DISPLAY_NORMAL && !d->editing_[bv])
584 return d->expanded_.kerning(bv);
590 void InsetMathMacro::updateMacro(MacroContext const & mc)
593 d->macro_ = mc.get(name());
594 if (d->macro_ && d->macroBackup_ != *d->macro_) {
595 d->macroBackup_ = *d->macro_;
596 d->needsUpdate_ = true;
604 class InsetMathMacro::UpdateLocker
607 explicit UpdateLocker(InsetMathMacro & mm) : mac(mm)
609 mac.d->isUpdating_ = true;
611 ~UpdateLocker() { mac.d->isUpdating_ = false; }
613 InsetMathMacro & mac;
615 /** Avoid wrong usage of UpdateLocker.
616 To avoid wrong usage:
617 UpdateLocker(...); // wrong
618 UpdateLocker locker(...); // right
620 #define UpdateLocker(x) unnamed_UpdateLocker;
621 // Tip gotten from Bobby Schmidt's column in C/C++ Users Journal
624 void InsetMathMacro::updateRepresentation(Cursor * cur, MacroContext const & mc,
625 UpdateType utype, int nesting)
627 // block recursive calls (bug 8999)
631 UpdateLocker locker(*this);
637 // remember nesting level of this macro
638 d->nesting_ = nesting;
641 d->requires_ = d->macro_->requires();
644 // non-normal mode? We are done!
645 || (d->displayMode_ != DISPLAY_NORMAL))
648 d->needsUpdate_ = false;
650 // get default values of macro
651 vector<docstring> const & defaults = d->macro_->defaults();
653 // create MathMacroArgumentValue objects pointing to the cells of the macro
654 vector<MathData> values(nargs());
655 for (size_t i = 0; i < nargs(); ++i) {
656 InsetArgumentProxy * proxy;
657 if (i < defaults.size())
658 proxy = new InsetArgumentProxy(this, i, defaults[i]);
660 proxy = new InsetArgumentProxy(this, i);
661 values[i].insert(0, MathAtom(proxy));
663 // expanding macro with the values
664 // Only update the argument macros if anything was expanded or the LyX
665 // representation part does not contain the macro itself, otherwise we
666 // would get an endless loop (bugs 9140 and 11595). UpdateLocker does
667 // not work in this case, since MacroData::expand() creates new
668 // InsetMathMacro objects, so this would be a different recursion path
669 // than the one protected by UpdateLocker.
670 docstring const & display = d->macro_->display();
671 docstring const latexname = from_ascii("\\") + macroName();
672 bool const ret = d->macro_->expand(values, d->expanded_);
673 d->expanded_.setBuffer(buffer());
674 if (ret && !support::contains(display, latexname)) {
675 if (utype == OutputUpdate && !d->expanded_.empty())
676 d->expanded_.updateMacros(cur, mc, utype, nesting);
678 // get definition for list edit mode
679 asArray(display.empty() ? d->macro_->definition() : display,
680 d->definition_, Parse::QUIET | Parse::MACRODEF);
684 void InsetMathMacro::draw(PainterInfo & pi, int x, int y) const
686 Dimension const dim = dimension(*pi.base.bv);
691 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
692 Changer dummy = pi.base.changeFontSet("lyxtex");
693 pi.pain.text(x, y, from_ascii("\\") + name(), pi.base.font);
694 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
695 Changer dummy = pi.base.changeFontSet("lyxtex");
696 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
697 x += mathed_string_width(pi.base.font, from_ascii("\\")) + 1;
698 cell(0).draw(pi, x, y);
699 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
700 && d->editing_[pi.base.bv]) {
701 // Macro will be edited in a old-style list mode here:
703 CoordCache const & coords = pi.base.bv->coordCache();
704 FontInfo const & labelFont = sane_font;
706 // box needs one pixel
709 // get maximal font height
711 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
714 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
715 pi.pain.text(x, y, label, labelFont);
716 x += mathed_string_width(labelFont, label);
719 d->definition_.draw(pi, x, y);
720 Dimension const & defDim = coords.getArrays().dim(&d->definition_);
721 y += max(fontDim.des, defDim.des);
724 docstring str = from_ascii("#9");
725 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
726 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
728 for (idx_type i = 0; i < nargs(); ++i) {
730 Dimension const & cdim = coords.getArrays().dim(&cell(i));
732 y += max(fontDim.asc, cdim.asc) + 1;
736 pi.pain.text(x, y, str, labelFont);
738 pi.pain.text(x, y, from_ascii(":"), labelFont);
742 cell(i).draw(pi, x, y);
745 y += max(fontDim.des, cdim.des);
748 pi.pain.rectangle(expx, expy - dim.asc + 1, dim.wid - 1,
749 dim.height() - 2, Color_mathmacroframe);
751 // We should not be here, since the macro is linearized in this case.
755 // edit mode changed?
756 if (d->editing_[pi.base.bv] != editMode(pi.base.bv))
757 pi.base.bv->cursor().screenUpdateFlags(Update::SinglePar);
761 void InsetMathMacro::setDisplayMode(InsetMathMacro::DisplayMode mode, int appetite)
763 if (d->displayMode_ != mode) {
764 // transfer name if changing from or to DISPLAY_UNFOLDED
765 if (mode == DISPLAY_UNFOLDED) {
767 asArray(d->name_, cell(0));
768 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
769 d->name_ = asString(cell(0));
773 d->displayMode_ = mode;
774 d->needsUpdate_ = true;
777 // the interactive init mode is non-greedy by default
779 d->appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
781 d->appetite_ = size_t(appetite);
785 InsetMathMacro::DisplayMode InsetMathMacro::computeDisplayMode() const
787 if (d->nextFoldMode_ == true && d->macro_ && !d->macro_->locked())
788 return DISPLAY_NORMAL;
790 return DISPLAY_UNFOLDED;
794 bool InsetMathMacro::validName() const
796 docstring n = name();
801 // converting back and force doesn't swallow anything?
804 if (asString(ma) != n)
809 for (size_t i = 0; i<n.size(); ++i) {
810 if (!(n[i] >= 'a' && n[i] <= 'z')
811 && !(n[i] >= 'A' && n[i] <= 'Z')
821 size_t InsetMathMacro::arity() const
823 if (d->displayMode_ == DISPLAY_NORMAL )
824 return cells_.size();
830 size_t InsetMathMacro::optionals() const
832 return d->optionals_;
836 void InsetMathMacro::setOptionals(int n)
838 if (n <= int(nargs()))
843 size_t InsetMathMacro::appetite() const
849 MathClass InsetMathMacro::mathClass() const
851 // This can be just a heuristic, since it is only considered for display
852 // when the macro is not linearised. Therefore it affects:
853 // * The spacing of the inset while being edited,
854 // * Intelligent splitting
855 // * Cursor word movement (Ctrl-Arrow).
856 if (MacroData const * m = macroBackup()) {
857 // If it is a global macro and is defined explicitly
859 MathClass mc = string_to_class(m->symbol()->extra);
860 if (mc != MC_UNKNOWN)
864 // Otherwise guess from the expanded macro
865 return d->expanded_.mathClass();
869 InsetMath::mode_type InsetMathMacro::currentMode() const
871 // User defined macros are always assumed to be mathmode macros.
872 // Only the global macros defined in lib/symbols may be textmode.
873 if (MacroData const * m = macroBackup()) {
874 if (m->symbol() && m->symbol()->extra == "textmode")
879 // Unknown macros are undecided.
880 return UNDECIDED_MODE;
884 MacroData const * InsetMathMacro::macroBackup() const
887 return &d->macroBackup_;
888 if (MacroData const * data = MacroTable::globalMacros().get(name()))
894 void InsetMathMacro::validate(LaTeXFeatures & features) const
896 // Immediately after a document is loaded, in some cases the MacroData
897 // of the global macros defined in the lib/symbols file may still not
898 // be known to the macro machinery because it will be set only after
899 // the first call to updateMacros(). This is not a problem unless
900 // instant preview is on for math, in which case we will be missing
901 // the corresponding requirements.
902 // In this case, we get the required info from the global macro table.
903 if (!d->requires_.empty())
904 features.require(d->requires_);
905 else if (!d->macro_) {
906 // Update requires for known global macros.
907 MacroData const * data = MacroTable::globalMacros().get(name());
908 if (data && !data->requires().empty())
909 features.require(data->requires());
912 if (name() == "binom")
913 features.require("binom");
915 // validate the cells and the definition
916 if (displayMode() == DISPLAY_NORMAL) {
917 d->definition_.validate(features);
918 InsetMathNest::validate(features);
923 void InsetMathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
925 cur.screenUpdateFlags(Update::SinglePar);
926 InsetMathNest::edit(cur, front, entry_from);
930 Inset * InsetMathMacro::editXY(Cursor & cur, int x, int y)
932 // We may have 0 arguments, but InsetMathNest requires at least one.
934 cur.screenUpdateFlags(Update::SinglePar);
935 return InsetMathNest::editXY(cur, x, y);
941 void InsetMathMacro::removeArgument(Inset::pos_type pos) {
942 if (d->displayMode_ == DISPLAY_NORMAL) {
943 LASSERT(size_t(pos) < cells_.size(), return);
944 cells_.erase(cells_.begin() + pos);
945 if (size_t(pos) < d->attachedArgsNum_)
946 --d->attachedArgsNum_;
947 if (size_t(pos) < d->optionals_) {
951 d->needsUpdate_ = true;
956 void InsetMathMacro::insertArgument(Inset::pos_type pos) {
957 if (d->displayMode_ == DISPLAY_NORMAL) {
958 LASSERT(size_t(pos) <= cells_.size(), return);
959 cells_.insert(cells_.begin() + pos, MathData());
960 if (size_t(pos) < d->attachedArgsNum_)
961 ++d->attachedArgsNum_;
962 if (size_t(pos) < d->optionals_)
965 d->needsUpdate_ = true;
970 void InsetMathMacro::detachArguments(vector<MathData> & args, bool strip)
972 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
975 // strip off empty cells, but not more than arity-attachedArgsNum_
978 for (i = cells_.size(); i > d->attachedArgsNum_; --i)
979 if (!cell(i - 1).empty()) break;
983 d->attachedArgsNum_ = 0;
984 d->expanded_ = MathData();
987 d->needsUpdate_ = true;
991 void InsetMathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
993 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
995 d->attachedArgsNum_ = args.size();
996 cells_.resize(arity);
997 d->expanded_ = MathData();
998 d->optionals_ = optionals;
1000 d->needsUpdate_ = true;
1004 bool InsetMathMacro::idxFirst(Cursor & cur) const
1006 cur.screenUpdateFlags(Update::SinglePar);
1007 return InsetMathNest::idxFirst(cur);
1011 bool InsetMathMacro::idxLast(Cursor & cur) const
1013 cur.screenUpdateFlags(Update::SinglePar);
1014 return InsetMathNest::idxLast(cur);
1018 bool InsetMathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
1020 if (d->displayMode_ == DISPLAY_UNFOLDED) {
1021 docstring const & unfolded_name = name();
1022 if (unfolded_name != d->name_) {
1023 // The macro name was changed
1024 Cursor inset_cursor = old;
1025 int macroSlice = inset_cursor.find(this);
1026 // returning true means the cursor is "now" invalid,
1028 LASSERT(macroSlice != -1, return true);
1029 inset_cursor.cutOff(macroSlice);
1030 inset_cursor.recordUndoInset();
1032 inset_cursor.cell().erase(inset_cursor.pos());
1033 inset_cursor.cell().insert(inset_cursor.pos(),
1034 createInsetMath(unfolded_name, cur.buffer()));
1036 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
1040 cur.screenUpdateFlags(Update::Force);
1041 return InsetMathNest::notifyCursorLeaves(old, cur);
1045 void InsetMathMacro::fold(Cursor & cur)
1047 if (!d->nextFoldMode_) {
1048 d->nextFoldMode_ = true;
1049 cur.screenUpdateFlags(Update::SinglePar);
1054 void InsetMathMacro::unfold(Cursor & cur)
1056 if (d->nextFoldMode_) {
1057 d->nextFoldMode_ = false;
1058 cur.screenUpdateFlags(Update::SinglePar);
1063 bool InsetMathMacro::folded() const
1065 return d->nextFoldMode_;
1069 void InsetMathMacro::write(WriteStream & os) const
1071 mode_type mode = currentMode();
1072 MathEnsurer ensurer(os, mode == MATH_MODE, true, mode == TEXT_MODE);
1075 if (d->displayMode_ != DISPLAY_NORMAL) {
1076 os << "\\" << name();
1077 if (name().size() != 1 || isAlphaASCII(name()[0]))
1078 os.pendingSpace(true);
1083 // we should be ok to continue even if this fails.
1086 // Always protect macros in a fragile environment
1090 os << "\\" << name();
1093 // Optional arguments:
1094 // First find last non-empty optional argument
1095 idx_type emptyOptFrom = 0;
1097 for (; i < cells_.size() && i < d->optionals_; ++i) {
1098 if (!cell(i).empty())
1099 emptyOptFrom = i + 1;
1102 // print out optionals
1103 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
1105 // For correctly parsing it when a document is reloaded, we
1106 // need to enclose an optional argument in braces if it starts
1107 // with a script inset with empty nucleus or ends with a
1108 // delimiter-size-modifier macro (see #10497 and #11346).
1109 // We also need to do that when the optional argument
1110 // contains macros with optionals.
1111 bool braced = false;
1112 size_type last = cell(i).size() - 1;
1113 if (cell(i).size() && cell(i)[last]->asUnknownInset()) {
1114 latexkeys const * l = in_word_set(cell(i)[last]->name());
1115 braced = (l && l->inset == "big");
1116 } else if (cell(i).size() && cell(i)[0]->asScriptInset()) {
1117 braced = cell(i)[0]->asScriptInset()->nuc().empty();
1119 for (size_type j = 0; j < cell(i).size(); ++j) {
1120 InsetMathMacro const * ma = cell(i)[j]->asMacro();
1121 if (ma && ma->optionals()) {
1128 os << "[{" << cell(i) << "}]";
1130 os << "[" << cell(i) << "]";
1133 // skip the tailing empty optionals
1136 // Print remaining arguments
1137 for (; i < cells_.size(); ++i) {
1138 if (cell(i).size() == 1
1139 && cell(i)[0].nucleus()->asCharInset()
1140 && isASCII(cell(i)[0].nucleus()->asCharInset()->getChar())) {
1145 os << "{" << cell(i) << "}";
1149 // add space if there was no argument
1151 os.pendingSpace(true);
1155 void InsetMathMacro::maple(MapleStream & os) const
1157 lyx::maple(d->expanded_, os);
1161 void InsetMathMacro::maxima(MaximaStream & os) const
1163 lyx::maxima(d->expanded_, os);
1167 void InsetMathMacro::mathematica(MathematicaStream & os) const
1169 lyx::mathematica(d->expanded_, os);
1173 void InsetMathMacro::mathmlize(MathStream & os) const
1175 // macro_ is 0 if this is an unknown macro
1176 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1178 docstring const xmlname = d->macro_->xmlname();
1179 if (!xmlname.empty()) {
1180 char const * type = d->macro_->MathMLtype();
1181 os << '<' << type << "> " << xmlname << " </"
1186 if (d->expanded_.empty()) {
1187 // this means that we do not recognize the macro
1188 throw MathExportException();
1194 void InsetMathMacro::htmlize(HtmlStream & os) const
1196 // macro_ is 0 if this is an unknown macro
1197 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1199 docstring const xmlname = d->macro_->xmlname();
1200 if (!xmlname.empty()) {
1201 os << ' ' << xmlname << ' ';
1205 if (d->expanded_.empty()) {
1206 // this means that we do not recognize the macro
1207 throw MathExportException();
1213 void InsetMathMacro::octave(OctaveStream & os) const
1215 lyx::octave(d->expanded_, os);
1219 void InsetMathMacro::infoize(odocstream & os) const
1221 os << bformat(_("Macro: %1$s"), name());
1225 void InsetMathMacro::infoize2(odocstream & os) const
1227 os << bformat(_("Macro: %1$s"), name());
1231 bool InsetMathMacro::completionSupported(Cursor const & cur) const
1233 if (displayMode() != DISPLAY_UNFOLDED)
1234 return InsetMathNest::completionSupported(cur);
1236 return lyxrc.completion_popup_math
1237 && cur.bv().cursor().pos() == int(name().size());
1241 bool InsetMathMacro::inlineCompletionSupported(Cursor const & cur) const
1243 if (displayMode() != DISPLAY_UNFOLDED)
1244 return InsetMathNest::inlineCompletionSupported(cur);
1246 return lyxrc.completion_inline_math
1247 && cur.bv().cursor().pos() == int(name().size());
1251 bool InsetMathMacro::automaticInlineCompletion() const
1253 if (displayMode() != DISPLAY_UNFOLDED)
1254 return InsetMathNest::automaticInlineCompletion();
1256 return lyxrc.completion_inline_math;
1260 bool InsetMathMacro::automaticPopupCompletion() const
1262 if (displayMode() != DISPLAY_UNFOLDED)
1263 return InsetMathNest::automaticPopupCompletion();
1265 return lyxrc.completion_popup_math;
1269 CompletionList const *
1270 InsetMathMacro::createCompletionList(Cursor const & cur) const
1272 if (displayMode() != DISPLAY_UNFOLDED)
1273 return InsetMathNest::createCompletionList(cur);
1275 return new MathCompletionList(cur.bv().cursor());
1279 docstring InsetMathMacro::completionPrefix(Cursor const & cur) const
1281 if (displayMode() != DISPLAY_UNFOLDED)
1282 return InsetMathNest::completionPrefix(cur);
1284 if (!completionSupported(cur))
1287 return "\\" + name();
1291 bool InsetMathMacro::insertCompletion(Cursor & cur, docstring const & s,
1294 if (displayMode() != DISPLAY_UNFOLDED)
1295 return InsetMathNest::insertCompletion(cur, s, finished);
1297 if (!completionSupported(cur))
1300 // append completion
1301 docstring newName = name() + s;
1302 asArray(newName, cell(0));
1303 cur.bv().cursor().pos() = name().size();
1304 cur.screenUpdateFlags(Update::SinglePar);
1308 cur.bv().cursor().pop();
1309 ++cur.bv().cursor().pos();
1310 cur.screenUpdateFlags(Update::SinglePar);
1317 void InsetMathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
1318 Dimension & dim) const
1320 if (displayMode() != DISPLAY_UNFOLDED)
1321 InsetMathNest::completionPosAndDim(cur, x, y, dim);
1323 // get inset dimensions
1324 dim = cur.bv().coordCache().insets().dim(this);
1325 // FIXME: these 3 are no accurate, but should depend on the font.
1326 // Now the popup jumps down if you enter a char with descent > 0.
1332 = cur.bv().coordCache().insets().xy(this);
1338 void InsetMathMacro::setBuffer(Buffer & buffer)
1340 d->definition_.setBuffer(buffer);
1341 InsetMathNest::setBuffer(buffer);