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/textutils.h"
46 using namespace lyx::support;
52 /// A proxy for the macro values
53 class ArgumentProxy : public InsetMath {
56 ArgumentProxy(MathMacro * mathMacro, size_t idx)
57 : mathMacro_(mathMacro), idx_(idx) {}
59 ArgumentProxy(MathMacro * mathMacro, size_t idx, docstring const & def)
60 : mathMacro_(mathMacro), idx_(idx)
65 void setOwner(MathMacro * mathMacro) { mathMacro_ = mathMacro; }
67 MathMacro const * owner() { return mathMacro_; }
69 InsetCode lyxCode() const { return ARGUMENT_PROXY_CODE; }
71 bool addToMathRow(MathRow & mrow, MetricsInfo & mi) const
73 // macro arguments are in macros
74 LATTEST(mi.base.macro_nesting > 0);
75 if (mi.base.macro_nesting == 1)
76 mi.base.macro_nesting = 0;
78 MathRow::Element e_beg(MathRow::BEG_ARG, mi);
79 e_beg.macro = mathMacro_;
80 e_beg.ar = &mathMacro_->cell(idx_);
81 mrow.push_back(e_beg);
83 mathMacro_->macro()->unlock();
84 bool has_contents = mathMacro_->cell(idx_).addToMathRow(mrow, mi);
85 mathMacro_->macro()->lock();
87 // if there was no contents, and the contents is editable,
88 // then we insert a box instead.
89 if (!has_contents && mi.base.macro_nesting == 0) {
90 MathRow::Element e(MathRow::BOX, mi);
91 e.color = Color_mathline;
96 if (mi.base.macro_nesting == 0)
97 mi.base.macro_nesting = 1;
99 MathRow::Element e_end(MathRow::END_ARG, mi);
100 e_end.macro = mathMacro_;
101 e_end.ar = &mathMacro_->cell(idx_);
103 mrow.push_back(e_end);
108 void metrics(MetricsInfo & mi, Dimension & dim) const {
109 // macro arguments are in macros
110 LATTEST(mi.base.macro_nesting > 0);
111 if (mi.base.macro_nesting == 1)
112 mi.base.macro_nesting = 0;
114 mathMacro_->macro()->unlock();
115 mathMacro_->cell(idx_).metrics(mi, dim);
117 if (!mathMacro_->editMetrics(mi.base.bv)
118 && mathMacro_->cell(idx_).empty())
119 def_.metrics(mi, dim);
121 mathMacro_->macro()->lock();
122 if (mi.base.macro_nesting == 0)
123 mi.base.macro_nesting = 1;
125 // write(), normalize(), infoize() and infoize2() are not needed since
126 // MathMacro uses the definition and not the expanded cells.
128 void maple(MapleStream & ms) const { ms << mathMacro_->cell(idx_); }
130 void maxima(MaximaStream & ms) const { ms << mathMacro_->cell(idx_); }
132 void mathematica(MathematicaStream & ms) const { ms << mathMacro_->cell(idx_); }
134 void mathmlize(MathStream & ms) const { ms << mathMacro_->cell(idx_); }
136 void htmlize(HtmlStream & ms) const { ms << mathMacro_->cell(idx_); }
138 void octave(OctaveStream & os) const { os << mathMacro_->cell(idx_); }
140 void draw(PainterInfo & pi, int x, int y) const {
141 LATTEST(pi.base.macro_nesting > 0);
142 if (pi.base.macro_nesting == 1)
143 pi.base.macro_nesting = 0;
145 if (mathMacro_->editMetrics(pi.base.bv)) {
146 // The only way a ArgumentProxy can appear is in a cell of the
147 // MathMacro. Moreover the cells are only drawn in the DISPLAY_FOLDED
148 // mode and then, if the macro is edited the monochrome
149 // mode is entered by the MathMacro before calling the cells' draw
150 // method. Then eventually this code is reached and the proxy leaves
151 // monochrome mode temporarely. Hence, if it is not in monochrome
152 // here (and the assert triggers in pain.leaveMonochromeMode())
154 pi.pain.leaveMonochromeMode();
155 mathMacro_->cell(idx_).draw(pi, x, y);
156 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
157 } else if (mathMacro_->cell(idx_).empty()) {
158 mathMacro_->cell(idx_).setXY(*pi.base.bv, x, y);
161 mathMacro_->cell(idx_).draw(pi, x, y);
163 if (pi.base.macro_nesting == 0)
164 pi.base.macro_nesting = 1;
167 size_t idx() const { return idx_; }
169 int kerning(BufferView const * bv) const
171 if (mathMacro_->editMetrics(bv)
172 || !mathMacro_->cell(idx_).empty())
173 return mathMacro_->cell(idx_).kerning(bv);
175 return def_.kerning(bv);
180 Inset * clone() const
182 return new ArgumentProxy(*this);
185 MathMacro * mathMacro_;
193 /// Private implementation of MathMacro
194 class MathMacro::Private {
196 Private(Buffer * buf, docstring const & name)
197 : name_(name), displayMode_(DISPLAY_INIT),
198 expanded_(buf), definition_(buf), attachedArgsNum_(0),
199 optionals_(0), nextFoldMode_(true), macroBackup_(buf),
200 macro_(0), needsUpdate_(false), isUpdating_(false),
204 /// Update the pointers to our owner of all expanded macros.
205 /// This needs to be called every time a copy of the owner is created
207 void updateChildren(MathMacro * owner);
208 /// Recursively update the pointers of all expanded macros
209 /// appearing in the arguments of the current macro
210 void updateNestedChildren(MathMacro * owner, InsetMathNest * ni);
213 /// current display mode
214 DisplayMode displayMode_;
215 /// expanded macro with ArgumentProxies
217 /// macro definition with #1,#2,.. insets
218 MathData definition_;
219 /// number of arguments that were really attached
220 size_t attachedArgsNum_;
221 /// optional argument attached? (only in DISPLAY_NORMAL mode)
223 /// fold mode to be set in next metrics call?
225 /// if macro_ == true, then here is a copy of the macro
226 /// don't use it for locking
227 MacroData macroBackup_;
228 /// if macroNotFound_ == false, then here is a reference to the macro
229 /// this might invalidate after metrics was called
230 MacroData const * macro_;
232 mutable std::map<BufferView const *, bool> editing_;
234 std::string requires_;
235 /// update macro representation
239 /// maximal number of arguments the macro is greedy for
244 void MathMacro::Private::updateChildren(MathMacro * owner)
246 for (size_t i = 0; i < expanded_.size(); ++i) {
247 ArgumentProxy * p = dynamic_cast<ArgumentProxy *>(expanded_[i].nucleus());
251 InsetMathNest * ni = expanded_[i].nucleus()->asNestInset();
253 updateNestedChildren(owner, ni);
257 // The macro_ pointer is updated when MathData::metrics() is
258 // called. However, when instant preview is on or the macro is
259 // not on screen, MathData::metrics() is not called and we may
260 // have a dangling pointer. As a safety measure, when a macro
261 // is copied, always let macro_ point to the backup copy of the
262 // MacroData structure. This backup is updated every time the
263 // macro is changed, so it will not become stale.
264 macro_ = ¯oBackup_;
269 void MathMacro::Private::updateNestedChildren(MathMacro * owner, InsetMathNest * ni)
271 for (size_t i = 0; i < ni->nargs(); ++i) {
272 MathData & ar = ni->cell(i);
273 for (size_t j = 0; j < ar.size(); ++j) {
274 ArgumentProxy * ap = dynamic_cast
275 <ArgumentProxy *>(ar[j].nucleus());
277 MathMacro::Private * md = ap->owner()->d;
279 md->macro_ = &md->macroBackup_;
282 InsetMathNest * imn = ar[j].nucleus()->asNestInset();
284 updateNestedChildren(owner, imn);
290 MathMacro::MathMacro(Buffer * buf, docstring const & name)
291 : InsetMathNest(buf, 0), d(new Private(buf, name))
295 MathMacro::MathMacro(MathMacro const & that)
296 : InsetMathNest(that), d(new Private(*that.d))
298 setBuffer(*that.buffer_);
299 d->updateChildren(this);
303 MathMacro & MathMacro::operator=(MathMacro const & that)
307 InsetMathNest::operator=(that);
309 d->updateChildren(this);
314 MathMacro::~MathMacro()
320 bool MathMacro::addToMathRow(MathRow & mrow, MetricsInfo & mi) const
322 // set edit mode for which we will have calculated row.
323 // This is the same as what is done in metrics().
324 d->editing_[mi.base.bv] = editMode(mi.base.bv);
326 if (displayMode() != MathMacro::DISPLAY_NORMAL
327 || d->editing_[mi.base.bv])
328 return InsetMath::addToMathRow(mrow, mi);
330 MathRow::Element e_beg(MathRow::BEG_MACRO, mi);
332 mrow.push_back(e_beg);
334 ++mi.base.macro_nesting;
337 bool has_contents = d->expanded_.addToMathRow(mrow, mi);
340 // if there was no contents and the array is editable, then we
341 // insert a grey box instead.
342 if (!has_contents && mi.base.macro_nesting == 1) {
343 MathRow::Element e(MathRow::BOX, mi);
344 e.color = Color_mathmacroblend;
349 --mi.base.macro_nesting;
351 MathRow::Element e_end(MathRow::END_MACRO, mi);
353 mrow.push_back(e_end);
359 Inset * MathMacro::clone() const
361 MathMacro * copy = new MathMacro(*this);
362 copy->d->needsUpdate_ = true;
363 //copy->d->expanded_.clear();
368 void MathMacro::normalize(NormalStream & os) const
370 os << "[macro " << name();
371 for (size_t i = 0; i < nargs(); ++i)
372 os << ' ' << cell(i);
377 MathMacro::DisplayMode MathMacro::displayMode() const
379 return d->displayMode_;
383 bool MathMacro::extraBraces() const
385 return d->displayMode_ == DISPLAY_NORMAL && arity() > 0;
389 docstring MathMacro::name() const
391 if (d->displayMode_ == DISPLAY_UNFOLDED)
392 return asString(cell(0));
398 docstring MathMacro::macroName() const
404 void MathMacro::cursorPos(BufferView const & bv,
405 CursorSlice const & sl, bool boundary, int & x, int & y) const
407 // We may have 0 arguments, but InsetMathNest requires at least one.
409 InsetMathNest::cursorPos(bv, sl, boundary, x, y);
413 bool MathMacro::editMode(BufferView const * bv) const {
414 // find this in cursor trace
415 Cursor const & cur = bv->cursor();
416 for (size_t i = 0; i != cur.depth(); ++i)
417 if (&cur[i].inset() == this) {
418 // look if there is no other macro in edit mode above
420 for (; i != cur.depth(); ++i) {
421 InsetMath * im = cur[i].asInsetMath();
423 MathMacro const * macro = im->asMacro();
424 if (macro && macro->displayMode() == DISPLAY_NORMAL)
429 // ok, none found, I am the highest one
437 MacroData const * MathMacro::macro() const
443 bool MathMacro::editMetrics(BufferView const * bv) const
445 return d->editing_[bv];
449 void MathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
451 // the macro contents is not editable (except the arguments)
452 ++mi.base.macro_nesting;
454 // set edit mode for which we will have calculated metrics. But only
455 d->editing_[mi.base.bv] = editMode(mi.base.bv);
457 // calculate new metrics according to display mode
458 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
459 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
460 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
461 cell(0).metrics(mi, dim);
463 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
464 dim.wid += bsdim.width() + 1;
465 dim.asc = max(bsdim.ascent(), dim.ascent());
466 dim.des = max(bsdim.descent(), dim.descent());
467 metricsMarkers(mi, dim);
468 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
469 && d->editing_[mi.base.bv]) {
470 // Macro will be edited in a old-style list mode here:
474 FontInfo labelFont = sane_font;
475 math_font_max_dim(labelFont, fontDim.asc, fontDim.des);
477 // get dimension of components of list view
479 nameDim.wid = mathed_string_width(mi.base.font, from_ascii("Macro \\") + name() + ": ");
480 nameDim.asc = fontDim.asc;
481 nameDim.des = fontDim.des;
484 argDim.wid = mathed_string_width(labelFont, from_ascii("#9: "));
485 argDim.asc = fontDim.asc;
486 argDim.des = fontDim.des;
489 d->definition_.metrics(mi, defDim);
492 dim.wid = nameDim.wid + defDim.wid;
493 dim.asc = max(nameDim.asc, defDim.asc);
494 dim.des = max(nameDim.des, defDim.des);
496 for (idx_type i = 0; i < nargs(); ++i) {
498 cell(i).metrics(mi, cdim);
499 dim.des += max(argDim.height(), cdim.height()) + 1;
500 dim.wid = max(dim.wid, argDim.wid + cdim.wid);
503 // make space for box and markers, 2 pixels
507 metricsMarkers2(mi, dim);
511 // calculate metrics, hoping that all cells are seen
513 d->expanded_.metrics(mi, dim);
515 // otherwise do a manual metrics call
516 CoordCache & coords = mi.base.bv->coordCache();
517 for (idx_type i = 0; i < nargs(); ++i) {
518 if (!coords.getArrays().hasDim(&cell(i))) {
520 cell(i).metrics(mi, tdim);
525 // calculate dimension with label while editing
526 if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX
527 && d->editing_[mi.base.bv]) {
528 FontInfo font = mi.base.font;
529 augmentFont(font, "lyxtex");
531 mathed_string_dim(font, name(), namedim);
533 dim.wid += 2 + namedim.wid + 2 + 2;
534 dim.asc = max(dim.asc, namedim.asc) + 2;
535 dim.des = max(dim.des, namedim.des) + 2;
537 dim.wid = max(1 + namedim.wid + 1, 2 + dim.wid + 2);
538 dim.asc += 1 + namedim.height() + 1;
543 // restore macro nesting
544 --mi.base.macro_nesting;
548 int MathMacro::kerning(BufferView const * bv) const {
549 if (d->displayMode_ == DISPLAY_NORMAL && !d->editing_[bv])
550 return d->expanded_.kerning(bv);
556 void MathMacro::updateMacro(MacroContext const & mc)
559 d->macro_ = mc.get(name());
560 if (d->macro_ && d->macroBackup_ != *d->macro_) {
561 d->macroBackup_ = *d->macro_;
562 d->needsUpdate_ = true;
570 class MathMacro::UpdateLocker
573 explicit UpdateLocker(MathMacro & mm) : mac(mm)
575 mac.d->isUpdating_ = true;
577 ~UpdateLocker() { mac.d->isUpdating_ = false; }
581 /** Avoid wrong usage of UpdateLocker.
582 To avoid wrong usage:
583 UpdateLocker(...); // wrong
584 UpdateLocker locker(...); // right
586 #define UpdateLocker(x) unnamed_UpdateLocker;
587 // Tip gotten from Bobby Schmidt's column in C/C++ Users Journal
590 void MathMacro::updateRepresentation(Cursor * cur, MacroContext const & mc,
593 // block recursive calls (bug 8999)
597 UpdateLocker locker(*this);
604 d->requires_ = d->macro_->requires();
607 // non-normal mode? We are done!
608 || (d->displayMode_ != DISPLAY_NORMAL))
611 d->needsUpdate_ = false;
613 // get default values of macro
614 vector<docstring> const & defaults = d->macro_->defaults();
616 // create MathMacroArgumentValue objects pointing to the cells of the macro
617 vector<MathData> values(nargs());
618 for (size_t i = 0; i < nargs(); ++i) {
619 ArgumentProxy * proxy;
620 if (i < defaults.size())
621 proxy = new ArgumentProxy(this, i, defaults[i]);
623 proxy = new ArgumentProxy(this, i);
624 values[i].insert(0, MathAtom(proxy));
626 // expanding macro with the values
627 // Only update the argument macros if anything was expanded, otherwise
628 // we would get an endless loop (bug 9140). UpdateLocker does not work
629 // in this case, since MacroData::expand() creates new MathMacro
630 // objects, so this would be a different recursion path than the one
631 // protected by UpdateLocker.
632 if (d->macro_->expand(values, d->expanded_)) {
633 if (utype == OutputUpdate && !d->expanded_.empty())
634 d->expanded_.updateMacros(cur, mc, utype);
636 // get definition for list edit mode
637 docstring const & display = d->macro_->display();
638 asArray(display.empty() ? d->macro_->definition() : display,
639 d->definition_, Parse::QUIET);
643 void MathMacro::draw(PainterInfo & pi, int x, int y) const
645 Dimension const dim = dimension(*pi.base.bv);
647 setPosCache(pi, x, y);
651 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
652 Changer dummy = pi.base.changeFontSet("lyxtex");
653 pi.pain.text(x, y, from_ascii("\\") + name(), pi.base.font);
654 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
655 Changer dummy = pi.base.changeFontSet("lyxtex");
656 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
657 x += mathed_string_width(pi.base.font, from_ascii("\\")) + 1;
658 cell(0).draw(pi, x, y);
659 drawMarkers(pi, expx, expy);
660 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
661 && d->editing_[pi.base.bv]) {
662 // Macro will be edited in a old-style list mode here:
664 CoordCache const & coords = pi.base.bv->coordCache();
665 FontInfo const & labelFont = sane_font;
667 // markers and box needs two pixels
670 // get maximal font height
672 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
675 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
676 pi.pain.text(x, y, label, labelFont);
677 x += mathed_string_width(labelFont, label);
680 d->definition_.draw(pi, x, y);
681 Dimension const & defDim = coords.getArrays().dim(&d->definition_);
682 y += max(fontDim.des, defDim.des);
685 docstring str = from_ascii("#9");
686 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
687 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
689 for (idx_type i = 0; i < nargs(); ++i) {
691 Dimension const & cdim = coords.getArrays().dim(&cell(i));
693 y += max(fontDim.asc, cdim.asc) + 1;
697 pi.pain.text(x, y, str, labelFont);
699 pi.pain.text(x, y, from_ascii(":"), labelFont);
703 cell(i).draw(pi, x, y);
706 y += max(fontDim.des, cdim.des);
709 pi.pain.rectangle(expx + 1, expy - dim.asc + 1, dim.wid - 3,
710 dim.height() - 2, Color_mathmacroframe);
711 drawMarkers2(pi, expx, expy);
713 // the macro contents is not editable (except the arguments)
714 ++pi.base.macro_nesting;
716 bool drawBox = lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX;
717 bool upshape = currentMode() == TEXT_MODE;
718 Changer dummy = pi.base.font.changeShape(upshape ? UP_SHAPE
719 : pi.base.font.shape());
722 for (size_t i = 0; i < nargs(); ++i)
723 cell(i).setXY(*pi.base.bv, x, y);
725 if (drawBox && d->editing_[pi.base.bv]) {
726 // draw header and rectangle around
727 FontInfo font = pi.base.font;
728 augmentFont(font, "lyxtex");
729 font.setSize(FONT_SIZE_TINY);
730 font.setColor(Color_mathmacrolabel);
732 mathed_string_dim(font, name(), namedim);
734 pi.pain.fillRectangle(x, y - dim.asc, dim.wid, 1 + namedim.height() + 1, Color_mathmacrobg);
735 pi.pain.text(x + 1, y - dim.asc + namedim.asc + 2, name(), font);
736 expx += (dim.wid - d->expanded_.dimension(*pi.base.bv).width()) / 2;
739 if (d->editing_[pi.base.bv]) {
740 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
741 d->expanded_.draw(pi, expx, expy);
742 pi.pain.leaveMonochromeMode();
745 pi.pain.rectangle(x, y - dim.asc, dim.wid,
746 dim.height(), Color_mathmacroframe);
748 d->expanded_.draw(pi, expx, expy);
750 --pi.base.macro_nesting;
753 drawMarkers(pi, x, y);
757 // edit mode changed?
758 if (d->editing_[pi.base.bv] != editMode(pi.base.bv))
759 pi.base.bv->cursor().screenUpdateFlags(Update::SinglePar);
763 void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
765 // We may have 0 arguments, but InsetMathNest requires at least one.
767 InsetMathNest::drawSelection(pi, x, y);
771 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode, int appetite)
773 if (d->displayMode_ != mode) {
774 // transfer name if changing from or to DISPLAY_UNFOLDED
775 if (mode == DISPLAY_UNFOLDED) {
777 asArray(d->name_, cell(0));
778 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
779 d->name_ = asString(cell(0));
783 d->displayMode_ = mode;
784 d->needsUpdate_ = true;
787 // the interactive init mode is non-greedy by default
789 d->appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
791 d->appetite_ = size_t(appetite);
795 MathMacro::DisplayMode MathMacro::computeDisplayMode() const
797 if (d->nextFoldMode_ == true && d->macro_ && !d->macro_->locked())
798 return DISPLAY_NORMAL;
800 return DISPLAY_UNFOLDED;
804 bool MathMacro::validName() const
806 docstring n = name();
811 // converting back and force doesn't swallow anything?
814 if (asString(ma) != n)
818 for (size_t i = 0; i<n.size(); ++i) {
819 if (!(n[i] >= 'a' && n[i] <= 'z')
820 && !(n[i] >= 'A' && n[i] <= 'Z')
829 size_t MathMacro::arity() const
831 if (d->displayMode_ == DISPLAY_NORMAL )
832 return cells_.size();
838 size_t MathMacro::optionals() const
840 return d->optionals_;
844 void MathMacro::setOptionals(int n)
846 if (n <= int(nargs()))
851 size_t MathMacro::appetite() const
857 InsetMath::mode_type MathMacro::currentMode() const
859 // User defined macros are always assumed to be mathmode macros.
860 // Only the global macros defined in lib/symbols may be textmode.
862 MacroData const * data = MacroTable::globalMacros().get(name());
863 bool textmode = data && data->symbol() && data->symbol()->extra == "textmode";
864 return textmode ? TEXT_MODE : MATH_MODE;
868 void MathMacro::validate(LaTeXFeatures & features) const
870 // Immediately after a document is loaded, in some cases the MacroData
871 // of the global macros defined in the lib/symbols file may still not
872 // be known to the macro machinery because it will be set only after
873 // the first call to updateMacros(). This is not a problem unless
874 // instant preview is on for math, in which case we will be missing
875 // the corresponding requirements.
876 // In this case, we get the required info from the global macro table.
877 if (!d->requires_.empty())
878 features.require(d->requires_);
879 else if (!d->macro_) {
880 // Update requires for known global macros.
881 MacroData const * data = MacroTable::globalMacros().get(name());
882 if (data && !data->requires().empty())
883 features.require(data->requires());
886 if (name() == "binom")
887 features.require("binom");
889 // validate the cells and the definition
890 if (displayMode() == DISPLAY_NORMAL) {
891 d->definition_.validate(features);
892 InsetMathNest::validate(features);
897 void MathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
899 cur.screenUpdateFlags(Update::SinglePar);
900 InsetMathNest::edit(cur, front, entry_from);
904 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
906 // We may have 0 arguments, but InsetMathNest requires at least one.
908 cur.screenUpdateFlags(Update::SinglePar);
909 return InsetMathNest::editXY(cur, x, y);
915 void MathMacro::removeArgument(Inset::pos_type pos) {
916 if (d->displayMode_ == DISPLAY_NORMAL) {
917 LASSERT(size_t(pos) < cells_.size(), return);
918 cells_.erase(cells_.begin() + pos);
919 if (size_t(pos) < d->attachedArgsNum_)
920 --d->attachedArgsNum_;
921 if (size_t(pos) < d->optionals_) {
925 d->needsUpdate_ = true;
930 void MathMacro::insertArgument(Inset::pos_type pos) {
931 if (d->displayMode_ == DISPLAY_NORMAL) {
932 LASSERT(size_t(pos) <= cells_.size(), return);
933 cells_.insert(cells_.begin() + pos, MathData());
934 if (size_t(pos) < d->attachedArgsNum_)
935 ++d->attachedArgsNum_;
936 if (size_t(pos) < d->optionals_)
939 d->needsUpdate_ = true;
944 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
946 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
949 // strip off empty cells, but not more than arity-attachedArgsNum_
952 for (i = cells_.size(); i > d->attachedArgsNum_; --i)
953 if (!cell(i - 1).empty()) break;
957 d->attachedArgsNum_ = 0;
958 d->expanded_ = MathData();
961 d->needsUpdate_ = true;
965 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
967 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
969 d->attachedArgsNum_ = args.size();
970 cells_.resize(arity);
971 d->expanded_ = MathData();
972 d->optionals_ = optionals;
974 d->needsUpdate_ = true;
978 bool MathMacro::idxFirst(Cursor & cur) const
980 cur.screenUpdateFlags(Update::SinglePar);
981 return InsetMathNest::idxFirst(cur);
985 bool MathMacro::idxLast(Cursor & cur) const
987 cur.screenUpdateFlags(Update::SinglePar);
988 return InsetMathNest::idxLast(cur);
992 bool MathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
994 if (d->displayMode_ == DISPLAY_UNFOLDED) {
995 docstring const & unfolded_name = name();
996 if (unfolded_name != d->name_) {
997 // The macro name was changed
998 Cursor inset_cursor = old;
999 int macroSlice = inset_cursor.find(this);
1000 // returning true means the cursor is "now" invalid,
1002 LASSERT(macroSlice != -1, return true);
1003 inset_cursor.cutOff(macroSlice);
1004 inset_cursor.recordUndoInset();
1006 inset_cursor.cell().erase(inset_cursor.pos());
1007 inset_cursor.cell().insert(inset_cursor.pos(),
1008 createInsetMath(unfolded_name, cur.buffer()));
1010 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
1014 cur.screenUpdateFlags(Update::Force);
1015 return InsetMathNest::notifyCursorLeaves(old, cur);
1019 void MathMacro::fold(Cursor & cur)
1021 if (!d->nextFoldMode_) {
1022 d->nextFoldMode_ = true;
1023 cur.screenUpdateFlags(Update::SinglePar);
1028 void MathMacro::unfold(Cursor & cur)
1030 if (d->nextFoldMode_) {
1031 d->nextFoldMode_ = false;
1032 cur.screenUpdateFlags(Update::SinglePar);
1037 bool MathMacro::folded() const
1039 return d->nextFoldMode_;
1043 void MathMacro::write(WriteStream & os) const
1045 MacroData const * data = MacroTable::globalMacros().get(name());
1046 bool textmode_macro = data && data->symbol()
1047 && data->symbol()->extra == "textmode";
1048 bool needs_mathmode = data && (!data->symbol()
1049 || data->symbol()->extra != "textmode");
1051 MathEnsurer ensurer(os, needs_mathmode, true, textmode_macro);
1054 if (d->displayMode_ != DISPLAY_NORMAL) {
1055 os << "\\" << name();
1056 if (name().size() != 1 || isAlphaASCII(name()[0]))
1057 os.pendingSpace(true);
1062 // we should be ok to continue even if this fails.
1065 // Always protect macros in a fragile environment
1069 os << "\\" << name();
1072 // Optional arguments:
1073 // First find last non-empty optional argument
1074 idx_type emptyOptFrom = 0;
1076 for (; i < cells_.size() && i < d->optionals_; ++i) {
1077 if (!cell(i).empty())
1078 emptyOptFrom = i + 1;
1081 // print out optionals
1082 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
1084 os << "[" << cell(i) << "]";
1087 // skip the tailing empty optionals
1090 // Print remaining arguments
1091 for (; i < cells_.size(); ++i) {
1092 if (cell(i).size() == 1
1093 && cell(i)[0].nucleus()->asCharInset()
1094 && isASCII(cell(i)[0].nucleus()->asCharInset()->getChar())) {
1099 os << "{" << cell(i) << "}";
1103 // add space if there was no argument
1105 os.pendingSpace(true);
1109 void MathMacro::maple(MapleStream & os) const
1111 lyx::maple(d->expanded_, os);
1115 void MathMacro::maxima(MaximaStream & os) const
1117 lyx::maxima(d->expanded_, os);
1121 void MathMacro::mathematica(MathematicaStream & os) const
1123 lyx::mathematica(d->expanded_, os);
1127 void MathMacro::mathmlize(MathStream & os) const
1129 // macro_ is 0 if this is an unknown macro
1130 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1132 docstring const xmlname = d->macro_->xmlname();
1133 if (!xmlname.empty()) {
1134 char const * type = d->macro_->MathMLtype();
1135 os << '<' << type << "> " << xmlname << " </"
1140 if (d->expanded_.empty()) {
1141 // this means that we do not recognize the macro
1142 throw MathExportException();
1148 void MathMacro::htmlize(HtmlStream & os) const
1150 // macro_ is 0 if this is an unknown macro
1151 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1153 docstring const xmlname = d->macro_->xmlname();
1154 if (!xmlname.empty()) {
1155 os << ' ' << xmlname << ' ';
1159 if (d->expanded_.empty()) {
1160 // this means that we do not recognize the macro
1161 throw MathExportException();
1167 void MathMacro::octave(OctaveStream & os) const
1169 lyx::octave(d->expanded_, os);
1173 void MathMacro::infoize(odocstream & os) const
1175 os << bformat(_("Macro: %1$s"), name());
1179 void MathMacro::infoize2(odocstream & os) const
1181 os << bformat(_("Macro: %1$s"), name());
1185 bool MathMacro::completionSupported(Cursor const & cur) const
1187 if (displayMode() != DISPLAY_UNFOLDED)
1188 return InsetMathNest::completionSupported(cur);
1190 return lyxrc.completion_popup_math
1191 && displayMode() == DISPLAY_UNFOLDED
1192 && cur.bv().cursor().pos() == int(name().size());
1196 bool MathMacro::inlineCompletionSupported(Cursor const & cur) const
1198 if (displayMode() != DISPLAY_UNFOLDED)
1199 return InsetMathNest::inlineCompletionSupported(cur);
1201 return lyxrc.completion_inline_math
1202 && displayMode() == DISPLAY_UNFOLDED
1203 && cur.bv().cursor().pos() == int(name().size());
1207 bool MathMacro::automaticInlineCompletion() const
1209 if (displayMode() != DISPLAY_UNFOLDED)
1210 return InsetMathNest::automaticInlineCompletion();
1212 return lyxrc.completion_inline_math;
1216 bool MathMacro::automaticPopupCompletion() const
1218 if (displayMode() != DISPLAY_UNFOLDED)
1219 return InsetMathNest::automaticPopupCompletion();
1221 return lyxrc.completion_popup_math;
1225 CompletionList const *
1226 MathMacro::createCompletionList(Cursor const & cur) const
1228 if (displayMode() != DISPLAY_UNFOLDED)
1229 return InsetMathNest::createCompletionList(cur);
1231 return new MathCompletionList(cur.bv().cursor());
1235 docstring MathMacro::completionPrefix(Cursor const & cur) const
1237 if (displayMode() != DISPLAY_UNFOLDED)
1238 return InsetMathNest::completionPrefix(cur);
1240 if (!completionSupported(cur))
1243 return "\\" + name();
1247 bool MathMacro::insertCompletion(Cursor & cur, docstring const & s,
1250 if (displayMode() != DISPLAY_UNFOLDED)
1251 return InsetMathNest::insertCompletion(cur, s, finished);
1253 if (!completionSupported(cur))
1256 // append completion
1257 docstring newName = name() + s;
1258 asArray(newName, cell(0));
1259 cur.bv().cursor().pos() = name().size();
1260 cur.screenUpdateFlags(Update::SinglePar);
1264 cur.bv().cursor().pop();
1265 ++cur.bv().cursor().pos();
1266 cur.screenUpdateFlags(Update::SinglePar);
1273 void MathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
1274 Dimension & dim) const
1276 if (displayMode() != DISPLAY_UNFOLDED)
1277 InsetMathNest::completionPosAndDim(cur, x, y, dim);
1279 // get inset dimensions
1280 dim = cur.bv().coordCache().insets().dim(this);
1281 // FIXME: these 3 are no accurate, but should depend on the font.
1282 // Now the popup jumps down if you enter a char with descent > 0.
1288 = cur.bv().coordCache().insets().xy(this);