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 "MathMacro.h"
17 #include "InsetMathChar.h"
18 #include "MathCompletionList.h"
19 #include "MathExtern.h"
20 #include "MathFactory.h"
21 #include "MathStream.h"
22 #include "MathSupport.h"
25 #include "BufferView.h"
26 #include "CoordCache.h"
28 #include "FuncStatus.h"
29 #include "FuncRequest.h"
30 #include "LaTeXFeatures.h"
33 #include "MetricsInfo.h"
35 #include "frontends/Painter.h"
37 #include "support/debug.h"
38 #include "support/gettext.h"
39 #include "support/lassert.h"
40 #include "support/lstrings.h"
41 #include "support/RefChanger.h"
42 #include "support/textutils.h"
47 using namespace lyx::support;
53 /// A proxy for the macro values
54 class ArgumentProxy : public InsetMath {
57 ArgumentProxy(MathMacro * mathMacro, size_t idx)
58 : mathMacro_(mathMacro), idx_(idx) {}
60 ArgumentProxy(MathMacro * mathMacro, size_t idx, docstring const & def)
61 : mathMacro_(mathMacro), idx_(idx)
66 void setOwner(MathMacro * mathMacro) { mathMacro_ = mathMacro; }
68 MathMacro const * owner() { return mathMacro_; }
70 InsetCode lyxCode() const { return ARGUMENT_PROXY_CODE; }
71 /// The math data to use for display
72 MathData const & displayCell(BufferView const * bv) const
74 // handle default macro arguments
75 bool use_def_arg = !mathMacro_->editMetrics(bv)
76 && mathMacro_->cell(idx_).empty();
77 return use_def_arg ? def_ : mathMacro_->cell(idx_);
80 bool addToMathRow(MathRow & mrow, MetricsInfo & mi) const
82 // macro arguments are in macros
83 LATTEST(mathMacro_->nesting() > 0);
84 /// The macro nesting can change display of insets. Change it locally.
85 Changer chg = make_change(mi.base.macro_nesting, mathMacro_->nesting());
87 MathRow::Element e_beg(MathRow::BEG_ARG);
88 e_beg.macro = mathMacro_;
89 e_beg.ar = &mathMacro_->cell(idx_);
90 mrow.push_back(e_beg);
92 mathMacro_->macro()->unlock();
93 bool has_contents = displayCell(mi.base.bv).addToMathRow(mrow, mi);
94 mathMacro_->macro()->lock();
96 // if there was no contents, and the contents is editable,
97 // then we insert a box instead.
98 if (!has_contents && mathMacro_->nesting() == 1) {
99 // mathclass is ord because it should be spaced as a normal atom
100 MathRow::Element e(MathRow::BOX, MC_ORD);
101 e.color = Color_mathline;
106 MathRow::Element e_end(MathRow::END_ARG);
107 e_end.macro = mathMacro_;
108 e_end.ar = &mathMacro_->cell(idx_);
110 mrow.push_back(e_end);
115 void metrics(MetricsInfo &, Dimension &) const {
116 // This should never be invoked, since ArgumentProxy insets are linearized
120 int kerning(BufferView const * bv) const
122 return displayCell(bv).kerning(bv);
125 void draw(PainterInfo &, int, int) const {
126 // This should never be invoked, since ArgumentProxy insets are linearized
129 // write(), normalize(), infoize() and infoize2() are not needed since
130 // MathMacro uses the definition and not the expanded cells.
132 void maple(MapleStream & ms) const { ms << mathMacro_->cell(idx_); }
134 void maxima(MaximaStream & ms) const { ms << mathMacro_->cell(idx_); }
136 void mathematica(MathematicaStream & ms) const { ms << mathMacro_->cell(idx_); }
138 void mathmlize(MathStream & ms) const { ms << mathMacro_->cell(idx_); }
140 void htmlize(HtmlStream & ms) const { ms << mathMacro_->cell(idx_); }
142 void octave(OctaveStream & os) const { os << mathMacro_->cell(idx_); }
144 MathClass mathClass() const
147 // This can be refined once the pointer issues are fixed. I did not
148 // notice any immediate crash with the following code, but it is risky
150 //return mathMacro_->cell(idx_).mathClass();
155 Inset * clone() const
157 return new ArgumentProxy(*this);
160 MathMacro * mathMacro_;
168 /// Private implementation of MathMacro
169 class MathMacro::Private {
171 Private(Buffer * buf, docstring const & name)
172 : name_(name), displayMode_(DISPLAY_INIT),
173 expanded_(buf), definition_(buf), attachedArgsNum_(0),
174 optionals_(0), nextFoldMode_(true), macroBackup_(buf),
175 macro_(0), needsUpdate_(false), isUpdating_(false),
179 /// Update the pointers to our owner of all expanded macros.
180 /// This needs to be called every time a copy of the owner is created
182 void updateChildren(MathMacro * owner);
183 /// Recursively update the pointers of all expanded macros
184 /// appearing in the arguments of the current macro
185 void updateNestedChildren(MathMacro * owner, InsetMathNest * ni);
188 /// current display mode
189 DisplayMode displayMode_;
190 /// expanded macro with ArgumentProxies
192 /// macro definition with #1,#2,.. insets
193 MathData definition_;
194 /// number of arguments that were really attached
195 size_t attachedArgsNum_;
196 /// optional argument attached? (only in DISPLAY_NORMAL mode)
198 /// fold mode to be set in next metrics call?
200 /// if macro_ == true, then here is a copy of the macro
201 /// don't use it for locking
202 MacroData macroBackup_;
203 /// if macroNotFound_ == false, then here is a reference to the macro
204 /// this might invalidate after metrics was called
205 MacroData const * macro_;
207 mutable std::map<BufferView const *, bool> editing_;
209 std::string requires_;
210 /// update macro representation
214 /// maximal number of arguments the macro is greedy for
216 /// Level of nesting in macros (including this one)
221 void MathMacro::Private::updateChildren(MathMacro * owner)
223 for (size_t i = 0; i < expanded_.size(); ++i) {
224 ArgumentProxy * p = dynamic_cast<ArgumentProxy *>(expanded_[i].nucleus());
228 InsetMathNest * ni = expanded_[i].nucleus()->asNestInset();
230 updateNestedChildren(owner, ni);
234 // The macro_ pointer is updated when MathData::metrics() is
235 // called. However, when instant preview is on or the macro is
236 // not on screen, MathData::metrics() is not called and we may
237 // have a dangling pointer. As a safety measure, when a macro
238 // is copied, always let macro_ point to the backup copy of the
239 // MacroData structure. This backup is updated every time the
240 // macro is changed, so it will not become stale.
241 macro_ = ¯oBackup_;
246 void MathMacro::Private::updateNestedChildren(MathMacro * owner, InsetMathNest * ni)
248 for (size_t i = 0; i < ni->nargs(); ++i) {
249 MathData & ar = ni->cell(i);
250 for (size_t j = 0; j < ar.size(); ++j) {
251 ArgumentProxy * ap = dynamic_cast
252 <ArgumentProxy *>(ar[j].nucleus());
254 MathMacro::Private * md = ap->owner()->d;
256 md->macro_ = &md->macroBackup_;
259 InsetMathNest * imn = ar[j].nucleus()->asNestInset();
261 updateNestedChildren(owner, imn);
267 MathMacro::MathMacro(Buffer * buf, docstring const & name)
268 : InsetMathNest(buf, 0), d(new Private(buf, name))
272 MathMacro::MathMacro(MathMacro const & that)
273 : InsetMathNest(that), d(new Private(*that.d))
275 setBuffer(*that.buffer_);
276 d->updateChildren(this);
280 MathMacro & MathMacro::operator=(MathMacro const & that)
284 InsetMathNest::operator=(that);
286 d->updateChildren(this);
291 MathMacro::~MathMacro()
297 bool MathMacro::addToMathRow(MathRow & mrow, MetricsInfo & mi) const
299 // set edit mode for which we will have calculated row.
300 // This is the same as what is done in metrics().
301 d->editing_[mi.base.bv] = editMode(mi.base.bv);
303 /// The macro nesting can change display of insets. Change it locally.
304 Changer chg = make_change(mi.base.macro_nesting, d->nesting_);
306 if (displayMode() != MathMacro::DISPLAY_NORMAL
307 || d->editing_[mi.base.bv])
308 return InsetMath::addToMathRow(mrow, mi);
310 MathRow::Element e_beg(MathRow::BEG_MACRO);
312 mrow.push_back(e_beg);
315 bool has_contents = d->expanded_.addToMathRow(mrow, mi);
318 // if there was no contents and the array is editable, then we
319 // insert a grey box instead.
320 if (!has_contents && mi.base.macro_nesting == 1) {
321 // mathclass is unknown because it is irrelevant for spacing
322 MathRow::Element e(MathRow::BOX);
323 e.color = Color_mathmacroblend;
328 MathRow::Element e_end(MathRow::END_MACRO);
330 mrow.push_back(e_end);
336 Inset * MathMacro::clone() const
338 MathMacro * copy = new MathMacro(*this);
339 copy->d->needsUpdate_ = true;
340 //copy->d->expanded_.clear();
345 void MathMacro::normalize(NormalStream & os) const
347 os << "[macro " << name();
348 for (size_t i = 0; i < nargs(); ++i)
349 os << ' ' << cell(i);
354 MathMacro::DisplayMode MathMacro::displayMode() const
356 return d->displayMode_;
360 bool MathMacro::extraBraces() const
362 return d->displayMode_ == DISPLAY_NORMAL && arity() > 0;
366 docstring MathMacro::name() const
368 if (d->displayMode_ == DISPLAY_UNFOLDED)
369 return asString(cell(0));
375 docstring MathMacro::macroName() const
381 int MathMacro::nesting() const
387 void MathMacro::cursorPos(BufferView const & bv,
388 CursorSlice const & sl, bool boundary, int & x, int & y) const
390 // We may have 0 arguments, but InsetMathNest requires at least one.
392 InsetMathNest::cursorPos(bv, sl, boundary, x, y);
396 bool MathMacro::editMode(BufferView const * bv) const {
397 // find this in cursor trace
398 Cursor const & cur = bv->cursor();
399 for (size_t i = 0; i != cur.depth(); ++i)
400 if (&cur[i].inset() == this) {
401 // look if there is no other macro in edit mode above
403 for (; i != cur.depth(); ++i) {
404 InsetMath * im = cur[i].asInsetMath();
406 MathMacro const * macro = im->asMacro();
407 if (macro && macro->displayMode() == DISPLAY_NORMAL)
412 // ok, none found, I am the highest one
420 MacroData const * MathMacro::macro() const
426 bool MathMacro::editMetrics(BufferView const * bv) const
428 return d->editing_[bv];
432 void MathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
434 /// The macro nesting can change display of insets. Change it locally.
435 Changer chg = make_change(mi.base.macro_nesting, d->nesting_);
437 // set edit mode for which we will have calculated metrics. But only
438 d->editing_[mi.base.bv] = editMode(mi.base.bv);
440 // calculate new metrics according to display mode
441 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
442 Changer dummy = mi.base.changeFontSet("lyxtex");
443 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
444 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
445 Changer dummy = mi.base.changeFontSet("lyxtex");
446 cell(0).metrics(mi, dim);
448 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
449 dim.wid += bsdim.width() + 1;
450 dim.asc = max(bsdim.ascent(), dim.ascent());
451 dim.des = max(bsdim.descent(), dim.descent());
452 metricsMarkers(mi, dim);
453 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
454 && d->editing_[mi.base.bv]) {
455 // Macro will be edited in a old-style list mode here:
459 FontInfo labelFont = sane_font;
460 math_font_max_dim(labelFont, fontDim.asc, fontDim.des);
462 // get dimension of components of list view
464 nameDim.wid = mathed_string_width(mi.base.font, from_ascii("Macro \\") + name() + ": ");
465 nameDim.asc = fontDim.asc;
466 nameDim.des = fontDim.des;
469 argDim.wid = mathed_string_width(labelFont, from_ascii("#9: "));
470 argDim.asc = fontDim.asc;
471 argDim.des = fontDim.des;
474 d->definition_.metrics(mi, defDim);
477 dim.wid = nameDim.wid + defDim.wid;
478 dim.asc = max(nameDim.asc, defDim.asc);
479 dim.des = max(nameDim.des, defDim.des);
481 for (idx_type i = 0; i < nargs(); ++i) {
483 cell(i).metrics(mi, cdim);
484 dim.des += max(argDim.height(), cdim.height()) + 1;
485 dim.wid = max(dim.wid, argDim.wid + cdim.wid);
488 // make space for box and markers, 2 pixels
492 metricsMarkers2(mi, dim);
496 // calculate metrics, hoping that all cells are seen
498 d->expanded_.metrics(mi, dim);
500 // otherwise do a manual metrics call
501 CoordCache & coords = mi.base.bv->coordCache();
502 for (idx_type i = 0; i < nargs(); ++i) {
503 if (!coords.getArrays().hasDim(&cell(i))) {
505 cell(i).metrics(mi, tdim);
510 // calculate dimension with label while editing
511 if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX
512 && d->editing_[mi.base.bv]) {
513 FontInfo font = mi.base.font;
514 augmentFont(font, "lyxtex");
516 mathed_string_dim(font, name(), namedim);
518 dim.wid += 2 + namedim.wid + 2 + 2;
519 dim.asc = max(dim.asc, namedim.asc) + 2;
520 dim.des = max(dim.des, namedim.des) + 2;
522 dim.wid = max(1 + namedim.wid + 1, 2 + dim.wid + 2);
523 dim.asc += 1 + namedim.height() + 1;
530 int MathMacro::kerning(BufferView const * bv) const {
531 if (d->displayMode_ == DISPLAY_NORMAL && !d->editing_[bv])
532 return d->expanded_.kerning(bv);
538 void MathMacro::updateMacro(MacroContext const & mc)
541 d->macro_ = mc.get(name());
542 if (d->macro_ && d->macroBackup_ != *d->macro_) {
543 d->macroBackup_ = *d->macro_;
544 d->needsUpdate_ = true;
552 class MathMacro::UpdateLocker
555 explicit UpdateLocker(MathMacro & mm) : mac(mm)
557 mac.d->isUpdating_ = true;
559 ~UpdateLocker() { mac.d->isUpdating_ = false; }
563 /** Avoid wrong usage of UpdateLocker.
564 To avoid wrong usage:
565 UpdateLocker(...); // wrong
566 UpdateLocker locker(...); // right
568 #define UpdateLocker(x) unnamed_UpdateLocker;
569 // Tip gotten from Bobby Schmidt's column in C/C++ Users Journal
572 void MathMacro::updateRepresentation(Cursor * cur, MacroContext const & mc,
573 UpdateType utype, int nesting)
575 // block recursive calls (bug 8999)
579 UpdateLocker locker(*this);
585 // remember nesting level of this macro
586 d->nesting_ = nesting;
589 d->requires_ = d->macro_->requires();
592 // non-normal mode? We are done!
593 || (d->displayMode_ != DISPLAY_NORMAL))
596 d->needsUpdate_ = false;
598 // get default values of macro
599 vector<docstring> const & defaults = d->macro_->defaults();
601 // create MathMacroArgumentValue objects pointing to the cells of the macro
602 vector<MathData> values(nargs());
603 for (size_t i = 0; i < nargs(); ++i) {
604 ArgumentProxy * proxy;
605 if (i < defaults.size())
606 proxy = new ArgumentProxy(this, i, defaults[i]);
608 proxy = new ArgumentProxy(this, i);
609 values[i].insert(0, MathAtom(proxy));
611 // expanding macro with the values
612 // Only update the argument macros if anything was expanded, otherwise
613 // we would get an endless loop (bug 9140). UpdateLocker does not work
614 // in this case, since MacroData::expand() creates new MathMacro
615 // objects, so this would be a different recursion path than the one
616 // protected by UpdateLocker.
617 if (d->macro_->expand(values, d->expanded_)) {
618 if (utype == OutputUpdate && !d->expanded_.empty())
619 d->expanded_.updateMacros(cur, mc, utype, nesting);
621 // get definition for list edit mode
622 docstring const & display = d->macro_->display();
623 asArray(display.empty() ? d->macro_->definition() : display,
624 d->definition_, Parse::QUIET);
628 void MathMacro::draw(PainterInfo & pi, int x, int y) const
630 Dimension const dim = dimension(*pi.base.bv);
635 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
636 Changer dummy = pi.base.changeFontSet("lyxtex");
637 pi.pain.text(x, y, from_ascii("\\") + name(), pi.base.font);
638 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
639 Changer dummy = pi.base.changeFontSet("lyxtex");
640 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
641 x += mathed_string_width(pi.base.font, from_ascii("\\")) + 1;
642 cell(0).draw(pi, x, y);
643 drawMarkers(pi, expx, expy);
644 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
645 && d->editing_[pi.base.bv]) {
646 // Macro will be edited in a old-style list mode here:
648 CoordCache const & coords = pi.base.bv->coordCache();
649 FontInfo const & labelFont = sane_font;
651 // markers and box needs two pixels
654 // get maximal font height
656 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
659 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
660 pi.pain.text(x, y, label, labelFont);
661 x += mathed_string_width(labelFont, label);
664 d->definition_.draw(pi, x, y);
665 Dimension const & defDim = coords.getArrays().dim(&d->definition_);
666 y += max(fontDim.des, defDim.des);
669 docstring str = from_ascii("#9");
670 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
671 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
673 for (idx_type i = 0; i < nargs(); ++i) {
675 Dimension const & cdim = coords.getArrays().dim(&cell(i));
677 y += max(fontDim.asc, cdim.asc) + 1;
681 pi.pain.text(x, y, str, labelFont);
683 pi.pain.text(x, y, from_ascii(":"), labelFont);
687 cell(i).draw(pi, x, y);
690 y += max(fontDim.des, cdim.des);
693 pi.pain.rectangle(expx + 1, expy - dim.asc + 1, dim.wid - 3,
694 dim.height() - 2, Color_mathmacroframe);
695 drawMarkers2(pi, expx, expy);
697 bool drawBox = lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX;
700 for (size_t i = 0; i < nargs(); ++i)
701 cell(i).setXY(*pi.base.bv, x, y);
703 if (drawBox && d->editing_[pi.base.bv]) {
704 // draw header and rectangle around
705 FontInfo font = pi.base.font;
706 augmentFont(font, "lyxtex");
707 font.setSize(FONT_SIZE_TINY);
708 font.setColor(Color_mathmacrolabel);
710 mathed_string_dim(font, name(), namedim);
712 pi.pain.fillRectangle(x, y - dim.asc, dim.wid, 1 + namedim.height() + 1, Color_mathmacrobg);
713 pi.pain.text(x + 1, y - dim.asc + namedim.asc + 2, name(), font);
714 expx += (dim.wid - d->expanded_.dimension(*pi.base.bv).width()) / 2;
717 if (d->editing_[pi.base.bv]) {
718 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
719 d->expanded_.draw(pi, expx, expy);
720 pi.pain.leaveMonochromeMode();
723 pi.pain.rectangle(x, y - dim.asc, dim.wid,
724 dim.height(), Color_mathmacroframe);
726 d->expanded_.draw(pi, expx, expy);
729 drawMarkers(pi, x, y);
733 // edit mode changed?
734 if (d->editing_[pi.base.bv] != editMode(pi.base.bv))
735 pi.base.bv->cursor().screenUpdateFlags(Update::SinglePar);
739 void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
741 // We may have 0 arguments, but InsetMathNest requires at least one.
743 InsetMathNest::drawSelection(pi, x, y);
747 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode, int appetite)
749 if (d->displayMode_ != mode) {
750 // transfer name if changing from or to DISPLAY_UNFOLDED
751 if (mode == DISPLAY_UNFOLDED) {
753 asArray(d->name_, cell(0));
754 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
755 d->name_ = asString(cell(0));
759 d->displayMode_ = mode;
760 d->needsUpdate_ = true;
763 // the interactive init mode is non-greedy by default
765 d->appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
767 d->appetite_ = size_t(appetite);
771 MathMacro::DisplayMode MathMacro::computeDisplayMode() const
773 if (d->nextFoldMode_ == true && d->macro_ && !d->macro_->locked())
774 return DISPLAY_NORMAL;
776 return DISPLAY_UNFOLDED;
780 bool MathMacro::validName() const
782 docstring n = name();
787 // converting back and force doesn't swallow anything?
790 if (asString(ma) != n)
794 for (size_t i = 0; i<n.size(); ++i) {
795 if (!(n[i] >= 'a' && n[i] <= 'z')
796 && !(n[i] >= 'A' && n[i] <= 'Z')
805 size_t MathMacro::arity() const
807 if (d->displayMode_ == DISPLAY_NORMAL )
808 return cells_.size();
814 size_t MathMacro::optionals() const
816 return d->optionals_;
820 void MathMacro::setOptionals(int n)
822 if (n <= int(nargs()))
827 size_t MathMacro::appetite() const
833 MathClass MathMacro::mathClass() const
835 // This can be just a heuristic, since it is only considered for display
836 // when the macro is not linearised. Therefore it affects:
837 // * The spacing of the inset while being edited,
838 // * Intelligent splitting
839 // * Cursor word movement (Ctrl-Arrow).
840 if (MacroData const * m = macroBackup()) {
841 // If it is a global macro and is defined explicitly
843 MathClass mc = string_to_class(m->symbol()->extra);
844 if (mc != MC_UNKNOWN)
848 // Otherwise guess from the expanded macro
849 return d->expanded_.mathClass();
853 InsetMath::mode_type MathMacro::currentMode() const
855 // There is no way to guess the mode of user defined macros, so they are
856 // always assumed to be mathmode. Only the global macros defined in
857 // lib/symbols may be textmode.
858 mode_type mode = modeToEnsure();
859 return (mode == UNDECIDED_MODE) ? MATH_MODE : mode;
863 InsetMath::mode_type MathMacro::modeToEnsure() const
865 // User defined macros can be either text mode or math mode for output and
866 // display. There is no way to guess. For global macros defined in
867 // lib/symbols, we ensure textmode if flagged as such, otherwise we ensure
869 if (MacroData const * m = macroBackup())
871 return (m->symbol()->extra == "textmode") ? TEXT_MODE : MATH_MODE;
872 return UNDECIDED_MODE;
876 MacroData const * MathMacro::macroBackup() const
879 return &d->macroBackup_;
880 if (MacroData const * data = MacroTable::globalMacros().get(name()))
886 void MathMacro::validate(LaTeXFeatures & features) const
888 // Immediately after a document is loaded, in some cases the MacroData
889 // of the global macros defined in the lib/symbols file may still not
890 // be known to the macro machinery because it will be set only after
891 // the first call to updateMacros(). This is not a problem unless
892 // instant preview is on for math, in which case we will be missing
893 // the corresponding requirements.
894 // In this case, we get the required info from the global macro table.
895 if (!d->requires_.empty())
896 features.require(d->requires_);
897 else if (!d->macro_) {
898 // Update requires for known global macros.
899 MacroData const * data = MacroTable::globalMacros().get(name());
900 if (data && !data->requires().empty())
901 features.require(data->requires());
904 if (name() == "binom")
905 features.require("binom");
907 // validate the cells and the definition
908 if (displayMode() == DISPLAY_NORMAL) {
909 d->definition_.validate(features);
910 InsetMathNest::validate(features);
915 void MathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
917 cur.screenUpdateFlags(Update::SinglePar);
918 InsetMathNest::edit(cur, front, entry_from);
922 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
924 // We may have 0 arguments, but InsetMathNest requires at least one.
926 cur.screenUpdateFlags(Update::SinglePar);
927 return InsetMathNest::editXY(cur, x, y);
933 void MathMacro::removeArgument(Inset::pos_type pos) {
934 if (d->displayMode_ == DISPLAY_NORMAL) {
935 LASSERT(size_t(pos) < cells_.size(), return);
936 cells_.erase(cells_.begin() + pos);
937 if (size_t(pos) < d->attachedArgsNum_)
938 --d->attachedArgsNum_;
939 if (size_t(pos) < d->optionals_) {
943 d->needsUpdate_ = true;
948 void MathMacro::insertArgument(Inset::pos_type pos) {
949 if (d->displayMode_ == DISPLAY_NORMAL) {
950 LASSERT(size_t(pos) <= cells_.size(), return);
951 cells_.insert(cells_.begin() + pos, MathData());
952 if (size_t(pos) < d->attachedArgsNum_)
953 ++d->attachedArgsNum_;
954 if (size_t(pos) < d->optionals_)
957 d->needsUpdate_ = true;
962 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
964 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
967 // strip off empty cells, but not more than arity-attachedArgsNum_
970 for (i = cells_.size(); i > d->attachedArgsNum_; --i)
971 if (!cell(i - 1).empty()) break;
975 d->attachedArgsNum_ = 0;
976 d->expanded_ = MathData();
979 d->needsUpdate_ = true;
983 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
985 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
987 d->attachedArgsNum_ = args.size();
988 cells_.resize(arity);
989 d->expanded_ = MathData();
990 d->optionals_ = optionals;
992 d->needsUpdate_ = true;
996 bool MathMacro::idxFirst(Cursor & cur) const
998 cur.screenUpdateFlags(Update::SinglePar);
999 return InsetMathNest::idxFirst(cur);
1003 bool MathMacro::idxLast(Cursor & cur) const
1005 cur.screenUpdateFlags(Update::SinglePar);
1006 return InsetMathNest::idxLast(cur);
1010 bool MathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
1012 if (d->displayMode_ == DISPLAY_UNFOLDED) {
1013 docstring const & unfolded_name = name();
1014 if (unfolded_name != d->name_) {
1015 // The macro name was changed
1016 Cursor inset_cursor = old;
1017 int macroSlice = inset_cursor.find(this);
1018 // returning true means the cursor is "now" invalid,
1020 LASSERT(macroSlice != -1, return true);
1021 inset_cursor.cutOff(macroSlice);
1022 inset_cursor.recordUndoInset();
1024 inset_cursor.cell().erase(inset_cursor.pos());
1025 inset_cursor.cell().insert(inset_cursor.pos(),
1026 createInsetMath(unfolded_name, cur.buffer()));
1028 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
1032 cur.screenUpdateFlags(Update::Force);
1033 return InsetMathNest::notifyCursorLeaves(old, cur);
1037 void MathMacro::fold(Cursor & cur)
1039 if (!d->nextFoldMode_) {
1040 d->nextFoldMode_ = true;
1041 cur.screenUpdateFlags(Update::SinglePar);
1046 void MathMacro::unfold(Cursor & cur)
1048 if (d->nextFoldMode_) {
1049 d->nextFoldMode_ = false;
1050 cur.screenUpdateFlags(Update::SinglePar);
1055 bool MathMacro::folded() const
1057 return d->nextFoldMode_;
1061 void MathMacro::write(WriteStream & os) const
1063 mode_type mode = modeToEnsure();
1064 bool textmode_macro = mode == TEXT_MODE;
1065 bool needs_mathmode = mode == MATH_MODE;
1066 MathEnsurer ensurer(os, needs_mathmode, true, textmode_macro);
1069 if (d->displayMode_ != DISPLAY_NORMAL) {
1070 os << "\\" << name();
1071 if (name().size() != 1 || isAlphaASCII(name()[0]))
1072 os.pendingSpace(true);
1077 // we should be ok to continue even if this fails.
1080 // We may already be in the argument of a macro
1081 bool const inside_macro = os.insideMacro();
1082 os.insideMacro(true);
1084 // Enclose in braces to avoid latex errors with xargs if we have
1085 // optional arguments and are in the optional argument of a macro
1086 if (d->optionals_ && inside_macro)
1089 // Always protect macros in a fragile environment
1093 os << "\\" << name();
1096 // Optional arguments:
1097 // First find last non-empty optional argument
1098 idx_type emptyOptFrom = 0;
1100 for (; i < cells_.size() && i < d->optionals_; ++i) {
1101 if (!cell(i).empty())
1102 emptyOptFrom = i + 1;
1105 // print out optionals
1106 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
1108 os << "[" << cell(i) << "]";
1111 // skip the tailing empty optionals
1114 // Print remaining arguments
1115 for (; i < cells_.size(); ++i) {
1116 if (cell(i).size() == 1
1117 && cell(i)[0].nucleus()->asCharInset()
1118 && isASCII(cell(i)[0].nucleus()->asCharInset()->getChar())) {
1123 os << "{" << cell(i) << "}";
1127 // Close the opened brace or add space if there was no argument
1128 if (d->optionals_ && inside_macro)
1131 os.pendingSpace(true);
1133 os.insideMacro(inside_macro);
1137 void MathMacro::maple(MapleStream & os) const
1139 lyx::maple(d->expanded_, os);
1143 void MathMacro::maxima(MaximaStream & os) const
1145 lyx::maxima(d->expanded_, os);
1149 void MathMacro::mathematica(MathematicaStream & os) const
1151 lyx::mathematica(d->expanded_, os);
1155 void MathMacro::mathmlize(MathStream & os) const
1157 // macro_ is 0 if this is an unknown macro
1158 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1160 docstring const xmlname = d->macro_->xmlname();
1161 if (!xmlname.empty()) {
1162 char const * type = d->macro_->MathMLtype();
1163 os << '<' << type << "> " << xmlname << " </"
1168 if (d->expanded_.empty()) {
1169 // this means that we do not recognize the macro
1170 throw MathExportException();
1176 void MathMacro::htmlize(HtmlStream & os) const
1178 // macro_ is 0 if this is an unknown macro
1179 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1181 docstring const xmlname = d->macro_->xmlname();
1182 if (!xmlname.empty()) {
1183 os << ' ' << xmlname << ' ';
1187 if (d->expanded_.empty()) {
1188 // this means that we do not recognize the macro
1189 throw MathExportException();
1195 void MathMacro::octave(OctaveStream & os) const
1197 lyx::octave(d->expanded_, os);
1201 void MathMacro::infoize(odocstream & os) const
1203 os << bformat(_("Macro: %1$s"), name());
1207 void MathMacro::infoize2(odocstream & os) const
1209 os << bformat(_("Macro: %1$s"), name());
1213 bool MathMacro::completionSupported(Cursor const & cur) const
1215 if (displayMode() != DISPLAY_UNFOLDED)
1216 return InsetMathNest::completionSupported(cur);
1218 return lyxrc.completion_popup_math
1219 && displayMode() == DISPLAY_UNFOLDED
1220 && cur.bv().cursor().pos() == int(name().size());
1224 bool MathMacro::inlineCompletionSupported(Cursor const & cur) const
1226 if (displayMode() != DISPLAY_UNFOLDED)
1227 return InsetMathNest::inlineCompletionSupported(cur);
1229 return lyxrc.completion_inline_math
1230 && displayMode() == DISPLAY_UNFOLDED
1231 && cur.bv().cursor().pos() == int(name().size());
1235 bool MathMacro::automaticInlineCompletion() const
1237 if (displayMode() != DISPLAY_UNFOLDED)
1238 return InsetMathNest::automaticInlineCompletion();
1240 return lyxrc.completion_inline_math;
1244 bool MathMacro::automaticPopupCompletion() const
1246 if (displayMode() != DISPLAY_UNFOLDED)
1247 return InsetMathNest::automaticPopupCompletion();
1249 return lyxrc.completion_popup_math;
1253 CompletionList const *
1254 MathMacro::createCompletionList(Cursor const & cur) const
1256 if (displayMode() != DISPLAY_UNFOLDED)
1257 return InsetMathNest::createCompletionList(cur);
1259 return new MathCompletionList(cur.bv().cursor());
1263 docstring MathMacro::completionPrefix(Cursor const & cur) const
1265 if (displayMode() != DISPLAY_UNFOLDED)
1266 return InsetMathNest::completionPrefix(cur);
1268 if (!completionSupported(cur))
1271 return "\\" + name();
1275 bool MathMacro::insertCompletion(Cursor & cur, docstring const & s,
1278 if (displayMode() != DISPLAY_UNFOLDED)
1279 return InsetMathNest::insertCompletion(cur, s, finished);
1281 if (!completionSupported(cur))
1284 // append completion
1285 docstring newName = name() + s;
1286 asArray(newName, cell(0));
1287 cur.bv().cursor().pos() = name().size();
1288 cur.screenUpdateFlags(Update::SinglePar);
1292 cur.bv().cursor().pop();
1293 ++cur.bv().cursor().pos();
1294 cur.screenUpdateFlags(Update::SinglePar);
1301 void MathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
1302 Dimension & dim) const
1304 if (displayMode() != DISPLAY_UNFOLDED)
1305 InsetMathNest::completionPosAndDim(cur, x, y, dim);
1307 // get inset dimensions
1308 dim = cur.bv().coordCache().insets().dim(this);
1309 // FIXME: these 3 are no accurate, but should depend on the font.
1310 // Now the popup jumps down if you enter a char with descent > 0.
1316 = cur.bv().coordCache().insets().xy(this);