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 marker_type marker() const { return NO_MARKER; }
72 InsetCode lyxCode() const { return ARGUMENT_PROXY_CODE; }
73 /// The math data to use for display
74 MathData const & displayCell(BufferView const * bv) const
76 // handle default macro arguments
77 bool use_def_arg = !mathMacro_->editMetrics(bv)
78 && mathMacro_->cell(idx_).empty();
79 return use_def_arg ? def_ : mathMacro_->cell(idx_);
82 bool addToMathRow(MathRow & mrow, MetricsInfo & mi) const
84 // macro arguments are in macros
85 LATTEST(mathMacro_->nesting() > 0);
86 /// The macro nesting can change display of insets. Change it locally.
87 Changer chg = make_change(mi.base.macro_nesting,
88 mathMacro_->nesting() == 1 ? 0 : mathMacro_->nesting());
90 MathRow::Element e_beg(mi, MathRow::BEG_ARG);
92 e_beg.ar = &mathMacro_->cell(idx_);
93 mrow.push_back(e_beg);
95 mathMacro_->macro()->unlock();
96 bool has_contents = displayCell(mi.base.bv).addToMathRow(mrow, mi);
97 mathMacro_->macro()->lock();
99 // if there was no contents, and the contents is editable,
100 // then we insert a box instead.
101 if (!has_contents && mathMacro_->nesting() == 1) {
102 // mathclass is ord because it should be spaced as a normal atom
103 MathRow::Element e(mi, MathRow::BOX, MC_ORD);
104 e.color = Color_mathline;
109 MathRow::Element e_end(mi, MathRow::END_ARG);
111 e_end.ar = &mathMacro_->cell(idx_);
113 mrow.push_back(e_end);
118 void beforeMetrics() const
120 mathMacro_->macro()->unlock();
123 void afterMetrics() const
125 mathMacro_->macro()->lock();
128 void beforeDraw(PainterInfo const & pi) const
130 // if the macro is being edited, then the painter is in
132 if (mathMacro_->editMetrics(pi.base.bv))
133 pi.pain.leaveMonochromeMode();
136 void afterDraw(PainterInfo const & pi) const
138 if (mathMacro_->editMetrics(pi.base.bv))
139 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
142 void metrics(MetricsInfo &, Dimension &) const {
143 // This should never be invoked, since ArgumentProxy insets are linearized
147 void draw(PainterInfo &, int, int) const {
148 // This should never be invoked, since ArgumentProxy insets are linearized
152 int kerning(BufferView const * bv) const
154 return displayCell(bv).kerning(bv);
156 // write(), normalize(), infoize() and infoize2() are not needed since
157 // MathMacro uses the definition and not the expanded cells.
159 void maple(MapleStream & ms) const { ms << mathMacro_->cell(idx_); }
161 void maxima(MaximaStream & ms) const { ms << mathMacro_->cell(idx_); }
163 void mathematica(MathematicaStream & ms) const { ms << mathMacro_->cell(idx_); }
165 void mathmlize(MathStream & ms) const { ms << mathMacro_->cell(idx_); }
167 void htmlize(HtmlStream & ms) const { ms << mathMacro_->cell(idx_); }
169 void octave(OctaveStream & os) const { os << mathMacro_->cell(idx_); }
171 MathClass mathClass() const
174 // This can be refined once the pointer issues are fixed. I did not
175 // notice any immediate crash with the following code, but it is risky
177 //return mathMacro_->cell(idx_).mathClass();
182 Inset * clone() const
184 return new ArgumentProxy(*this);
187 MathMacro * mathMacro_;
195 /// Private implementation of MathMacro
196 class MathMacro::Private {
198 Private(Buffer * buf, docstring const & name)
199 : name_(name), displayMode_(DISPLAY_INIT),
200 expanded_(buf), definition_(buf), attachedArgsNum_(0),
201 optionals_(0), nextFoldMode_(true), macroBackup_(buf),
202 macro_(0), needsUpdate_(false), isUpdating_(false),
206 /// Update the pointers to our owner of all expanded macros.
207 /// This needs to be called every time a copy of the owner is created
209 void updateChildren(MathMacro * owner);
210 /// Recursively update the pointers of all expanded macros
211 /// appearing in the arguments of the current macro
212 void updateNestedChildren(MathMacro * owner, InsetMathNest * ni);
215 /// current display mode
216 DisplayMode displayMode_;
217 /// expanded macro with ArgumentProxies
219 /// macro definition with #1,#2,.. insets
220 MathData definition_;
221 /// number of arguments that were really attached
222 size_t attachedArgsNum_;
223 /// optional argument attached? (only in DISPLAY_NORMAL mode)
225 /// fold mode to be set in next metrics call?
227 /// if macro_ == true, then here is a copy of the macro
228 /// don't use it for locking
229 MacroData macroBackup_;
230 /// if macroNotFound_ == false, then here is a reference to the macro
231 /// this might invalidate after metrics was called
232 MacroData const * macro_;
234 mutable std::map<BufferView const *, bool> editing_;
236 std::string requires_;
237 /// update macro representation
241 /// maximal number of arguments the macro is greedy for
243 /// Level of nesting in macros (including this one)
248 void MathMacro::Private::updateChildren(MathMacro * owner)
250 for (size_t i = 0; i < expanded_.size(); ++i) {
251 ArgumentProxy * p = dynamic_cast<ArgumentProxy *>(expanded_[i].nucleus());
255 InsetMathNest * ni = expanded_[i].nucleus()->asNestInset();
257 updateNestedChildren(owner, ni);
261 // The macro_ pointer is updated when MathData::metrics() is
262 // called. However, when instant preview is on or the macro is
263 // not on screen, MathData::metrics() is not called and we may
264 // have a dangling pointer. As a safety measure, when a macro
265 // is copied, always let macro_ point to the backup copy of the
266 // MacroData structure. This backup is updated every time the
267 // macro is changed, so it will not become stale.
268 macro_ = ¯oBackup_;
273 void MathMacro::Private::updateNestedChildren(MathMacro * owner, InsetMathNest * ni)
275 for (size_t i = 0; i < ni->nargs(); ++i) {
276 MathData & ar = ni->cell(i);
277 for (size_t j = 0; j < ar.size(); ++j) {
278 ArgumentProxy * ap = dynamic_cast
279 <ArgumentProxy *>(ar[j].nucleus());
281 MathMacro::Private * md = ap->owner()->d;
283 md->macro_ = &md->macroBackup_;
286 InsetMathNest * imn = ar[j].nucleus()->asNestInset();
288 updateNestedChildren(owner, imn);
294 MathMacro::MathMacro(Buffer * buf, docstring const & name)
295 : InsetMathNest(buf, 0), d(new Private(buf, name))
299 MathMacro::MathMacro(MathMacro const & that)
300 : InsetMathNest(that), d(new Private(*that.d))
302 setBuffer(*that.buffer_);
303 d->updateChildren(this);
307 MathMacro & MathMacro::operator=(MathMacro const & that)
311 InsetMathNest::operator=(that);
313 d->updateChildren(this);
318 MathMacro::~MathMacro()
324 bool MathMacro::addToMathRow(MathRow & mrow, MetricsInfo & mi) const
326 // set edit mode for which we will have calculated row.
327 // This is the same as what is done in metrics().
328 d->editing_[mi.base.bv] = editMode(mi.base.bv);
330 // For now we do not linearize in the following cases (can be improved)
331 // - display mode different from normal
332 // - editing with parameter list
333 // - editing with box around macro
334 if (displayMode() != MathMacro::DISPLAY_NORMAL
335 || (d->editing_[mi.base.bv] && lyxrc.macro_edit_style != LyXRC::MACRO_EDIT_INLINE))
336 return InsetMath::addToMathRow(mrow, mi);
338 /// The macro nesting can change display of insets. Change it locally.
339 Changer chg = make_change(mi.base.macro_nesting, d->nesting_);
341 MathRow::Element e_beg(mi, MathRow::BEG_MACRO);
343 e_beg.marker = (d->nesting_ == 1 && nargs()) ? marker() : NO_MARKER;
344 mrow.push_back(e_beg);
347 bool has_contents = d->expanded_.addToMathRow(mrow, mi);
350 // if there was no contents and the array is editable, then we
351 // insert a grey box instead.
352 if (!has_contents && mi.base.macro_nesting == 1) {
353 // mathclass is unknown because it is irrelevant for spacing
354 MathRow::Element e(mi, MathRow::BOX);
355 e.color = Color_mathmacroblend;
360 MathRow::Element e_end(mi, MathRow::END_MACRO);
362 mrow.push_back(e_end);
367 void MathMacro::beforeMetrics() const
373 void MathMacro::afterMetrics() const
379 void MathMacro::beforeDraw(PainterInfo const & pi) const
381 if (d->editing_[pi.base.bv])
382 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
386 void MathMacro::afterDraw(PainterInfo const & pi) const
388 if (d->editing_[pi.base.bv])
389 pi.pain.leaveMonochromeMode();
393 Inset * MathMacro::clone() const
395 MathMacro * copy = new MathMacro(*this);
396 copy->d->needsUpdate_ = true;
397 //copy->d->expanded_.clear();
402 void MathMacro::normalize(NormalStream & os) const
404 os << "[macro " << name();
405 for (size_t i = 0; i < nargs(); ++i)
406 os << ' ' << cell(i);
411 MathMacro::DisplayMode MathMacro::displayMode() const
413 return d->displayMode_;
417 bool MathMacro::extraBraces() const
419 return d->displayMode_ == DISPLAY_NORMAL && arity() > 0;
423 docstring MathMacro::name() const
425 if (d->displayMode_ == DISPLAY_UNFOLDED)
426 return asString(cell(0));
432 docstring MathMacro::macroName() const
438 int MathMacro::nesting() const
444 void MathMacro::cursorPos(BufferView const & bv,
445 CursorSlice const & sl, bool boundary, int & x, int & y) const
447 // We may have 0 arguments, but InsetMathNest requires at least one.
449 InsetMathNest::cursorPos(bv, sl, boundary, x, y);
453 bool MathMacro::editMode(BufferView const * bv) const {
454 // find this in cursor trace
455 Cursor const & cur = bv->cursor();
456 for (size_t i = 0; i != cur.depth(); ++i)
457 if (&cur[i].inset() == this) {
458 // look if there is no other macro in edit mode above
460 for (; i != cur.depth(); ++i) {
461 InsetMath * im = cur[i].asInsetMath();
463 MathMacro const * macro = im->asMacro();
464 if (macro && macro->displayMode() == DISPLAY_NORMAL)
469 // ok, none found, I am the highest one
477 MacroData const * MathMacro::macro() const
483 bool MathMacro::editMetrics(BufferView const * bv) const
485 return d->editing_[bv];
489 Inset::marker_type MathMacro::marker() const
491 switch (d->displayMode_) {
493 case DISPLAY_INTERACTIVE_INIT:
495 case DISPLAY_UNFOLDED:
498 switch (lyxrc.macro_edit_style) {
499 case LyXRC::MACRO_EDIT_LIST:
501 case LyXRC::MACRO_EDIT_INLINE_BOX:
510 void MathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
512 /// The macro nesting can change display of insets. Change it locally.
513 Changer chg = make_change(mi.base.macro_nesting, d->nesting_);
515 // set edit mode for which we will have calculated metrics. But only
516 d->editing_[mi.base.bv] = editMode(mi.base.bv);
518 // calculate new metrics according to display mode
519 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
520 Changer dummy = mi.base.changeFontSet("lyxtex");
521 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
522 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
523 Changer dummy = mi.base.changeFontSet("lyxtex");
524 cell(0).metrics(mi, dim);
526 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
527 dim.wid += bsdim.width() + 1;
528 dim.asc = max(bsdim.ascent(), dim.ascent());
529 dim.des = max(bsdim.descent(), dim.descent());
530 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
531 && d->editing_[mi.base.bv]) {
532 // Macro will be edited in a old-style list mode here:
536 FontInfo labelFont = sane_font;
537 math_font_max_dim(labelFont, fontDim.asc, fontDim.des);
539 // get dimension of components of list view
541 nameDim.wid = mathed_string_width(mi.base.font, from_ascii("Macro \\") + name() + ": ");
542 nameDim.asc = fontDim.asc;
543 nameDim.des = fontDim.des;
546 argDim.wid = mathed_string_width(labelFont, from_ascii("#9: "));
547 argDim.asc = fontDim.asc;
548 argDim.des = fontDim.des;
551 d->definition_.metrics(mi, defDim);
554 dim.wid = nameDim.wid + defDim.wid;
555 dim.asc = max(nameDim.asc, defDim.asc);
556 dim.des = max(nameDim.des, defDim.des);
558 for (idx_type i = 0; i < nargs(); ++i) {
560 cell(i).metrics(mi, cdim);
561 dim.des += max(argDim.height(), cdim.height()) + 1;
562 dim.wid = max(dim.wid, argDim.wid + cdim.wid);
565 // make space for box and markers, 2 pixels
572 // calculate metrics, hoping that all cells are seen
574 d->expanded_.metrics(mi, dim);
576 // otherwise do a manual metrics call
577 CoordCache & coords = mi.base.bv->coordCache();
578 for (idx_type i = 0; i < nargs(); ++i) {
579 if (!coords.getArrays().hasDim(&cell(i))) {
581 cell(i).metrics(mi, tdim);
586 // calculate dimension with label while editing
587 if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX
588 && d->editing_[mi.base.bv]) {
589 FontInfo font = mi.base.font;
590 augmentFont(font, "lyxtex");
592 mathed_string_dim(font, name(), namedim);
594 dim.wid += 2 + namedim.wid + 2 + 2;
595 dim.asc = max(dim.asc, namedim.asc) + 2;
596 dim.des = max(dim.des, namedim.des) + 2;
598 dim.wid = max(1 + namedim.wid + 1, 2 + dim.wid + 2);
599 dim.asc += 1 + namedim.height() + 1;
606 int MathMacro::kerning(BufferView const * bv) const {
607 if (d->displayMode_ == DISPLAY_NORMAL && !d->editing_[bv])
608 return d->expanded_.kerning(bv);
614 void MathMacro::updateMacro(MacroContext const & mc)
617 d->macro_ = mc.get(name());
618 if (d->macro_ && d->macroBackup_ != *d->macro_) {
619 d->macroBackup_ = *d->macro_;
620 d->needsUpdate_ = true;
628 class MathMacro::UpdateLocker
631 explicit UpdateLocker(MathMacro & mm) : mac(mm)
633 mac.d->isUpdating_ = true;
635 ~UpdateLocker() { mac.d->isUpdating_ = false; }
639 /** Avoid wrong usage of UpdateLocker.
640 To avoid wrong usage:
641 UpdateLocker(...); // wrong
642 UpdateLocker locker(...); // right
644 #define UpdateLocker(x) unnamed_UpdateLocker;
645 // Tip gotten from Bobby Schmidt's column in C/C++ Users Journal
648 void MathMacro::updateRepresentation(Cursor * cur, MacroContext const & mc,
649 UpdateType utype, int nesting)
651 // block recursive calls (bug 8999)
655 UpdateLocker locker(*this);
661 // remember nesting level of this macro
662 d->nesting_ = nesting;
665 d->requires_ = d->macro_->requires();
668 // non-normal mode? We are done!
669 || (d->displayMode_ != DISPLAY_NORMAL))
672 d->needsUpdate_ = false;
674 // get default values of macro
675 vector<docstring> const & defaults = d->macro_->defaults();
677 // create MathMacroArgumentValue objects pointing to the cells of the macro
678 vector<MathData> values(nargs());
679 for (size_t i = 0; i < nargs(); ++i) {
680 ArgumentProxy * proxy;
681 if (i < defaults.size())
682 proxy = new ArgumentProxy(this, i, defaults[i]);
684 proxy = new ArgumentProxy(this, i);
685 values[i].insert(0, MathAtom(proxy));
687 // expanding macro with the values
688 // Only update the argument macros if anything was expanded, otherwise
689 // we would get an endless loop (bug 9140). UpdateLocker does not work
690 // in this case, since MacroData::expand() creates new MathMacro
691 // objects, so this would be a different recursion path than the one
692 // protected by UpdateLocker.
693 if (d->macro_->expand(values, d->expanded_)) {
694 if (utype == OutputUpdate && !d->expanded_.empty())
695 d->expanded_.updateMacros(cur, mc, utype, nesting);
697 // get definition for list edit mode
698 docstring const & display = d->macro_->display();
699 asArray(display.empty() ? d->macro_->definition() : display,
700 d->definition_, Parse::QUIET);
704 void MathMacro::draw(PainterInfo & pi, int x, int y) const
706 Dimension const dim = dimension(*pi.base.bv);
711 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
712 Changer dummy = pi.base.changeFontSet("lyxtex");
713 pi.pain.text(x, y, from_ascii("\\") + name(), pi.base.font);
714 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
715 Changer dummy = pi.base.changeFontSet("lyxtex");
716 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
717 x += mathed_string_width(pi.base.font, from_ascii("\\")) + 1;
718 cell(0).draw(pi, x, y);
719 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
720 && d->editing_[pi.base.bv]) {
721 // Macro will be edited in a old-style list mode here:
723 CoordCache const & coords = pi.base.bv->coordCache();
724 FontInfo const & labelFont = sane_font;
726 // box needs one pixel
729 // get maximal font height
731 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
734 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
735 pi.pain.text(x, y, label, labelFont);
736 x += mathed_string_width(labelFont, label);
739 d->definition_.draw(pi, x, y);
740 Dimension const & defDim = coords.getArrays().dim(&d->definition_);
741 y += max(fontDim.des, defDim.des);
744 docstring str = from_ascii("#9");
745 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
746 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
748 for (idx_type i = 0; i < nargs(); ++i) {
750 Dimension const & cdim = coords.getArrays().dim(&cell(i));
752 y += max(fontDim.asc, cdim.asc) + 1;
756 pi.pain.text(x, y, str, labelFont);
758 pi.pain.text(x, y, from_ascii(":"), labelFont);
762 cell(i).draw(pi, x, y);
765 y += max(fontDim.des, cdim.des);
768 pi.pain.rectangle(expx, expy - dim.asc + 1, dim.wid - 3,
769 dim.height() - 2, Color_mathmacroframe);
771 bool drawBox = lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX
772 && d->editing_[pi.base.bv];
775 for (size_t i = 0; i < nargs(); ++i)
776 cell(i).setXY(*pi.base.bv, x, y);
779 // draw header and rectangle around
780 FontInfo font = pi.base.font;
781 augmentFont(font, "lyxtex");
782 font.setSize(FONT_SIZE_TINY);
783 font.setColor(Color_mathmacrolabel);
785 mathed_string_dim(font, name(), namedim);
787 pi.pain.fillRectangle(x, y - dim.asc, dim.wid, 1 + namedim.height() + 1, Color_mathmacrobg);
788 pi.pain.text(x + 1, y - dim.asc + namedim.asc + 2, name(), font);
789 expx += (dim.wid - d->expanded_.dimension(*pi.base.bv).width()) / 2;
793 d->expanded_.draw(pi, expx, expy);
797 pi.pain.rectangle(x, y - dim.asc, dim.wid,
798 dim.height(), Color_mathmacroframe);
801 // edit mode changed?
802 if (d->editing_[pi.base.bv] != editMode(pi.base.bv))
803 pi.base.bv->cursor().screenUpdateFlags(Update::SinglePar);
807 void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
809 // We may have 0 arguments, but InsetMathNest requires at least one.
811 InsetMathNest::drawSelection(pi, x, y);
815 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode, int appetite)
817 if (d->displayMode_ != mode) {
818 // transfer name if changing from or to DISPLAY_UNFOLDED
819 if (mode == DISPLAY_UNFOLDED) {
821 asArray(d->name_, cell(0));
822 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
823 d->name_ = asString(cell(0));
827 d->displayMode_ = mode;
828 d->needsUpdate_ = true;
831 // the interactive init mode is non-greedy by default
833 d->appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
835 d->appetite_ = size_t(appetite);
839 MathMacro::DisplayMode MathMacro::computeDisplayMode() const
841 if (d->nextFoldMode_ == true && d->macro_ && !d->macro_->locked())
842 return DISPLAY_NORMAL;
844 return DISPLAY_UNFOLDED;
848 bool MathMacro::validName() const
850 docstring n = name();
855 // converting back and force doesn't swallow anything?
858 if (asString(ma) != n)
862 for (size_t i = 0; i<n.size(); ++i) {
863 if (!(n[i] >= 'a' && n[i] <= 'z')
864 && !(n[i] >= 'A' && n[i] <= 'Z')
873 size_t MathMacro::arity() const
875 if (d->displayMode_ == DISPLAY_NORMAL )
876 return cells_.size();
882 size_t MathMacro::optionals() const
884 return d->optionals_;
888 void MathMacro::setOptionals(int n)
890 if (n <= int(nargs()))
895 size_t MathMacro::appetite() const
901 MathClass MathMacro::mathClass() const
903 // This can be just a heuristic, since it is only considered for display
904 // when the macro is not linearised. Therefore it affects:
905 // * The spacing of the inset while being edited,
906 // * Intelligent splitting
907 // * Cursor word movement (Ctrl-Arrow).
908 if (MacroData const * m = macroBackup()) {
909 // If it is a global macro and is defined explicitly
911 MathClass mc = string_to_class(m->symbol()->extra);
912 if (mc != MC_UNKNOWN)
916 // Otherwise guess from the expanded macro
917 return d->expanded_.mathClass();
921 InsetMath::mode_type MathMacro::currentMode() const
923 // There is no way to guess the mode of user defined macros, so they are
924 // always assumed to be mathmode. Only the global macros defined in
925 // lib/symbols may be textmode.
926 mode_type mode = modeToEnsure();
927 return (mode == UNDECIDED_MODE) ? MATH_MODE : mode;
931 InsetMath::mode_type MathMacro::modeToEnsure() const
933 // User defined macros can be either text mode or math mode for output and
934 // display. There is no way to guess. For global macros defined in
935 // lib/symbols, we ensure textmode if flagged as such, otherwise we ensure
937 if (MacroData const * m = macroBackup())
939 return (m->symbol()->extra == "textmode") ? TEXT_MODE : MATH_MODE;
940 return UNDECIDED_MODE;
944 MacroData const * MathMacro::macroBackup() const
947 return &d->macroBackup_;
948 if (MacroData const * data = MacroTable::globalMacros().get(name()))
954 void MathMacro::validate(LaTeXFeatures & features) const
956 // Immediately after a document is loaded, in some cases the MacroData
957 // of the global macros defined in the lib/symbols file may still not
958 // be known to the macro machinery because it will be set only after
959 // the first call to updateMacros(). This is not a problem unless
960 // instant preview is on for math, in which case we will be missing
961 // the corresponding requirements.
962 // In this case, we get the required info from the global macro table.
963 if (!d->requires_.empty())
964 features.require(d->requires_);
965 else if (!d->macro_) {
966 // Update requires for known global macros.
967 MacroData const * data = MacroTable::globalMacros().get(name());
968 if (data && !data->requires().empty())
969 features.require(data->requires());
972 if (name() == "binom")
973 features.require("binom");
975 // validate the cells and the definition
976 if (displayMode() == DISPLAY_NORMAL) {
977 d->definition_.validate(features);
978 InsetMathNest::validate(features);
983 void MathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
985 cur.screenUpdateFlags(Update::SinglePar);
986 InsetMathNest::edit(cur, front, entry_from);
990 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
992 // We may have 0 arguments, but InsetMathNest requires at least one.
994 cur.screenUpdateFlags(Update::SinglePar);
995 return InsetMathNest::editXY(cur, x, y);
1001 void MathMacro::removeArgument(Inset::pos_type pos) {
1002 if (d->displayMode_ == DISPLAY_NORMAL) {
1003 LASSERT(size_t(pos) < cells_.size(), return);
1004 cells_.erase(cells_.begin() + pos);
1005 if (size_t(pos) < d->attachedArgsNum_)
1006 --d->attachedArgsNum_;
1007 if (size_t(pos) < d->optionals_) {
1011 d->needsUpdate_ = true;
1016 void MathMacro::insertArgument(Inset::pos_type pos) {
1017 if (d->displayMode_ == DISPLAY_NORMAL) {
1018 LASSERT(size_t(pos) <= cells_.size(), return);
1019 cells_.insert(cells_.begin() + pos, MathData());
1020 if (size_t(pos) < d->attachedArgsNum_)
1021 ++d->attachedArgsNum_;
1022 if (size_t(pos) < d->optionals_)
1025 d->needsUpdate_ = true;
1030 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
1032 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
1035 // strip off empty cells, but not more than arity-attachedArgsNum_
1038 for (i = cells_.size(); i > d->attachedArgsNum_; --i)
1039 if (!cell(i - 1).empty()) break;
1043 d->attachedArgsNum_ = 0;
1044 d->expanded_ = MathData();
1047 d->needsUpdate_ = true;
1051 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
1053 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
1055 d->attachedArgsNum_ = args.size();
1056 cells_.resize(arity);
1057 d->expanded_ = MathData();
1058 d->optionals_ = optionals;
1060 d->needsUpdate_ = true;
1064 bool MathMacro::idxFirst(Cursor & cur) const
1066 cur.screenUpdateFlags(Update::SinglePar);
1067 return InsetMathNest::idxFirst(cur);
1071 bool MathMacro::idxLast(Cursor & cur) const
1073 cur.screenUpdateFlags(Update::SinglePar);
1074 return InsetMathNest::idxLast(cur);
1078 bool MathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
1080 if (d->displayMode_ == DISPLAY_UNFOLDED) {
1081 docstring const & unfolded_name = name();
1082 if (unfolded_name != d->name_) {
1083 // The macro name was changed
1084 Cursor inset_cursor = old;
1085 int macroSlice = inset_cursor.find(this);
1086 // returning true means the cursor is "now" invalid,
1088 LASSERT(macroSlice != -1, return true);
1089 inset_cursor.cutOff(macroSlice);
1090 inset_cursor.recordUndoInset();
1092 inset_cursor.cell().erase(inset_cursor.pos());
1093 inset_cursor.cell().insert(inset_cursor.pos(),
1094 createInsetMath(unfolded_name, cur.buffer()));
1096 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
1100 cur.screenUpdateFlags(Update::Force);
1101 return InsetMathNest::notifyCursorLeaves(old, cur);
1105 void MathMacro::fold(Cursor & cur)
1107 if (!d->nextFoldMode_) {
1108 d->nextFoldMode_ = true;
1109 cur.screenUpdateFlags(Update::SinglePar);
1114 void MathMacro::unfold(Cursor & cur)
1116 if (d->nextFoldMode_) {
1117 d->nextFoldMode_ = false;
1118 cur.screenUpdateFlags(Update::SinglePar);
1123 bool MathMacro::folded() const
1125 return d->nextFoldMode_;
1129 void MathMacro::write(WriteStream & os) const
1131 mode_type mode = modeToEnsure();
1132 bool textmode_macro = mode == TEXT_MODE;
1133 bool needs_mathmode = mode == MATH_MODE;
1134 MathEnsurer ensurer(os, needs_mathmode, true, textmode_macro);
1137 if (d->displayMode_ != DISPLAY_NORMAL) {
1138 os << "\\" << name();
1139 if (name().size() != 1 || isAlphaASCII(name()[0]))
1140 os.pendingSpace(true);
1145 // we should be ok to continue even if this fails.
1148 // We may already be in the argument of a macro
1149 bool const inside_macro = os.insideMacro();
1150 os.insideMacro(true);
1152 // Enclose in braces to avoid latex errors with xargs if we have
1153 // optional arguments and are in the optional argument of a macro
1154 if (d->optionals_ && inside_macro)
1157 // Always protect macros in a fragile environment
1161 os << "\\" << name();
1164 // Optional arguments:
1165 // First find last non-empty optional argument
1166 idx_type emptyOptFrom = 0;
1168 for (; i < cells_.size() && i < d->optionals_; ++i) {
1169 if (!cell(i).empty())
1170 emptyOptFrom = i + 1;
1173 // print out optionals
1174 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
1176 os << "[" << cell(i) << "]";
1179 // skip the tailing empty optionals
1182 // Print remaining arguments
1183 for (; i < cells_.size(); ++i) {
1184 if (cell(i).size() == 1
1185 && cell(i)[0].nucleus()->asCharInset()
1186 && isASCII(cell(i)[0].nucleus()->asCharInset()->getChar())) {
1191 os << "{" << cell(i) << "}";
1195 // Close the opened brace or add space if there was no argument
1196 if (d->optionals_ && inside_macro)
1199 os.pendingSpace(true);
1201 os.insideMacro(inside_macro);
1205 void MathMacro::maple(MapleStream & os) const
1207 lyx::maple(d->expanded_, os);
1211 void MathMacro::maxima(MaximaStream & os) const
1213 lyx::maxima(d->expanded_, os);
1217 void MathMacro::mathematica(MathematicaStream & os) const
1219 lyx::mathematica(d->expanded_, os);
1223 void MathMacro::mathmlize(MathStream & os) const
1225 // macro_ is 0 if this is an unknown macro
1226 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1228 docstring const xmlname = d->macro_->xmlname();
1229 if (!xmlname.empty()) {
1230 char const * type = d->macro_->MathMLtype();
1231 os << '<' << type << "> " << xmlname << " </"
1236 if (d->expanded_.empty()) {
1237 // this means that we do not recognize the macro
1238 throw MathExportException();
1244 void MathMacro::htmlize(HtmlStream & os) const
1246 // macro_ is 0 if this is an unknown macro
1247 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1249 docstring const xmlname = d->macro_->xmlname();
1250 if (!xmlname.empty()) {
1251 os << ' ' << xmlname << ' ';
1255 if (d->expanded_.empty()) {
1256 // this means that we do not recognize the macro
1257 throw MathExportException();
1263 void MathMacro::octave(OctaveStream & os) const
1265 lyx::octave(d->expanded_, os);
1269 void MathMacro::infoize(odocstream & os) const
1271 os << bformat(_("Macro: %1$s"), name());
1275 void MathMacro::infoize2(odocstream & os) const
1277 os << bformat(_("Macro: %1$s"), name());
1281 bool MathMacro::completionSupported(Cursor const & cur) const
1283 if (displayMode() != DISPLAY_UNFOLDED)
1284 return InsetMathNest::completionSupported(cur);
1286 return lyxrc.completion_popup_math
1287 && displayMode() == DISPLAY_UNFOLDED
1288 && cur.bv().cursor().pos() == int(name().size());
1292 bool MathMacro::inlineCompletionSupported(Cursor const & cur) const
1294 if (displayMode() != DISPLAY_UNFOLDED)
1295 return InsetMathNest::inlineCompletionSupported(cur);
1297 return lyxrc.completion_inline_math
1298 && displayMode() == DISPLAY_UNFOLDED
1299 && cur.bv().cursor().pos() == int(name().size());
1303 bool MathMacro::automaticInlineCompletion() const
1305 if (displayMode() != DISPLAY_UNFOLDED)
1306 return InsetMathNest::automaticInlineCompletion();
1308 return lyxrc.completion_inline_math;
1312 bool MathMacro::automaticPopupCompletion() const
1314 if (displayMode() != DISPLAY_UNFOLDED)
1315 return InsetMathNest::automaticPopupCompletion();
1317 return lyxrc.completion_popup_math;
1321 CompletionList const *
1322 MathMacro::createCompletionList(Cursor const & cur) const
1324 if (displayMode() != DISPLAY_UNFOLDED)
1325 return InsetMathNest::createCompletionList(cur);
1327 return new MathCompletionList(cur.bv().cursor());
1331 docstring MathMacro::completionPrefix(Cursor const & cur) const
1333 if (displayMode() != DISPLAY_UNFOLDED)
1334 return InsetMathNest::completionPrefix(cur);
1336 if (!completionSupported(cur))
1339 return "\\" + name();
1343 bool MathMacro::insertCompletion(Cursor & cur, docstring const & s,
1346 if (displayMode() != DISPLAY_UNFOLDED)
1347 return InsetMathNest::insertCompletion(cur, s, finished);
1349 if (!completionSupported(cur))
1352 // append completion
1353 docstring newName = name() + s;
1354 asArray(newName, cell(0));
1355 cur.bv().cursor().pos() = name().size();
1356 cur.screenUpdateFlags(Update::SinglePar);
1360 cur.bv().cursor().pop();
1361 ++cur.bv().cursor().pos();
1362 cur.screenUpdateFlags(Update::SinglePar);
1369 void MathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
1370 Dimension & dim) const
1372 if (displayMode() != DISPLAY_UNFOLDED)
1373 InsetMathNest::completionPosAndDim(cur, x, y, dim);
1375 // get inset dimensions
1376 dim = cur.bv().coordCache().insets().dim(this);
1377 // FIXME: these 3 are no accurate, but should depend on the font.
1378 // Now the popup jumps down if you enter a char with descent > 0.
1384 = cur.bv().coordCache().insets().xy(this);