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,
86 mathMacro_->nesting() == 1 ? 0 : mathMacro_->nesting());
88 MathRow::Element e_beg(MathRow::BEG_ARG);
89 e_beg.macro = mathMacro_;
90 e_beg.ar = &mathMacro_->cell(idx_);
91 mrow.push_back(e_beg);
93 mathMacro_->macro()->unlock();
94 bool has_contents = displayCell(mi.base.bv).addToMathRow(mrow, mi);
95 mathMacro_->macro()->lock();
97 // if there was no contents, and the contents is editable,
98 // then we insert a box instead.
99 if (!has_contents && mathMacro_->nesting() == 1) {
100 // mathclass is ord because it should be spaced as a normal atom
101 MathRow::Element e(MathRow::BOX, MC_ORD);
102 e.color = Color_mathline;
107 MathRow::Element e_end(MathRow::END_ARG);
108 e_end.macro = mathMacro_;
109 e_end.ar = &mathMacro_->cell(idx_);
111 mrow.push_back(e_end);
116 void metrics(MetricsInfo &, Dimension &) const {
117 // This should never be invoked, since ArgumentProxy insets are linearized
121 int kerning(BufferView const * bv) const
123 return displayCell(bv).kerning(bv);
126 void draw(PainterInfo &, int, int) const {
127 // This should never be invoked, since ArgumentProxy insets are linearized
130 // write(), normalize(), infoize() and infoize2() are not needed since
131 // MathMacro uses the definition and not the expanded cells.
133 void maple(MapleStream & ms) const { ms << mathMacro_->cell(idx_); }
135 void maxima(MaximaStream & ms) const { ms << mathMacro_->cell(idx_); }
137 void mathematica(MathematicaStream & ms) const { ms << mathMacro_->cell(idx_); }
139 void mathmlize(MathStream & ms) const { ms << mathMacro_->cell(idx_); }
141 void htmlize(HtmlStream & ms) const { ms << mathMacro_->cell(idx_); }
143 void octave(OctaveStream & os) const { os << mathMacro_->cell(idx_); }
145 MathClass mathClass() const
148 // This can be refined once the pointer issues are fixed. I did not
149 // notice any immediate crash with the following code, but it is risky
151 //return mathMacro_->cell(idx_).mathClass();
156 Inset * clone() const
158 return new ArgumentProxy(*this);
161 MathMacro * mathMacro_;
169 /// Private implementation of MathMacro
170 class MathMacro::Private {
172 Private(Buffer * buf, docstring const & name)
173 : name_(name), displayMode_(DISPLAY_INIT),
174 expanded_(buf), definition_(buf), attachedArgsNum_(0),
175 optionals_(0), nextFoldMode_(true), macroBackup_(buf),
176 macro_(0), needsUpdate_(false), isUpdating_(false),
180 /// Update the pointers to our owner of all expanded macros.
181 /// This needs to be called every time a copy of the owner is created
183 void updateChildren(MathMacro * owner);
184 /// Recursively update the pointers of all expanded macros
185 /// appearing in the arguments of the current macro
186 void updateNestedChildren(MathMacro * owner, InsetMathNest * ni);
189 /// current display mode
190 DisplayMode displayMode_;
191 /// expanded macro with ArgumentProxies
193 /// macro definition with #1,#2,.. insets
194 MathData definition_;
195 /// number of arguments that were really attached
196 size_t attachedArgsNum_;
197 /// optional argument attached? (only in DISPLAY_NORMAL mode)
199 /// fold mode to be set in next metrics call?
201 /// if macro_ == true, then here is a copy of the macro
202 /// don't use it for locking
203 MacroData macroBackup_;
204 /// if macroNotFound_ == false, then here is a reference to the macro
205 /// this might invalidate after metrics was called
206 MacroData const * macro_;
208 mutable std::map<BufferView const *, bool> editing_;
210 std::string requires_;
211 /// update macro representation
215 /// maximal number of arguments the macro is greedy for
217 /// Level of nesting in macros (including this one)
222 void MathMacro::Private::updateChildren(MathMacro * owner)
224 for (size_t i = 0; i < expanded_.size(); ++i) {
225 ArgumentProxy * p = dynamic_cast<ArgumentProxy *>(expanded_[i].nucleus());
229 InsetMathNest * ni = expanded_[i].nucleus()->asNestInset();
231 updateNestedChildren(owner, ni);
235 // The macro_ pointer is updated when MathData::metrics() is
236 // called. However, when instant preview is on or the macro is
237 // not on screen, MathData::metrics() is not called and we may
238 // have a dangling pointer. As a safety measure, when a macro
239 // is copied, always let macro_ point to the backup copy of the
240 // MacroData structure. This backup is updated every time the
241 // macro is changed, so it will not become stale.
242 macro_ = ¯oBackup_;
247 void MathMacro::Private::updateNestedChildren(MathMacro * owner, InsetMathNest * ni)
249 for (size_t i = 0; i < ni->nargs(); ++i) {
250 MathData & ar = ni->cell(i);
251 for (size_t j = 0; j < ar.size(); ++j) {
252 ArgumentProxy * ap = dynamic_cast
253 <ArgumentProxy *>(ar[j].nucleus());
255 MathMacro::Private * md = ap->owner()->d;
257 md->macro_ = &md->macroBackup_;
260 InsetMathNest * imn = ar[j].nucleus()->asNestInset();
262 updateNestedChildren(owner, imn);
268 MathMacro::MathMacro(Buffer * buf, docstring const & name)
269 : InsetMathNest(buf, 0), d(new Private(buf, name))
273 MathMacro::MathMacro(MathMacro const & that)
274 : InsetMathNest(that), d(new Private(*that.d))
276 setBuffer(*that.buffer_);
277 d->updateChildren(this);
281 MathMacro & MathMacro::operator=(MathMacro const & that)
285 InsetMathNest::operator=(that);
287 d->updateChildren(this);
292 MathMacro::~MathMacro()
298 bool MathMacro::addToMathRow(MathRow & mrow, MetricsInfo & mi) const
300 // set edit mode for which we will have calculated row.
301 // This is the same as what is done in metrics().
302 d->editing_[mi.base.bv] = editMode(mi.base.bv);
304 /// The macro nesting can change display of insets. Change it locally.
305 Changer chg = make_change(mi.base.macro_nesting, d->nesting_);
307 if (displayMode() != MathMacro::DISPLAY_NORMAL
308 || d->editing_[mi.base.bv])
309 return InsetMath::addToMathRow(mrow, mi);
311 MathRow::Element e_beg(MathRow::BEG_MACRO);
313 mrow.push_back(e_beg);
316 bool has_contents = d->expanded_.addToMathRow(mrow, mi);
319 // if there was no contents and the array is editable, then we
320 // insert a grey box instead.
321 if (!has_contents && mi.base.macro_nesting == 1) {
322 // mathclass is unknown because it is irrelevant for spacing
323 MathRow::Element e(MathRow::BOX);
324 e.color = Color_mathmacroblend;
329 MathRow::Element e_end(MathRow::END_MACRO);
331 mrow.push_back(e_end);
337 Inset * MathMacro::clone() const
339 MathMacro * copy = new MathMacro(*this);
340 copy->d->needsUpdate_ = true;
341 //copy->d->expanded_.clear();
346 void MathMacro::normalize(NormalStream & os) const
348 os << "[macro " << name();
349 for (size_t i = 0; i < nargs(); ++i)
350 os << ' ' << cell(i);
355 MathMacro::DisplayMode MathMacro::displayMode() const
357 return d->displayMode_;
361 bool MathMacro::extraBraces() const
363 return d->displayMode_ == DISPLAY_NORMAL && arity() > 0;
367 docstring MathMacro::name() const
369 if (d->displayMode_ == DISPLAY_UNFOLDED)
370 return asString(cell(0));
376 docstring MathMacro::macroName() const
382 int MathMacro::nesting() const
388 void MathMacro::cursorPos(BufferView const & bv,
389 CursorSlice const & sl, bool boundary, int & x, int & y) const
391 // We may have 0 arguments, but InsetMathNest requires at least one.
393 InsetMathNest::cursorPos(bv, sl, boundary, x, y);
397 bool MathMacro::editMode(BufferView const * bv) const {
398 // find this in cursor trace
399 Cursor const & cur = bv->cursor();
400 for (size_t i = 0; i != cur.depth(); ++i)
401 if (&cur[i].inset() == this) {
402 // look if there is no other macro in edit mode above
404 for (; i != cur.depth(); ++i) {
405 InsetMath * im = cur[i].asInsetMath();
407 MathMacro const * macro = im->asMacro();
408 if (macro && macro->displayMode() == DISPLAY_NORMAL)
413 // ok, none found, I am the highest one
421 MacroData const * MathMacro::macro() const
427 bool MathMacro::editMetrics(BufferView const * bv) const
429 return d->editing_[bv];
433 void MathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
435 /// The macro nesting can change display of insets. Change it locally.
436 Changer chg = make_change(mi.base.macro_nesting, d->nesting_);
438 // set edit mode for which we will have calculated metrics. But only
439 d->editing_[mi.base.bv] = editMode(mi.base.bv);
441 // calculate new metrics according to display mode
442 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
443 Changer dummy = mi.base.changeFontSet("lyxtex");
444 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
445 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
446 Changer dummy = mi.base.changeFontSet("lyxtex");
447 cell(0).metrics(mi, dim);
449 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
450 dim.wid += bsdim.width() + 1;
451 dim.asc = max(bsdim.ascent(), dim.ascent());
452 dim.des = max(bsdim.descent(), dim.descent());
453 metricsMarkers(mi, dim);
454 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
455 && d->editing_[mi.base.bv]) {
456 // Macro will be edited in a old-style list mode here:
460 FontInfo labelFont = sane_font;
461 math_font_max_dim(labelFont, fontDim.asc, fontDim.des);
463 // get dimension of components of list view
465 nameDim.wid = mathed_string_width(mi.base.font, from_ascii("Macro \\") + name() + ": ");
466 nameDim.asc = fontDim.asc;
467 nameDim.des = fontDim.des;
470 argDim.wid = mathed_string_width(labelFont, from_ascii("#9: "));
471 argDim.asc = fontDim.asc;
472 argDim.des = fontDim.des;
475 d->definition_.metrics(mi, defDim);
478 dim.wid = nameDim.wid + defDim.wid;
479 dim.asc = max(nameDim.asc, defDim.asc);
480 dim.des = max(nameDim.des, defDim.des);
482 for (idx_type i = 0; i < nargs(); ++i) {
484 cell(i).metrics(mi, cdim);
485 dim.des += max(argDim.height(), cdim.height()) + 1;
486 dim.wid = max(dim.wid, argDim.wid + cdim.wid);
489 // make space for box and markers, 2 pixels
493 metricsMarkers2(mi, dim);
497 // calculate metrics, hoping that all cells are seen
499 d->expanded_.metrics(mi, dim);
501 // otherwise do a manual metrics call
502 CoordCache & coords = mi.base.bv->coordCache();
503 for (idx_type i = 0; i < nargs(); ++i) {
504 if (!coords.getArrays().hasDim(&cell(i))) {
506 cell(i).metrics(mi, tdim);
511 // calculate dimension with label while editing
512 if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX
513 && d->editing_[mi.base.bv]) {
514 FontInfo font = mi.base.font;
515 augmentFont(font, "lyxtex");
517 mathed_string_dim(font, name(), namedim);
519 dim.wid += 2 + namedim.wid + 2 + 2;
520 dim.asc = max(dim.asc, namedim.asc) + 2;
521 dim.des = max(dim.des, namedim.des) + 2;
523 dim.wid = max(1 + namedim.wid + 1, 2 + dim.wid + 2);
524 dim.asc += 1 + namedim.height() + 1;
531 int MathMacro::kerning(BufferView const * bv) const {
532 if (d->displayMode_ == DISPLAY_NORMAL && !d->editing_[bv])
533 return d->expanded_.kerning(bv);
539 void MathMacro::updateMacro(MacroContext const & mc)
542 d->macro_ = mc.get(name());
543 if (d->macro_ && d->macroBackup_ != *d->macro_) {
544 d->macroBackup_ = *d->macro_;
545 d->needsUpdate_ = true;
553 class MathMacro::UpdateLocker
556 explicit UpdateLocker(MathMacro & mm) : mac(mm)
558 mac.d->isUpdating_ = true;
560 ~UpdateLocker() { mac.d->isUpdating_ = false; }
564 /** Avoid wrong usage of UpdateLocker.
565 To avoid wrong usage:
566 UpdateLocker(...); // wrong
567 UpdateLocker locker(...); // right
569 #define UpdateLocker(x) unnamed_UpdateLocker;
570 // Tip gotten from Bobby Schmidt's column in C/C++ Users Journal
573 void MathMacro::updateRepresentation(Cursor * cur, MacroContext const & mc,
574 UpdateType utype, int nesting)
576 // block recursive calls (bug 8999)
580 UpdateLocker locker(*this);
586 // remember nesting level of this macro
587 d->nesting_ = nesting;
590 d->requires_ = d->macro_->requires();
593 // non-normal mode? We are done!
594 || (d->displayMode_ != DISPLAY_NORMAL))
597 d->needsUpdate_ = false;
599 // get default values of macro
600 vector<docstring> const & defaults = d->macro_->defaults();
602 // create MathMacroArgumentValue objects pointing to the cells of the macro
603 vector<MathData> values(nargs());
604 for (size_t i = 0; i < nargs(); ++i) {
605 ArgumentProxy * proxy;
606 if (i < defaults.size())
607 proxy = new ArgumentProxy(this, i, defaults[i]);
609 proxy = new ArgumentProxy(this, i);
610 values[i].insert(0, MathAtom(proxy));
612 // expanding macro with the values
613 // Only update the argument macros if anything was expanded, otherwise
614 // we would get an endless loop (bug 9140). UpdateLocker does not work
615 // in this case, since MacroData::expand() creates new MathMacro
616 // objects, so this would be a different recursion path than the one
617 // protected by UpdateLocker.
618 if (d->macro_->expand(values, d->expanded_)) {
619 if (utype == OutputUpdate && !d->expanded_.empty())
620 d->expanded_.updateMacros(cur, mc, utype, nesting);
622 // get definition for list edit mode
623 docstring const & display = d->macro_->display();
624 asArray(display.empty() ? d->macro_->definition() : display,
625 d->definition_, Parse::QUIET);
629 void MathMacro::draw(PainterInfo & pi, int x, int y) const
631 Dimension const dim = dimension(*pi.base.bv);
636 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
637 Changer dummy = pi.base.changeFontSet("lyxtex");
638 pi.pain.text(x, y, from_ascii("\\") + name(), pi.base.font);
639 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
640 Changer dummy = pi.base.changeFontSet("lyxtex");
641 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
642 x += mathed_string_width(pi.base.font, from_ascii("\\")) + 1;
643 cell(0).draw(pi, x, y);
644 drawMarkers(pi, expx, expy);
645 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
646 && d->editing_[pi.base.bv]) {
647 // Macro will be edited in a old-style list mode here:
649 CoordCache const & coords = pi.base.bv->coordCache();
650 FontInfo const & labelFont = sane_font;
652 // markers and box needs two pixels
655 // get maximal font height
657 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
660 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
661 pi.pain.text(x, y, label, labelFont);
662 x += mathed_string_width(labelFont, label);
665 d->definition_.draw(pi, x, y);
666 Dimension const & defDim = coords.getArrays().dim(&d->definition_);
667 y += max(fontDim.des, defDim.des);
670 docstring str = from_ascii("#9");
671 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
672 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
674 for (idx_type i = 0; i < nargs(); ++i) {
676 Dimension const & cdim = coords.getArrays().dim(&cell(i));
678 y += max(fontDim.asc, cdim.asc) + 1;
682 pi.pain.text(x, y, str, labelFont);
684 pi.pain.text(x, y, from_ascii(":"), labelFont);
688 cell(i).draw(pi, x, y);
691 y += max(fontDim.des, cdim.des);
694 pi.pain.rectangle(expx + 1, expy - dim.asc + 1, dim.wid - 3,
695 dim.height() - 2, Color_mathmacroframe);
696 drawMarkers2(pi, expx, expy);
698 bool drawBox = lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX;
701 for (size_t i = 0; i < nargs(); ++i)
702 cell(i).setXY(*pi.base.bv, x, y);
704 if (drawBox && d->editing_[pi.base.bv]) {
705 // draw header and rectangle around
706 FontInfo font = pi.base.font;
707 augmentFont(font, "lyxtex");
708 font.setSize(FONT_SIZE_TINY);
709 font.setColor(Color_mathmacrolabel);
711 mathed_string_dim(font, name(), namedim);
713 pi.pain.fillRectangle(x, y - dim.asc, dim.wid, 1 + namedim.height() + 1, Color_mathmacrobg);
714 pi.pain.text(x + 1, y - dim.asc + namedim.asc + 2, name(), font);
715 expx += (dim.wid - d->expanded_.dimension(*pi.base.bv).width()) / 2;
718 if (d->editing_[pi.base.bv]) {
719 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
720 d->expanded_.draw(pi, expx, expy);
721 pi.pain.leaveMonochromeMode();
724 pi.pain.rectangle(x, y - dim.asc, dim.wid,
725 dim.height(), Color_mathmacroframe);
727 d->expanded_.draw(pi, expx, expy);
730 drawMarkers(pi, x, y);
734 // edit mode changed?
735 if (d->editing_[pi.base.bv] != editMode(pi.base.bv))
736 pi.base.bv->cursor().screenUpdateFlags(Update::SinglePar);
740 void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
742 // We may have 0 arguments, but InsetMathNest requires at least one.
744 InsetMathNest::drawSelection(pi, x, y);
748 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode, int appetite)
750 if (d->displayMode_ != mode) {
751 // transfer name if changing from or to DISPLAY_UNFOLDED
752 if (mode == DISPLAY_UNFOLDED) {
754 asArray(d->name_, cell(0));
755 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
756 d->name_ = asString(cell(0));
760 d->displayMode_ = mode;
761 d->needsUpdate_ = true;
764 // the interactive init mode is non-greedy by default
766 d->appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
768 d->appetite_ = size_t(appetite);
772 MathMacro::DisplayMode MathMacro::computeDisplayMode() const
774 if (d->nextFoldMode_ == true && d->macro_ && !d->macro_->locked())
775 return DISPLAY_NORMAL;
777 return DISPLAY_UNFOLDED;
781 bool MathMacro::validName() const
783 docstring n = name();
788 // converting back and force doesn't swallow anything?
791 if (asString(ma) != n)
795 for (size_t i = 0; i<n.size(); ++i) {
796 if (!(n[i] >= 'a' && n[i] <= 'z')
797 && !(n[i] >= 'A' && n[i] <= 'Z')
806 size_t MathMacro::arity() const
808 if (d->displayMode_ == DISPLAY_NORMAL )
809 return cells_.size();
815 size_t MathMacro::optionals() const
817 return d->optionals_;
821 void MathMacro::setOptionals(int n)
823 if (n <= int(nargs()))
828 size_t MathMacro::appetite() const
834 MathClass MathMacro::mathClass() const
836 // This can be just a heuristic, since it is only considered for display
837 // when the macro is not linearised. Therefore it affects:
838 // * The spacing of the inset while being edited,
839 // * Intelligent splitting
840 // * Cursor word movement (Ctrl-Arrow).
841 if (MacroData const * m = macroBackup()) {
842 // If it is a global macro and is defined explicitly
844 MathClass mc = string_to_class(m->symbol()->extra);
845 if (mc != MC_UNKNOWN)
849 // Otherwise guess from the expanded macro
850 return d->expanded_.mathClass();
854 InsetMath::mode_type MathMacro::currentMode() const
856 // There is no way to guess the mode of user defined macros, so they are
857 // always assumed to be mathmode. Only the global macros defined in
858 // lib/symbols may be textmode.
859 mode_type mode = modeToEnsure();
860 return (mode == UNDECIDED_MODE) ? MATH_MODE : mode;
864 InsetMath::mode_type MathMacro::modeToEnsure() const
866 // User defined macros can be either text mode or math mode for output and
867 // display. There is no way to guess. For global macros defined in
868 // lib/symbols, we ensure textmode if flagged as such, otherwise we ensure
870 if (MacroData const * m = macroBackup())
872 return (m->symbol()->extra == "textmode") ? TEXT_MODE : MATH_MODE;
873 return UNDECIDED_MODE;
877 MacroData const * MathMacro::macroBackup() const
880 return &d->macroBackup_;
881 if (MacroData const * data = MacroTable::globalMacros().get(name()))
887 void MathMacro::validate(LaTeXFeatures & features) const
889 // Immediately after a document is loaded, in some cases the MacroData
890 // of the global macros defined in the lib/symbols file may still not
891 // be known to the macro machinery because it will be set only after
892 // the first call to updateMacros(). This is not a problem unless
893 // instant preview is on for math, in which case we will be missing
894 // the corresponding requirements.
895 // In this case, we get the required info from the global macro table.
896 if (!d->requires_.empty())
897 features.require(d->requires_);
898 else if (!d->macro_) {
899 // Update requires for known global macros.
900 MacroData const * data = MacroTable::globalMacros().get(name());
901 if (data && !data->requires().empty())
902 features.require(data->requires());
905 if (name() == "binom")
906 features.require("binom");
908 // validate the cells and the definition
909 if (displayMode() == DISPLAY_NORMAL) {
910 d->definition_.validate(features);
911 InsetMathNest::validate(features);
916 void MathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
918 cur.screenUpdateFlags(Update::SinglePar);
919 InsetMathNest::edit(cur, front, entry_from);
923 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
925 // We may have 0 arguments, but InsetMathNest requires at least one.
927 cur.screenUpdateFlags(Update::SinglePar);
928 return InsetMathNest::editXY(cur, x, y);
934 void MathMacro::removeArgument(Inset::pos_type pos) {
935 if (d->displayMode_ == DISPLAY_NORMAL) {
936 LASSERT(size_t(pos) < cells_.size(), return);
937 cells_.erase(cells_.begin() + pos);
938 if (size_t(pos) < d->attachedArgsNum_)
939 --d->attachedArgsNum_;
940 if (size_t(pos) < d->optionals_) {
944 d->needsUpdate_ = true;
949 void MathMacro::insertArgument(Inset::pos_type pos) {
950 if (d->displayMode_ == DISPLAY_NORMAL) {
951 LASSERT(size_t(pos) <= cells_.size(), return);
952 cells_.insert(cells_.begin() + pos, MathData());
953 if (size_t(pos) < d->attachedArgsNum_)
954 ++d->attachedArgsNum_;
955 if (size_t(pos) < d->optionals_)
958 d->needsUpdate_ = true;
963 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
965 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
968 // strip off empty cells, but not more than arity-attachedArgsNum_
971 for (i = cells_.size(); i > d->attachedArgsNum_; --i)
972 if (!cell(i - 1).empty()) break;
976 d->attachedArgsNum_ = 0;
977 d->expanded_ = MathData();
980 d->needsUpdate_ = true;
984 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
986 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
988 d->attachedArgsNum_ = args.size();
989 cells_.resize(arity);
990 d->expanded_ = MathData();
991 d->optionals_ = optionals;
993 d->needsUpdate_ = true;
997 bool MathMacro::idxFirst(Cursor & cur) const
999 cur.screenUpdateFlags(Update::SinglePar);
1000 return InsetMathNest::idxFirst(cur);
1004 bool MathMacro::idxLast(Cursor & cur) const
1006 cur.screenUpdateFlags(Update::SinglePar);
1007 return InsetMathNest::idxLast(cur);
1011 bool MathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
1013 if (d->displayMode_ == DISPLAY_UNFOLDED) {
1014 docstring const & unfolded_name = name();
1015 if (unfolded_name != d->name_) {
1016 // The macro name was changed
1017 Cursor inset_cursor = old;
1018 int macroSlice = inset_cursor.find(this);
1019 // returning true means the cursor is "now" invalid,
1021 LASSERT(macroSlice != -1, return true);
1022 inset_cursor.cutOff(macroSlice);
1023 inset_cursor.recordUndoInset();
1025 inset_cursor.cell().erase(inset_cursor.pos());
1026 inset_cursor.cell().insert(inset_cursor.pos(),
1027 createInsetMath(unfolded_name, cur.buffer()));
1029 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
1033 cur.screenUpdateFlags(Update::Force);
1034 return InsetMathNest::notifyCursorLeaves(old, cur);
1038 void MathMacro::fold(Cursor & cur)
1040 if (!d->nextFoldMode_) {
1041 d->nextFoldMode_ = true;
1042 cur.screenUpdateFlags(Update::SinglePar);
1047 void MathMacro::unfold(Cursor & cur)
1049 if (d->nextFoldMode_) {
1050 d->nextFoldMode_ = false;
1051 cur.screenUpdateFlags(Update::SinglePar);
1056 bool MathMacro::folded() const
1058 return d->nextFoldMode_;
1062 void MathMacro::write(WriteStream & os) const
1064 mode_type mode = modeToEnsure();
1065 bool textmode_macro = mode == TEXT_MODE;
1066 bool needs_mathmode = mode == MATH_MODE;
1067 MathEnsurer ensurer(os, needs_mathmode, true, textmode_macro);
1070 if (d->displayMode_ != DISPLAY_NORMAL) {
1071 os << "\\" << name();
1072 if (name().size() != 1 || isAlphaASCII(name()[0]))
1073 os.pendingSpace(true);
1078 // we should be ok to continue even if this fails.
1081 // We may already be in the argument of a macro
1082 bool const inside_macro = os.insideMacro();
1083 os.insideMacro(true);
1085 // Enclose in braces to avoid latex errors with xargs if we have
1086 // optional arguments and are in the optional argument of a macro
1087 if (d->optionals_ && inside_macro)
1090 // Always protect macros in a fragile environment
1094 os << "\\" << name();
1097 // Optional arguments:
1098 // First find last non-empty optional argument
1099 idx_type emptyOptFrom = 0;
1101 for (; i < cells_.size() && i < d->optionals_; ++i) {
1102 if (!cell(i).empty())
1103 emptyOptFrom = i + 1;
1106 // print out optionals
1107 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
1109 os << "[" << cell(i) << "]";
1112 // skip the tailing empty optionals
1115 // Print remaining arguments
1116 for (; i < cells_.size(); ++i) {
1117 if (cell(i).size() == 1
1118 && cell(i)[0].nucleus()->asCharInset()
1119 && isASCII(cell(i)[0].nucleus()->asCharInset()->getChar())) {
1124 os << "{" << cell(i) << "}";
1128 // Close the opened brace or add space if there was no argument
1129 if (d->optionals_ && inside_macro)
1132 os.pendingSpace(true);
1134 os.insideMacro(inside_macro);
1138 void MathMacro::maple(MapleStream & os) const
1140 lyx::maple(d->expanded_, os);
1144 void MathMacro::maxima(MaximaStream & os) const
1146 lyx::maxima(d->expanded_, os);
1150 void MathMacro::mathematica(MathematicaStream & os) const
1152 lyx::mathematica(d->expanded_, os);
1156 void MathMacro::mathmlize(MathStream & os) const
1158 // macro_ is 0 if this is an unknown macro
1159 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1161 docstring const xmlname = d->macro_->xmlname();
1162 if (!xmlname.empty()) {
1163 char const * type = d->macro_->MathMLtype();
1164 os << '<' << type << "> " << xmlname << " </"
1169 if (d->expanded_.empty()) {
1170 // this means that we do not recognize the macro
1171 throw MathExportException();
1177 void MathMacro::htmlize(HtmlStream & os) const
1179 // macro_ is 0 if this is an unknown macro
1180 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1182 docstring const xmlname = d->macro_->xmlname();
1183 if (!xmlname.empty()) {
1184 os << ' ' << xmlname << ' ';
1188 if (d->expanded_.empty()) {
1189 // this means that we do not recognize the macro
1190 throw MathExportException();
1196 void MathMacro::octave(OctaveStream & os) const
1198 lyx::octave(d->expanded_, os);
1202 void MathMacro::infoize(odocstream & os) const
1204 os << bformat(_("Macro: %1$s"), name());
1208 void MathMacro::infoize2(odocstream & os) const
1210 os << bformat(_("Macro: %1$s"), name());
1214 bool MathMacro::completionSupported(Cursor const & cur) const
1216 if (displayMode() != DISPLAY_UNFOLDED)
1217 return InsetMathNest::completionSupported(cur);
1219 return lyxrc.completion_popup_math
1220 && displayMode() == DISPLAY_UNFOLDED
1221 && cur.bv().cursor().pos() == int(name().size());
1225 bool MathMacro::inlineCompletionSupported(Cursor const & cur) const
1227 if (displayMode() != DISPLAY_UNFOLDED)
1228 return InsetMathNest::inlineCompletionSupported(cur);
1230 return lyxrc.completion_inline_math
1231 && displayMode() == DISPLAY_UNFOLDED
1232 && cur.bv().cursor().pos() == int(name().size());
1236 bool MathMacro::automaticInlineCompletion() const
1238 if (displayMode() != DISPLAY_UNFOLDED)
1239 return InsetMathNest::automaticInlineCompletion();
1241 return lyxrc.completion_inline_math;
1245 bool MathMacro::automaticPopupCompletion() const
1247 if (displayMode() != DISPLAY_UNFOLDED)
1248 return InsetMathNest::automaticPopupCompletion();
1250 return lyxrc.completion_popup_math;
1254 CompletionList const *
1255 MathMacro::createCompletionList(Cursor const & cur) const
1257 if (displayMode() != DISPLAY_UNFOLDED)
1258 return InsetMathNest::createCompletionList(cur);
1260 return new MathCompletionList(cur.bv().cursor());
1264 docstring MathMacro::completionPrefix(Cursor const & cur) const
1266 if (displayMode() != DISPLAY_UNFOLDED)
1267 return InsetMathNest::completionPrefix(cur);
1269 if (!completionSupported(cur))
1272 return "\\" + name();
1276 bool MathMacro::insertCompletion(Cursor & cur, docstring const & s,
1279 if (displayMode() != DISPLAY_UNFOLDED)
1280 return InsetMathNest::insertCompletion(cur, s, finished);
1282 if (!completionSupported(cur))
1285 // append completion
1286 docstring newName = name() + s;
1287 asArray(newName, cell(0));
1288 cur.bv().cursor().pos() = name().size();
1289 cur.screenUpdateFlags(Update::SinglePar);
1293 cur.bv().cursor().pop();
1294 ++cur.bv().cursor().pos();
1295 cur.screenUpdateFlags(Update::SinglePar);
1302 void MathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
1303 Dimension & dim) const
1305 if (displayMode() != DISPLAY_UNFOLDED)
1306 InsetMathNest::completionPosAndDim(cur, x, y, dim);
1308 // get inset dimensions
1309 dim = cur.bv().coordCache().insets().dim(this);
1310 // FIXME: these 3 are no accurate, but should depend on the font.
1311 // Now the popup jumps down if you enter a char with descent > 0.
1317 = cur.bv().coordCache().insets().xy(this);