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 if (d->macro_->expand(values, d->expanded_)
673 && !support::contains(display, latexname)) {
674 if (utype == OutputUpdate && !d->expanded_.empty())
675 d->expanded_.updateMacros(cur, mc, utype, nesting);
677 // get definition for list edit mode
678 asArray(display.empty() ? d->macro_->definition() : display,
679 d->definition_, Parse::QUIET | Parse::MACRODEF);
683 void InsetMathMacro::draw(PainterInfo & pi, int x, int y) const
685 Dimension const dim = dimension(*pi.base.bv);
690 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
691 Changer dummy = pi.base.changeFontSet("lyxtex");
692 pi.pain.text(x, y, from_ascii("\\") + name(), pi.base.font);
693 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
694 Changer dummy = pi.base.changeFontSet("lyxtex");
695 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
696 x += mathed_string_width(pi.base.font, from_ascii("\\")) + 1;
697 cell(0).draw(pi, x, y);
698 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
699 && d->editing_[pi.base.bv]) {
700 // Macro will be edited in a old-style list mode here:
702 CoordCache const & coords = pi.base.bv->coordCache();
703 FontInfo const & labelFont = sane_font;
705 // box needs one pixel
708 // get maximal font height
710 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
713 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
714 pi.pain.text(x, y, label, labelFont);
715 x += mathed_string_width(labelFont, label);
718 d->definition_.draw(pi, x, y);
719 Dimension const & defDim = coords.getArrays().dim(&d->definition_);
720 y += max(fontDim.des, defDim.des);
723 docstring str = from_ascii("#9");
724 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
725 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
727 for (idx_type i = 0; i < nargs(); ++i) {
729 Dimension const & cdim = coords.getArrays().dim(&cell(i));
731 y += max(fontDim.asc, cdim.asc) + 1;
735 pi.pain.text(x, y, str, labelFont);
737 pi.pain.text(x, y, from_ascii(":"), labelFont);
741 cell(i).draw(pi, x, y);
744 y += max(fontDim.des, cdim.des);
747 pi.pain.rectangle(expx, expy - dim.asc + 1, dim.wid - 1,
748 dim.height() - 2, Color_mathmacroframe);
750 // We should not be here, since the macro is linearized in this case.
754 // edit mode changed?
755 if (d->editing_[pi.base.bv] != editMode(pi.base.bv))
756 pi.base.bv->cursor().screenUpdateFlags(Update::SinglePar);
760 void InsetMathMacro::setDisplayMode(InsetMathMacro::DisplayMode mode, int appetite)
762 if (d->displayMode_ != mode) {
763 // transfer name if changing from or to DISPLAY_UNFOLDED
764 if (mode == DISPLAY_UNFOLDED) {
766 asArray(d->name_, cell(0));
767 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
768 d->name_ = asString(cell(0));
772 d->displayMode_ = mode;
773 d->needsUpdate_ = true;
776 // the interactive init mode is non-greedy by default
778 d->appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
780 d->appetite_ = size_t(appetite);
784 InsetMathMacro::DisplayMode InsetMathMacro::computeDisplayMode() const
786 if (d->nextFoldMode_ == true && d->macro_ && !d->macro_->locked())
787 return DISPLAY_NORMAL;
789 return DISPLAY_UNFOLDED;
793 bool InsetMathMacro::validName() const
795 docstring n = name();
800 // converting back and force doesn't swallow anything?
803 if (asString(ma) != n)
808 for (size_t i = 0; i<n.size(); ++i) {
809 if (!(n[i] >= 'a' && n[i] <= 'z')
810 && !(n[i] >= 'A' && n[i] <= 'Z')
820 size_t InsetMathMacro::arity() const
822 if (d->displayMode_ == DISPLAY_NORMAL )
823 return cells_.size();
829 size_t InsetMathMacro::optionals() const
831 return d->optionals_;
835 void InsetMathMacro::setOptionals(int n)
837 if (n <= int(nargs()))
842 size_t InsetMathMacro::appetite() const
848 MathClass InsetMathMacro::mathClass() const
850 // This can be just a heuristic, since it is only considered for display
851 // when the macro is not linearised. Therefore it affects:
852 // * The spacing of the inset while being edited,
853 // * Intelligent splitting
854 // * Cursor word movement (Ctrl-Arrow).
855 if (MacroData const * m = macroBackup()) {
856 // If it is a global macro and is defined explicitly
858 MathClass mc = string_to_class(m->symbol()->extra);
859 if (mc != MC_UNKNOWN)
863 // Otherwise guess from the expanded macro
864 return d->expanded_.mathClass();
868 InsetMath::mode_type InsetMathMacro::currentMode() const
870 // User defined macros are always assumed to be mathmode macros.
871 // Only the global macros defined in lib/symbols may be textmode.
872 if (MacroData const * m = macroBackup()) {
873 if (m->symbol() && m->symbol()->extra == "textmode")
878 // Unknown macros are undecided.
879 return UNDECIDED_MODE;
883 MacroData const * InsetMathMacro::macroBackup() const
886 return &d->macroBackup_;
887 if (MacroData const * data = MacroTable::globalMacros().get(name()))
893 void InsetMathMacro::validate(LaTeXFeatures & features) const
895 // Immediately after a document is loaded, in some cases the MacroData
896 // of the global macros defined in the lib/symbols file may still not
897 // be known to the macro machinery because it will be set only after
898 // the first call to updateMacros(). This is not a problem unless
899 // instant preview is on for math, in which case we will be missing
900 // the corresponding requirements.
901 // In this case, we get the required info from the global macro table.
902 if (!d->requires_.empty())
903 features.require(d->requires_);
904 else if (!d->macro_) {
905 // Update requires for known global macros.
906 MacroData const * data = MacroTable::globalMacros().get(name());
907 if (data && !data->requires().empty())
908 features.require(data->requires());
911 if (name() == "binom")
912 features.require("binom");
914 // validate the cells and the definition
915 if (displayMode() == DISPLAY_NORMAL) {
916 d->definition_.validate(features);
917 InsetMathNest::validate(features);
922 void InsetMathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
924 cur.screenUpdateFlags(Update::SinglePar);
925 InsetMathNest::edit(cur, front, entry_from);
929 Inset * InsetMathMacro::editXY(Cursor & cur, int x, int y)
931 // We may have 0 arguments, but InsetMathNest requires at least one.
933 cur.screenUpdateFlags(Update::SinglePar);
934 return InsetMathNest::editXY(cur, x, y);
940 void InsetMathMacro::removeArgument(Inset::pos_type pos) {
941 if (d->displayMode_ == DISPLAY_NORMAL) {
942 LASSERT(size_t(pos) < cells_.size(), return);
943 cells_.erase(cells_.begin() + pos);
944 if (size_t(pos) < d->attachedArgsNum_)
945 --d->attachedArgsNum_;
946 if (size_t(pos) < d->optionals_) {
950 d->needsUpdate_ = true;
955 void InsetMathMacro::insertArgument(Inset::pos_type pos) {
956 if (d->displayMode_ == DISPLAY_NORMAL) {
957 LASSERT(size_t(pos) <= cells_.size(), return);
958 cells_.insert(cells_.begin() + pos, MathData());
959 if (size_t(pos) < d->attachedArgsNum_)
960 ++d->attachedArgsNum_;
961 if (size_t(pos) < d->optionals_)
964 d->needsUpdate_ = true;
969 void InsetMathMacro::detachArguments(vector<MathData> & args, bool strip)
971 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
974 // strip off empty cells, but not more than arity-attachedArgsNum_
977 for (i = cells_.size(); i > d->attachedArgsNum_; --i)
978 if (!cell(i - 1).empty()) break;
982 d->attachedArgsNum_ = 0;
983 d->expanded_ = MathData();
986 d->needsUpdate_ = true;
990 void InsetMathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
992 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
994 d->attachedArgsNum_ = args.size();
995 cells_.resize(arity);
996 d->expanded_ = MathData();
997 d->optionals_ = optionals;
999 d->needsUpdate_ = true;
1003 bool InsetMathMacro::idxFirst(Cursor & cur) const
1005 cur.screenUpdateFlags(Update::SinglePar);
1006 return InsetMathNest::idxFirst(cur);
1010 bool InsetMathMacro::idxLast(Cursor & cur) const
1012 cur.screenUpdateFlags(Update::SinglePar);
1013 return InsetMathNest::idxLast(cur);
1017 bool InsetMathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
1019 if (d->displayMode_ == DISPLAY_UNFOLDED) {
1020 docstring const & unfolded_name = name();
1021 if (unfolded_name != d->name_) {
1022 // The macro name was changed
1023 Cursor inset_cursor = old;
1024 int macroSlice = inset_cursor.find(this);
1025 // returning true means the cursor is "now" invalid,
1027 LASSERT(macroSlice != -1, return true);
1028 inset_cursor.cutOff(macroSlice);
1029 inset_cursor.recordUndoInset();
1031 inset_cursor.cell().erase(inset_cursor.pos());
1032 inset_cursor.cell().insert(inset_cursor.pos(),
1033 createInsetMath(unfolded_name, cur.buffer()));
1035 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
1039 cur.screenUpdateFlags(Update::Force);
1040 return InsetMathNest::notifyCursorLeaves(old, cur);
1044 void InsetMathMacro::fold(Cursor & cur)
1046 if (!d->nextFoldMode_) {
1047 d->nextFoldMode_ = true;
1048 cur.screenUpdateFlags(Update::SinglePar);
1053 void InsetMathMacro::unfold(Cursor & cur)
1055 if (d->nextFoldMode_) {
1056 d->nextFoldMode_ = false;
1057 cur.screenUpdateFlags(Update::SinglePar);
1062 bool InsetMathMacro::folded() const
1064 return d->nextFoldMode_;
1068 void InsetMathMacro::write(WriteStream & os) const
1070 mode_type mode = currentMode();
1071 MathEnsurer ensurer(os, mode == MATH_MODE, true, mode == TEXT_MODE);
1074 if (d->displayMode_ != DISPLAY_NORMAL) {
1075 os << "\\" << name();
1076 if (name().size() != 1 || isAlphaASCII(name()[0]))
1077 os.pendingSpace(true);
1082 // we should be ok to continue even if this fails.
1085 // Always protect macros in a fragile environment
1089 os << "\\" << name();
1092 // Optional arguments:
1093 // First find last non-empty optional argument
1094 idx_type emptyOptFrom = 0;
1096 for (; i < cells_.size() && i < d->optionals_; ++i) {
1097 if (!cell(i).empty())
1098 emptyOptFrom = i + 1;
1101 // print out optionals
1102 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
1104 // For correctly parsing it when a document is reloaded, we
1105 // need to enclose an optional argument in braces if it starts
1106 // with a script inset with empty nucleus or ends with a
1107 // delimiter-size-modifier macro (see #10497 and #11346).
1108 // We also need to do that when the optional argument
1109 // contains macros with optionals.
1110 bool braced = false;
1111 size_type last = cell(i).size() - 1;
1112 if (cell(i).size() && cell(i)[last]->asUnknownInset()) {
1113 latexkeys const * l = in_word_set(cell(i)[last]->name());
1114 braced = (l && l->inset == "big");
1115 } else if (cell(i).size() && cell(i)[0]->asScriptInset()) {
1116 braced = cell(i)[0]->asScriptInset()->nuc().empty();
1118 for (size_type j = 0; j < cell(i).size(); ++j) {
1119 InsetMathMacro const * ma = cell(i)[j]->asMacro();
1120 if (ma && ma->optionals()) {
1127 os << "[{" << cell(i) << "}]";
1129 os << "[" << cell(i) << "]";
1132 // skip the tailing empty optionals
1135 // Print remaining arguments
1136 for (; i < cells_.size(); ++i) {
1137 if (cell(i).size() == 1
1138 && cell(i)[0].nucleus()->asCharInset()
1139 && isASCII(cell(i)[0].nucleus()->asCharInset()->getChar())) {
1144 os << "{" << cell(i) << "}";
1148 // add space if there was no argument
1150 os.pendingSpace(true);
1154 void InsetMathMacro::maple(MapleStream & os) const
1156 lyx::maple(d->expanded_, os);
1160 void InsetMathMacro::maxima(MaximaStream & os) const
1162 lyx::maxima(d->expanded_, os);
1166 void InsetMathMacro::mathematica(MathematicaStream & os) const
1168 lyx::mathematica(d->expanded_, os);
1172 void InsetMathMacro::mathmlize(MathStream & os) const
1174 // macro_ is 0 if this is an unknown macro
1175 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1177 docstring const xmlname = d->macro_->xmlname();
1178 if (!xmlname.empty()) {
1179 char const * type = d->macro_->MathMLtype();
1180 os << '<' << type << "> " << xmlname << " </"
1185 if (d->expanded_.empty()) {
1186 // this means that we do not recognize the macro
1187 throw MathExportException();
1193 void InsetMathMacro::htmlize(HtmlStream & os) const
1195 // macro_ is 0 if this is an unknown macro
1196 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1198 docstring const xmlname = d->macro_->xmlname();
1199 if (!xmlname.empty()) {
1200 os << ' ' << xmlname << ' ';
1204 if (d->expanded_.empty()) {
1205 // this means that we do not recognize the macro
1206 throw MathExportException();
1212 void InsetMathMacro::octave(OctaveStream & os) const
1214 lyx::octave(d->expanded_, os);
1218 void InsetMathMacro::infoize(odocstream & os) const
1220 os << bformat(_("Macro: %1$s"), name());
1224 void InsetMathMacro::infoize2(odocstream & os) const
1226 os << bformat(_("Macro: %1$s"), name());
1230 bool InsetMathMacro::completionSupported(Cursor const & cur) const
1232 if (displayMode() != DISPLAY_UNFOLDED)
1233 return InsetMathNest::completionSupported(cur);
1235 return lyxrc.completion_popup_math
1236 && displayMode() == DISPLAY_UNFOLDED
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 && displayMode() == DISPLAY_UNFOLDED
1248 && cur.bv().cursor().pos() == int(name().size());
1252 bool InsetMathMacro::automaticInlineCompletion() const
1254 if (displayMode() != DISPLAY_UNFOLDED)
1255 return InsetMathNest::automaticInlineCompletion();
1257 return lyxrc.completion_inline_math;
1261 bool InsetMathMacro::automaticPopupCompletion() const
1263 if (displayMode() != DISPLAY_UNFOLDED)
1264 return InsetMathNest::automaticPopupCompletion();
1266 return lyxrc.completion_popup_math;
1270 CompletionList const *
1271 InsetMathMacro::createCompletionList(Cursor const & cur) const
1273 if (displayMode() != DISPLAY_UNFOLDED)
1274 return InsetMathNest::createCompletionList(cur);
1276 return new MathCompletionList(cur.bv().cursor());
1280 docstring InsetMathMacro::completionPrefix(Cursor const & cur) const
1282 if (displayMode() != DISPLAY_UNFOLDED)
1283 return InsetMathNest::completionPrefix(cur);
1285 if (!completionSupported(cur))
1288 return "\\" + name();
1292 bool InsetMathMacro::insertCompletion(Cursor & cur, docstring const & s,
1295 if (displayMode() != DISPLAY_UNFOLDED)
1296 return InsetMathNest::insertCompletion(cur, s, finished);
1298 if (!completionSupported(cur))
1301 // append completion
1302 docstring newName = name() + s;
1303 asArray(newName, cell(0));
1304 cur.bv().cursor().pos() = name().size();
1305 cur.screenUpdateFlags(Update::SinglePar);
1309 cur.bv().cursor().pop();
1310 ++cur.bv().cursor().pos();
1311 cur.screenUpdateFlags(Update::SinglePar);
1318 void InsetMathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
1319 Dimension & dim) const
1321 if (displayMode() != DISPLAY_UNFOLDED)
1322 InsetMathNest::completionPosAndDim(cur, x, y, dim);
1324 // get inset dimensions
1325 dim = cur.bv().coordCache().insets().dim(this);
1326 // FIXME: these 3 are no accurate, but should depend on the font.
1327 // Now the popup jumps down if you enter a char with descent > 0.
1333 = cur.bv().coordCache().insets().xy(this);
1339 void InsetMathMacro::setBuffer(Buffer & buffer)
1341 d->definition_.setBuffer(buffer);
1342 InsetMathNest::setBuffer(buffer);