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 Changer dummy = mi.base.changeFontSet("lyxtex");
460 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
461 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
462 Changer dummy = mi.base.changeFontSet("lyxtex");
463 cell(0).metrics(mi, dim);
465 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
466 dim.wid += bsdim.width() + 1;
467 dim.asc = max(bsdim.ascent(), dim.ascent());
468 dim.des = max(bsdim.descent(), dim.descent());
469 metricsMarkers(mi, dim);
470 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
471 && d->editing_[mi.base.bv]) {
472 // Macro will be edited in a old-style list mode here:
476 FontInfo labelFont = sane_font;
477 math_font_max_dim(labelFont, fontDim.asc, fontDim.des);
479 // get dimension of components of list view
481 nameDim.wid = mathed_string_width(mi.base.font, from_ascii("Macro \\") + name() + ": ");
482 nameDim.asc = fontDim.asc;
483 nameDim.des = fontDim.des;
486 argDim.wid = mathed_string_width(labelFont, from_ascii("#9: "));
487 argDim.asc = fontDim.asc;
488 argDim.des = fontDim.des;
491 d->definition_.metrics(mi, defDim);
494 dim.wid = nameDim.wid + defDim.wid;
495 dim.asc = max(nameDim.asc, defDim.asc);
496 dim.des = max(nameDim.des, defDim.des);
498 for (idx_type i = 0; i < nargs(); ++i) {
500 cell(i).metrics(mi, cdim);
501 dim.des += max(argDim.height(), cdim.height()) + 1;
502 dim.wid = max(dim.wid, argDim.wid + cdim.wid);
505 // make space for box and markers, 2 pixels
509 metricsMarkers2(mi, dim);
513 Changer dummy = (currentMode() == TEXT_MODE)
514 ? mi.base.font.changeShape(UP_SHAPE)
517 // calculate metrics, hoping that all cells are seen
519 d->expanded_.metrics(mi, dim);
521 // otherwise do a manual metrics call
522 CoordCache & coords = mi.base.bv->coordCache();
523 for (idx_type i = 0; i < nargs(); ++i) {
524 if (!coords.getArrays().hasDim(&cell(i))) {
526 cell(i).metrics(mi, tdim);
531 // calculate dimension with label while editing
532 if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX
533 && d->editing_[mi.base.bv]) {
534 FontInfo font = mi.base.font;
535 augmentFont(font, "lyxtex");
537 mathed_string_dim(font, name(), namedim);
539 dim.wid += 2 + namedim.wid + 2 + 2;
540 dim.asc = max(dim.asc, namedim.asc) + 2;
541 dim.des = max(dim.des, namedim.des) + 2;
543 dim.wid = max(1 + namedim.wid + 1, 2 + dim.wid + 2);
544 dim.asc += 1 + namedim.height() + 1;
549 // restore macro nesting
550 --mi.base.macro_nesting;
554 int MathMacro::kerning(BufferView const * bv) const {
555 if (d->displayMode_ == DISPLAY_NORMAL && !d->editing_[bv])
556 return d->expanded_.kerning(bv);
562 void MathMacro::updateMacro(MacroContext const & mc)
565 d->macro_ = mc.get(name());
566 if (d->macro_ && d->macroBackup_ != *d->macro_) {
567 d->macroBackup_ = *d->macro_;
568 d->needsUpdate_ = true;
576 class MathMacro::UpdateLocker
579 explicit UpdateLocker(MathMacro & mm) : mac(mm)
581 mac.d->isUpdating_ = true;
583 ~UpdateLocker() { mac.d->isUpdating_ = false; }
587 /** Avoid wrong usage of UpdateLocker.
588 To avoid wrong usage:
589 UpdateLocker(...); // wrong
590 UpdateLocker locker(...); // right
592 #define UpdateLocker(x) unnamed_UpdateLocker;
593 // Tip gotten from Bobby Schmidt's column in C/C++ Users Journal
596 void MathMacro::updateRepresentation(Cursor * cur, MacroContext const & mc,
599 // block recursive calls (bug 8999)
603 UpdateLocker locker(*this);
610 d->requires_ = d->macro_->requires();
613 // non-normal mode? We are done!
614 || (d->displayMode_ != DISPLAY_NORMAL))
617 d->needsUpdate_ = false;
619 // get default values of macro
620 vector<docstring> const & defaults = d->macro_->defaults();
622 // create MathMacroArgumentValue objects pointing to the cells of the macro
623 vector<MathData> values(nargs());
624 for (size_t i = 0; i < nargs(); ++i) {
625 ArgumentProxy * proxy;
626 if (i < defaults.size())
627 proxy = new ArgumentProxy(this, i, defaults[i]);
629 proxy = new ArgumentProxy(this, i);
630 values[i].insert(0, MathAtom(proxy));
632 // expanding macro with the values
633 // Only update the argument macros if anything was expanded, otherwise
634 // we would get an endless loop (bug 9140). UpdateLocker does not work
635 // in this case, since MacroData::expand() creates new MathMacro
636 // objects, so this would be a different recursion path than the one
637 // protected by UpdateLocker.
638 if (d->macro_->expand(values, d->expanded_)) {
639 if (utype == OutputUpdate && !d->expanded_.empty())
640 d->expanded_.updateMacros(cur, mc, utype);
642 // get definition for list edit mode
643 docstring const & display = d->macro_->display();
644 asArray(display.empty() ? d->macro_->definition() : display,
645 d->definition_, Parse::QUIET);
649 void MathMacro::draw(PainterInfo & pi, int x, int y) const
651 Dimension const dim = dimension(*pi.base.bv);
653 setPosCache(pi, x, y);
657 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
658 Changer dummy = pi.base.changeFontSet("lyxtex");
659 pi.pain.text(x, y, from_ascii("\\") + name(), pi.base.font);
660 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
661 Changer dummy = pi.base.changeFontSet("lyxtex");
662 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
663 x += mathed_string_width(pi.base.font, from_ascii("\\")) + 1;
664 cell(0).draw(pi, x, y);
665 drawMarkers(pi, expx, expy);
666 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
667 && d->editing_[pi.base.bv]) {
668 // Macro will be edited in a old-style list mode here:
670 CoordCache const & coords = pi.base.bv->coordCache();
671 FontInfo const & labelFont = sane_font;
673 // markers and box needs two pixels
676 // get maximal font height
678 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
681 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
682 pi.pain.text(x, y, label, labelFont);
683 x += mathed_string_width(labelFont, label);
686 d->definition_.draw(pi, x, y);
687 Dimension const & defDim = coords.getArrays().dim(&d->definition_);
688 y += max(fontDim.des, defDim.des);
691 docstring str = from_ascii("#9");
692 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
693 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
695 for (idx_type i = 0; i < nargs(); ++i) {
697 Dimension const & cdim = coords.getArrays().dim(&cell(i));
699 y += max(fontDim.asc, cdim.asc) + 1;
703 pi.pain.text(x, y, str, labelFont);
705 pi.pain.text(x, y, from_ascii(":"), labelFont);
709 cell(i).draw(pi, x, y);
712 y += max(fontDim.des, cdim.des);
715 pi.pain.rectangle(expx + 1, expy - dim.asc + 1, dim.wid - 3,
716 dim.height() - 2, Color_mathmacroframe);
717 drawMarkers2(pi, expx, expy);
719 // the macro contents is not editable (except the arguments)
720 ++pi.base.macro_nesting;
722 bool drawBox = lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX;
723 Changer dummy = (currentMode() == TEXT_MODE)
724 ? pi.base.font.changeShape(UP_SHAPE)
728 for (size_t i = 0; i < nargs(); ++i)
729 cell(i).setXY(*pi.base.bv, x, y);
731 if (drawBox && d->editing_[pi.base.bv]) {
732 // draw header and rectangle around
733 FontInfo font = pi.base.font;
734 augmentFont(font, "lyxtex");
735 font.setSize(FONT_SIZE_TINY);
736 font.setColor(Color_mathmacrolabel);
738 mathed_string_dim(font, name(), namedim);
740 pi.pain.fillRectangle(x, y - dim.asc, dim.wid, 1 + namedim.height() + 1, Color_mathmacrobg);
741 pi.pain.text(x + 1, y - dim.asc + namedim.asc + 2, name(), font);
742 expx += (dim.wid - d->expanded_.dimension(*pi.base.bv).width()) / 2;
745 if (d->editing_[pi.base.bv]) {
746 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
747 d->expanded_.draw(pi, expx, expy);
748 pi.pain.leaveMonochromeMode();
751 pi.pain.rectangle(x, y - dim.asc, dim.wid,
752 dim.height(), Color_mathmacroframe);
754 d->expanded_.draw(pi, expx, expy);
756 --pi.base.macro_nesting;
759 drawMarkers(pi, x, y);
763 // edit mode changed?
764 if (d->editing_[pi.base.bv] != editMode(pi.base.bv))
765 pi.base.bv->cursor().screenUpdateFlags(Update::SinglePar);
769 void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
771 // We may have 0 arguments, but InsetMathNest requires at least one.
773 InsetMathNest::drawSelection(pi, x, y);
777 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode, int appetite)
779 if (d->displayMode_ != mode) {
780 // transfer name if changing from or to DISPLAY_UNFOLDED
781 if (mode == DISPLAY_UNFOLDED) {
783 asArray(d->name_, cell(0));
784 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
785 d->name_ = asString(cell(0));
789 d->displayMode_ = mode;
790 d->needsUpdate_ = true;
793 // the interactive init mode is non-greedy by default
795 d->appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
797 d->appetite_ = size_t(appetite);
801 MathMacro::DisplayMode MathMacro::computeDisplayMode() const
803 if (d->nextFoldMode_ == true && d->macro_ && !d->macro_->locked())
804 return DISPLAY_NORMAL;
806 return DISPLAY_UNFOLDED;
810 bool MathMacro::validName() const
812 docstring n = name();
817 // converting back and force doesn't swallow anything?
820 if (asString(ma) != n)
824 for (size_t i = 0; i<n.size(); ++i) {
825 if (!(n[i] >= 'a' && n[i] <= 'z')
826 && !(n[i] >= 'A' && n[i] <= 'Z')
835 size_t MathMacro::arity() const
837 if (d->displayMode_ == DISPLAY_NORMAL )
838 return cells_.size();
844 size_t MathMacro::optionals() const
846 return d->optionals_;
850 void MathMacro::setOptionals(int n)
852 if (n <= int(nargs()))
857 size_t MathMacro::appetite() const
863 InsetMath::mode_type MathMacro::currentMode() const
865 // User defined macros are always assumed to be mathmode macros.
866 // Only the global macros defined in lib/symbols may be textmode.
868 MacroData const * data = MacroTable::globalMacros().get(name());
869 bool textmode = data && data->symbol() && data->symbol()->extra == "textmode";
870 return textmode ? TEXT_MODE : MATH_MODE;
874 void MathMacro::validate(LaTeXFeatures & features) const
876 // Immediately after a document is loaded, in some cases the MacroData
877 // of the global macros defined in the lib/symbols file may still not
878 // be known to the macro machinery because it will be set only after
879 // the first call to updateMacros(). This is not a problem unless
880 // instant preview is on for math, in which case we will be missing
881 // the corresponding requirements.
882 // In this case, we get the required info from the global macro table.
883 if (!d->requires_.empty())
884 features.require(d->requires_);
885 else if (!d->macro_) {
886 // Update requires for known global macros.
887 MacroData const * data = MacroTable::globalMacros().get(name());
888 if (data && !data->requires().empty())
889 features.require(data->requires());
892 if (name() == "binom")
893 features.require("binom");
895 // validate the cells and the definition
896 if (displayMode() == DISPLAY_NORMAL) {
897 d->definition_.validate(features);
898 InsetMathNest::validate(features);
903 void MathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
905 cur.screenUpdateFlags(Update::SinglePar);
906 InsetMathNest::edit(cur, front, entry_from);
910 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
912 // We may have 0 arguments, but InsetMathNest requires at least one.
914 cur.screenUpdateFlags(Update::SinglePar);
915 return InsetMathNest::editXY(cur, x, y);
921 void MathMacro::removeArgument(Inset::pos_type pos) {
922 if (d->displayMode_ == DISPLAY_NORMAL) {
923 LASSERT(size_t(pos) < cells_.size(), return);
924 cells_.erase(cells_.begin() + pos);
925 if (size_t(pos) < d->attachedArgsNum_)
926 --d->attachedArgsNum_;
927 if (size_t(pos) < d->optionals_) {
931 d->needsUpdate_ = true;
936 void MathMacro::insertArgument(Inset::pos_type pos) {
937 if (d->displayMode_ == DISPLAY_NORMAL) {
938 LASSERT(size_t(pos) <= cells_.size(), return);
939 cells_.insert(cells_.begin() + pos, MathData());
940 if (size_t(pos) < d->attachedArgsNum_)
941 ++d->attachedArgsNum_;
942 if (size_t(pos) < d->optionals_)
945 d->needsUpdate_ = true;
950 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
952 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
955 // strip off empty cells, but not more than arity-attachedArgsNum_
958 for (i = cells_.size(); i > d->attachedArgsNum_; --i)
959 if (!cell(i - 1).empty()) break;
963 d->attachedArgsNum_ = 0;
964 d->expanded_ = MathData();
967 d->needsUpdate_ = true;
971 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
973 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
975 d->attachedArgsNum_ = args.size();
976 cells_.resize(arity);
977 d->expanded_ = MathData();
978 d->optionals_ = optionals;
980 d->needsUpdate_ = true;
984 bool MathMacro::idxFirst(Cursor & cur) const
986 cur.screenUpdateFlags(Update::SinglePar);
987 return InsetMathNest::idxFirst(cur);
991 bool MathMacro::idxLast(Cursor & cur) const
993 cur.screenUpdateFlags(Update::SinglePar);
994 return InsetMathNest::idxLast(cur);
998 bool MathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
1000 if (d->displayMode_ == DISPLAY_UNFOLDED) {
1001 docstring const & unfolded_name = name();
1002 if (unfolded_name != d->name_) {
1003 // The macro name was changed
1004 Cursor inset_cursor = old;
1005 int macroSlice = inset_cursor.find(this);
1006 // returning true means the cursor is "now" invalid,
1008 LASSERT(macroSlice != -1, return true);
1009 inset_cursor.cutOff(macroSlice);
1010 inset_cursor.recordUndoInset();
1012 inset_cursor.cell().erase(inset_cursor.pos());
1013 inset_cursor.cell().insert(inset_cursor.pos(),
1014 createInsetMath(unfolded_name, cur.buffer()));
1016 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
1020 cur.screenUpdateFlags(Update::Force);
1021 return InsetMathNest::notifyCursorLeaves(old, cur);
1025 void MathMacro::fold(Cursor & cur)
1027 if (!d->nextFoldMode_) {
1028 d->nextFoldMode_ = true;
1029 cur.screenUpdateFlags(Update::SinglePar);
1034 void MathMacro::unfold(Cursor & cur)
1036 if (d->nextFoldMode_) {
1037 d->nextFoldMode_ = false;
1038 cur.screenUpdateFlags(Update::SinglePar);
1043 bool MathMacro::folded() const
1045 return d->nextFoldMode_;
1049 void MathMacro::write(WriteStream & os) const
1051 MacroData const * data = MacroTable::globalMacros().get(name());
1052 bool textmode_macro = data && data->symbol()
1053 && data->symbol()->extra == "textmode";
1054 bool needs_mathmode = data && (!data->symbol()
1055 || data->symbol()->extra != "textmode");
1057 MathEnsurer ensurer(os, needs_mathmode, true, textmode_macro);
1060 if (d->displayMode_ != DISPLAY_NORMAL) {
1061 os << "\\" << name();
1062 if (name().size() != 1 || isAlphaASCII(name()[0]))
1063 os.pendingSpace(true);
1068 // we should be ok to continue even if this fails.
1071 // We may already be in the argument of a macro
1072 bool const inside_macro = os.insideMacro();
1073 os.insideMacro(true);
1075 // Enclose in braces to avoid latex errors with xargs if we have
1076 // optional arguments and are in the optional argument of a macro
1077 if (d->optionals_ && inside_macro)
1080 // Always protect macros in a fragile environment
1084 os << "\\" << name();
1087 // Optional arguments:
1088 // First find last non-empty optional argument
1089 idx_type emptyOptFrom = 0;
1091 for (; i < cells_.size() && i < d->optionals_; ++i) {
1092 if (!cell(i).empty())
1093 emptyOptFrom = i + 1;
1096 // print out optionals
1097 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
1099 os << "[" << cell(i) << "]";
1102 // skip the tailing empty optionals
1105 // Print remaining arguments
1106 for (; i < cells_.size(); ++i) {
1107 if (cell(i).size() == 1
1108 && cell(i)[0].nucleus()->asCharInset()
1109 && isASCII(cell(i)[0].nucleus()->asCharInset()->getChar())) {
1114 os << "{" << cell(i) << "}";
1118 // Close the opened brace or add space if there was no argument
1119 if (d->optionals_ && inside_macro)
1122 os.pendingSpace(true);
1124 os.insideMacro(inside_macro);
1128 void MathMacro::maple(MapleStream & os) const
1130 lyx::maple(d->expanded_, os);
1134 void MathMacro::maxima(MaximaStream & os) const
1136 lyx::maxima(d->expanded_, os);
1140 void MathMacro::mathematica(MathematicaStream & os) const
1142 lyx::mathematica(d->expanded_, os);
1146 void MathMacro::mathmlize(MathStream & os) const
1148 // macro_ is 0 if this is an unknown macro
1149 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1151 docstring const xmlname = d->macro_->xmlname();
1152 if (!xmlname.empty()) {
1153 char const * type = d->macro_->MathMLtype();
1154 os << '<' << type << "> " << xmlname << " </"
1159 if (d->expanded_.empty()) {
1160 // this means that we do not recognize the macro
1161 throw MathExportException();
1167 void MathMacro::htmlize(HtmlStream & os) const
1169 // macro_ is 0 if this is an unknown macro
1170 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1172 docstring const xmlname = d->macro_->xmlname();
1173 if (!xmlname.empty()) {
1174 os << ' ' << xmlname << ' ';
1178 if (d->expanded_.empty()) {
1179 // this means that we do not recognize the macro
1180 throw MathExportException();
1186 void MathMacro::octave(OctaveStream & os) const
1188 lyx::octave(d->expanded_, os);
1192 void MathMacro::infoize(odocstream & os) const
1194 os << bformat(_("Macro: %1$s"), name());
1198 void MathMacro::infoize2(odocstream & os) const
1200 os << bformat(_("Macro: %1$s"), name());
1204 bool MathMacro::completionSupported(Cursor const & cur) const
1206 if (displayMode() != DISPLAY_UNFOLDED)
1207 return InsetMathNest::completionSupported(cur);
1209 return lyxrc.completion_popup_math
1210 && displayMode() == DISPLAY_UNFOLDED
1211 && cur.bv().cursor().pos() == int(name().size());
1215 bool MathMacro::inlineCompletionSupported(Cursor const & cur) const
1217 if (displayMode() != DISPLAY_UNFOLDED)
1218 return InsetMathNest::inlineCompletionSupported(cur);
1220 return lyxrc.completion_inline_math
1221 && displayMode() == DISPLAY_UNFOLDED
1222 && cur.bv().cursor().pos() == int(name().size());
1226 bool MathMacro::automaticInlineCompletion() const
1228 if (displayMode() != DISPLAY_UNFOLDED)
1229 return InsetMathNest::automaticInlineCompletion();
1231 return lyxrc.completion_inline_math;
1235 bool MathMacro::automaticPopupCompletion() const
1237 if (displayMode() != DISPLAY_UNFOLDED)
1238 return InsetMathNest::automaticPopupCompletion();
1240 return lyxrc.completion_popup_math;
1244 CompletionList const *
1245 MathMacro::createCompletionList(Cursor const & cur) const
1247 if (displayMode() != DISPLAY_UNFOLDED)
1248 return InsetMathNest::createCompletionList(cur);
1250 return new MathCompletionList(cur.bv().cursor());
1254 docstring MathMacro::completionPrefix(Cursor const & cur) const
1256 if (displayMode() != DISPLAY_UNFOLDED)
1257 return InsetMathNest::completionPrefix(cur);
1259 if (!completionSupported(cur))
1262 return "\\" + name();
1266 bool MathMacro::insertCompletion(Cursor & cur, docstring const & s,
1269 if (displayMode() != DISPLAY_UNFOLDED)
1270 return InsetMathNest::insertCompletion(cur, s, finished);
1272 if (!completionSupported(cur))
1275 // append completion
1276 docstring newName = name() + s;
1277 asArray(newName, cell(0));
1278 cur.bv().cursor().pos() = name().size();
1279 cur.screenUpdateFlags(Update::SinglePar);
1283 cur.bv().cursor().pop();
1284 ++cur.bv().cursor().pos();
1285 cur.screenUpdateFlags(Update::SinglePar);
1292 void MathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
1293 Dimension & dim) const
1295 if (displayMode() != DISPLAY_UNFOLDED)
1296 InsetMathNest::completionPosAndDim(cur, x, y, dim);
1298 // get inset dimensions
1299 dim = cur.bv().coordCache().insets().dim(this);
1300 // FIXME: these 3 are no accurate, but should depend on the font.
1301 // Now the popup jumps down if you enter a char with descent > 0.
1307 = cur.bv().coordCache().insets().xy(this);