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, otherwise
665 // we would get an endless loop (bug 9140). UpdateLocker does not work
666 // in this case, since MacroData::expand() creates new InsetMathMacro
667 // objects, so this would be a different recursion path than the one
668 // protected by UpdateLocker.
669 if (d->macro_->expand(values, d->expanded_)) {
670 if (utype == OutputUpdate && !d->expanded_.empty())
671 d->expanded_.updateMacros(cur, mc, utype, nesting);
673 // get definition for list edit mode
674 docstring const & display = d->macro_->display();
675 asArray(display.empty() ? d->macro_->definition() : display,
676 d->definition_, Parse::QUIET | Parse::MACRODEF);
680 void InsetMathMacro::draw(PainterInfo & pi, int x, int y) const
682 Dimension const dim = dimension(*pi.base.bv);
687 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
688 Changer dummy = pi.base.changeFontSet("lyxtex");
689 pi.pain.text(x, y, from_ascii("\\") + name(), pi.base.font);
690 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
691 Changer dummy = pi.base.changeFontSet("lyxtex");
692 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
693 x += mathed_string_width(pi.base.font, from_ascii("\\")) + 1;
694 cell(0).draw(pi, x, y);
695 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
696 && d->editing_[pi.base.bv]) {
697 // Macro will be edited in a old-style list mode here:
699 CoordCache const & coords = pi.base.bv->coordCache();
700 FontInfo const & labelFont = sane_font;
702 // box needs one pixel
705 // get maximal font height
707 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
710 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
711 pi.pain.text(x, y, label, labelFont);
712 x += mathed_string_width(labelFont, label);
715 d->definition_.draw(pi, x, y);
716 Dimension const & defDim = coords.getArrays().dim(&d->definition_);
717 y += max(fontDim.des, defDim.des);
720 docstring str = from_ascii("#9");
721 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
722 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
724 for (idx_type i = 0; i < nargs(); ++i) {
726 Dimension const & cdim = coords.getArrays().dim(&cell(i));
728 y += max(fontDim.asc, cdim.asc) + 1;
732 pi.pain.text(x, y, str, labelFont);
734 pi.pain.text(x, y, from_ascii(":"), labelFont);
738 cell(i).draw(pi, x, y);
741 y += max(fontDim.des, cdim.des);
744 pi.pain.rectangle(expx, expy - dim.asc + 1, dim.wid - 1,
745 dim.height() - 2, Color_mathmacroframe);
747 // We should not be here, since the macro is linearized in this case.
751 // edit mode changed?
752 if (d->editing_[pi.base.bv] != editMode(pi.base.bv))
753 pi.base.bv->cursor().screenUpdateFlags(Update::SinglePar);
757 void InsetMathMacro::setDisplayMode(InsetMathMacro::DisplayMode mode, int appetite)
759 if (d->displayMode_ != mode) {
760 // transfer name if changing from or to DISPLAY_UNFOLDED
761 if (mode == DISPLAY_UNFOLDED) {
763 asArray(d->name_, cell(0));
764 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
765 d->name_ = asString(cell(0));
769 d->displayMode_ = mode;
770 d->needsUpdate_ = true;
773 // the interactive init mode is non-greedy by default
775 d->appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
777 d->appetite_ = size_t(appetite);
781 InsetMathMacro::DisplayMode InsetMathMacro::computeDisplayMode() const
783 if (d->nextFoldMode_ == true && d->macro_ && !d->macro_->locked())
784 return DISPLAY_NORMAL;
786 return DISPLAY_UNFOLDED;
790 bool InsetMathMacro::validName() const
792 docstring n = name();
797 // converting back and force doesn't swallow anything?
800 if (asString(ma) != n)
805 for (size_t i = 0; i<n.size(); ++i) {
806 if (!(n[i] >= 'a' && n[i] <= 'z')
807 && !(n[i] >= 'A' && n[i] <= 'Z')
817 size_t InsetMathMacro::arity() const
819 if (d->displayMode_ == DISPLAY_NORMAL )
820 return cells_.size();
826 size_t InsetMathMacro::optionals() const
828 return d->optionals_;
832 void InsetMathMacro::setOptionals(int n)
834 if (n <= int(nargs()))
839 size_t InsetMathMacro::appetite() const
845 MathClass InsetMathMacro::mathClass() const
847 // This can be just a heuristic, since it is only considered for display
848 // when the macro is not linearised. Therefore it affects:
849 // * The spacing of the inset while being edited,
850 // * Intelligent splitting
851 // * Cursor word movement (Ctrl-Arrow).
852 if (MacroData const * m = macroBackup()) {
853 // If it is a global macro and is defined explicitly
855 MathClass mc = string_to_class(m->symbol()->extra);
856 if (mc != MC_UNKNOWN)
860 // Otherwise guess from the expanded macro
861 return d->expanded_.mathClass();
865 InsetMath::mode_type InsetMathMacro::currentMode() const
867 // User defined macros are always assumed to be mathmode macros.
868 // Only the global macros defined in lib/symbols may be textmode.
869 if (MacroData const * m = macroBackup()) {
870 if (m->symbol() && m->symbol()->extra == "textmode")
875 // Unknown macros are undecided.
876 return UNDECIDED_MODE;
880 MacroData const * InsetMathMacro::macroBackup() const
883 return &d->macroBackup_;
884 if (MacroData const * data = MacroTable::globalMacros().get(name()))
890 void InsetMathMacro::validate(LaTeXFeatures & features) const
892 // Immediately after a document is loaded, in some cases the MacroData
893 // of the global macros defined in the lib/symbols file may still not
894 // be known to the macro machinery because it will be set only after
895 // the first call to updateMacros(). This is not a problem unless
896 // instant preview is on for math, in which case we will be missing
897 // the corresponding requirements.
898 // In this case, we get the required info from the global macro table.
899 if (!d->requires_.empty())
900 features.require(d->requires_);
901 else if (!d->macro_) {
902 // Update requires for known global macros.
903 MacroData const * data = MacroTable::globalMacros().get(name());
904 if (data && !data->requires().empty())
905 features.require(data->requires());
908 if (name() == "binom")
909 features.require("binom");
911 // validate the cells and the definition
912 if (displayMode() == DISPLAY_NORMAL) {
913 d->definition_.validate(features);
914 InsetMathNest::validate(features);
919 void InsetMathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
921 cur.screenUpdateFlags(Update::SinglePar);
922 InsetMathNest::edit(cur, front, entry_from);
926 Inset * InsetMathMacro::editXY(Cursor & cur, int x, int y)
928 // We may have 0 arguments, but InsetMathNest requires at least one.
930 cur.screenUpdateFlags(Update::SinglePar);
931 return InsetMathNest::editXY(cur, x, y);
937 void InsetMathMacro::removeArgument(Inset::pos_type pos) {
938 if (d->displayMode_ == DISPLAY_NORMAL) {
939 LASSERT(size_t(pos) < cells_.size(), return);
940 cells_.erase(cells_.begin() + pos);
941 if (size_t(pos) < d->attachedArgsNum_)
942 --d->attachedArgsNum_;
943 if (size_t(pos) < d->optionals_) {
947 d->needsUpdate_ = true;
952 void InsetMathMacro::insertArgument(Inset::pos_type pos) {
953 if (d->displayMode_ == DISPLAY_NORMAL) {
954 LASSERT(size_t(pos) <= cells_.size(), return);
955 cells_.insert(cells_.begin() + pos, MathData());
956 if (size_t(pos) < d->attachedArgsNum_)
957 ++d->attachedArgsNum_;
958 if (size_t(pos) < d->optionals_)
961 d->needsUpdate_ = true;
966 void InsetMathMacro::detachArguments(vector<MathData> & args, bool strip)
968 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
971 // strip off empty cells, but not more than arity-attachedArgsNum_
974 for (i = cells_.size(); i > d->attachedArgsNum_; --i)
975 if (!cell(i - 1).empty()) break;
979 d->attachedArgsNum_ = 0;
980 d->expanded_ = MathData();
983 d->needsUpdate_ = true;
987 void InsetMathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
989 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
991 d->attachedArgsNum_ = args.size();
992 cells_.resize(arity);
993 d->expanded_ = MathData();
994 d->optionals_ = optionals;
996 d->needsUpdate_ = true;
1000 bool InsetMathMacro::idxFirst(Cursor & cur) const
1002 cur.screenUpdateFlags(Update::SinglePar);
1003 return InsetMathNest::idxFirst(cur);
1007 bool InsetMathMacro::idxLast(Cursor & cur) const
1009 cur.screenUpdateFlags(Update::SinglePar);
1010 return InsetMathNest::idxLast(cur);
1014 bool InsetMathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
1016 if (d->displayMode_ == DISPLAY_UNFOLDED) {
1017 docstring const & unfolded_name = name();
1018 if (unfolded_name != d->name_) {
1019 // The macro name was changed
1020 Cursor inset_cursor = old;
1021 int macroSlice = inset_cursor.find(this);
1022 // returning true means the cursor is "now" invalid,
1024 LASSERT(macroSlice != -1, return true);
1025 inset_cursor.cutOff(macroSlice);
1026 inset_cursor.recordUndoInset();
1028 inset_cursor.cell().erase(inset_cursor.pos());
1029 inset_cursor.cell().insert(inset_cursor.pos(),
1030 createInsetMath(unfolded_name, cur.buffer()));
1032 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
1036 cur.screenUpdateFlags(Update::Force);
1037 return InsetMathNest::notifyCursorLeaves(old, cur);
1041 void InsetMathMacro::fold(Cursor & cur)
1043 if (!d->nextFoldMode_) {
1044 d->nextFoldMode_ = true;
1045 cur.screenUpdateFlags(Update::SinglePar);
1050 void InsetMathMacro::unfold(Cursor & cur)
1052 if (d->nextFoldMode_) {
1053 d->nextFoldMode_ = false;
1054 cur.screenUpdateFlags(Update::SinglePar);
1059 bool InsetMathMacro::folded() const
1061 return d->nextFoldMode_;
1065 void InsetMathMacro::write(WriteStream & os) const
1067 mode_type mode = currentMode();
1068 MathEnsurer ensurer(os, mode == MATH_MODE, true, mode == TEXT_MODE);
1071 if (d->displayMode_ != DISPLAY_NORMAL) {
1072 os << "\\" << name();
1073 if (name().size() != 1 || isAlphaASCII(name()[0]))
1074 os.pendingSpace(true);
1079 // we should be ok to continue even if this fails.
1082 // We may already be in the argument of a macro
1083 bool const inside_macro = os.insideMacro();
1084 os.insideMacro(true);
1086 // Enclose in braces to avoid latex errors with xargs if we have
1087 // optional arguments and are in the optional argument of a macro
1088 if (d->optionals_ && inside_macro)
1091 // Always protect macros in a fragile environment
1095 os << "\\" << name();
1098 // Optional arguments:
1099 // First find last non-empty optional argument
1100 idx_type emptyOptFrom = 0;
1102 for (; i < cells_.size() && i < d->optionals_; ++i) {
1103 if (!cell(i).empty())
1104 emptyOptFrom = i + 1;
1107 // print out optionals
1108 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
1110 // For correctly parsing it when a document is reloaded, we
1111 // need to enclose an optional argument in braces if it starts
1112 // with a script inset with empty nucleus or ends with a
1113 // delimiter-size-modifier macro (see #10497 and #11346)
1114 bool braced = false;
1115 size_type last = cell(i).size() - 1;
1116 if (cell(i)[last].nucleus()->asUnknownInset()) {
1117 latexkeys const * l = in_word_set(cell(i)[last].nucleus()->name());
1118 braced = (l && l->inset == "big");
1119 } else if (cell(i)[0].nucleus()->asScriptInset()) {
1120 braced = cell(i)[0].nucleus()->asScriptInset()->nuc().empty();
1123 os << "[{" << cell(i) << "}]";
1125 os << "[" << cell(i) << "]";
1128 // skip the tailing empty optionals
1131 // Print remaining arguments
1132 for (; i < cells_.size(); ++i) {
1133 if (cell(i).size() == 1
1134 && cell(i)[0].nucleus()->asCharInset()
1135 && isASCII(cell(i)[0].nucleus()->asCharInset()->getChar())) {
1140 os << "{" << cell(i) << "}";
1144 // Close the opened brace or add space if there was no argument
1145 if (d->optionals_ && inside_macro)
1148 os.pendingSpace(true);
1150 os.insideMacro(inside_macro);
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);