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 void metrics(MetricsInfo & mi, Dimension & dim) const {
72 mathMacro_->macro()->unlock();
73 mathMacro_->cell(idx_).metrics(mi, dim);
75 if (!mathMacro_->editMetrics(mi.base.bv)
76 && mathMacro_->cell(idx_).empty())
77 def_.metrics(mi, dim);
79 mathMacro_->macro()->lock();
81 // write(), normalize(), infoize() and infoize2() are not needed since
82 // MathMacro uses the definition and not the expanded cells.
84 void maple(MapleStream & ms) const { ms << mathMacro_->cell(idx_); }
86 void maxima(MaximaStream & ms) const { ms << mathMacro_->cell(idx_); }
88 void mathematica(MathematicaStream & ms) const { ms << mathMacro_->cell(idx_); }
90 void mathmlize(MathStream & ms) const { ms << mathMacro_->cell(idx_); }
92 void htmlize(HtmlStream & ms) const { ms << mathMacro_->cell(idx_); }
94 void octave(OctaveStream & os) const { os << mathMacro_->cell(idx_); }
96 void draw(PainterInfo & pi, int x, int y) const {
97 if (mathMacro_->editMetrics(pi.base.bv)) {
98 // The only way a ArgumentProxy can appear is in a cell of the
99 // MathMacro. Moreover the cells are only drawn in the DISPLAY_FOLDED
100 // mode and then, if the macro is edited the monochrome
101 // mode is entered by the MathMacro before calling the cells' draw
102 // method. Then eventually this code is reached and the proxy leaves
103 // monochrome mode temporarely. Hence, if it is not in monochrome
104 // here (and the assert triggers in pain.leaveMonochromeMode())
106 pi.pain.leaveMonochromeMode();
107 mathMacro_->cell(idx_).draw(pi, x, y);
108 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
109 } else if (mathMacro_->cell(idx_).empty()) {
110 mathMacro_->cell(idx_).setXY(*pi.base.bv, x, y);
113 mathMacro_->cell(idx_).draw(pi, x, y);
116 size_t idx() const { return idx_; }
118 int kerning(BufferView const * bv) const
120 if (mathMacro_->editMetrics(bv)
121 || !mathMacro_->cell(idx_).empty())
122 return mathMacro_->cell(idx_).kerning(bv);
124 return def_.kerning(bv);
129 Inset * clone() const
131 return new ArgumentProxy(*this);
134 MathMacro * mathMacro_;
142 /// Private implementation of MathMacro
143 class MathMacro::Private {
145 Private(Buffer * buf, docstring const & name)
146 : name_(name), displayMode_(DISPLAY_INIT),
147 expanded_(buf), definition_(buf), attachedArgsNum_(0),
148 optionals_(0), nextFoldMode_(true), macroBackup_(buf),
149 macro_(0), needsUpdate_(false), isUpdating_(false),
153 /// Update the pointers to our owner of all expanded macros.
154 /// This needs to be called every time a copy of the owner is created
156 void updateChildren(MathMacro * owner);
157 /// Recursively update the pointers of all expanded macros
158 /// appearing in the arguments of the current macro
159 void updateNestedChildren(MathMacro * owner, InsetMathNest * ni);
162 /// current display mode
163 DisplayMode displayMode_;
164 /// expanded macro with ArgumentProxies
166 /// macro definition with #1,#2,.. insets
167 MathData definition_;
168 /// number of arguments that were really attached
169 size_t attachedArgsNum_;
170 /// optional argument attached? (only in DISPLAY_NORMAL mode)
172 /// fold mode to be set in next metrics call?
174 /// if macro_ == true, then here is a copy of the macro
175 /// don't use it for locking
176 MacroData macroBackup_;
177 /// if macroNotFound_ == false, then here is a reference to the macro
178 /// this might invalidate after metrics was called
179 MacroData const * macro_;
181 mutable std::map<BufferView const *, bool> editing_;
183 std::string requires_;
184 /// update macro representation
188 /// maximal number of arguments the macro is greedy for
193 void MathMacro::Private::updateChildren(MathMacro * owner)
195 for (size_t i = 0; i < expanded_.size(); ++i) {
196 ArgumentProxy * p = dynamic_cast<ArgumentProxy *>(expanded_[i].nucleus());
200 InsetMathNest * ni = expanded_[i].nucleus()->asNestInset();
202 updateNestedChildren(owner, ni);
206 // The macro_ pointer is updated when MathData::metrics() is
207 // called. However, when instant preview is on or the macro is
208 // not on screen, MathData::metrics() is not called and we may
209 // have a dangling pointer. As a safety measure, when a macro
210 // is copied, always let macro_ point to the backup copy of the
211 // MacroData structure. This backup is updated every time the
212 // macro is changed, so it will not become stale.
213 macro_ = ¯oBackup_;
218 void MathMacro::Private::updateNestedChildren(MathMacro * owner, InsetMathNest * ni)
220 for (size_t i = 0; i < ni->nargs(); ++i) {
221 MathData & ar = ni->cell(i);
222 for (size_t j = 0; j < ar.size(); ++j) {
223 ArgumentProxy * ap = dynamic_cast
224 <ArgumentProxy *>(ar[j].nucleus());
226 MathMacro::Private * md = ap->owner()->d;
228 md->macro_ = &md->macroBackup_;
231 InsetMathNest * imn = ar[j].nucleus()->asNestInset();
233 updateNestedChildren(owner, imn);
239 MathMacro::MathMacro(Buffer * buf, docstring const & name)
240 : InsetMathNest(buf, 0), d(new Private(buf, name))
244 MathMacro::MathMacro(MathMacro const & that)
245 : InsetMathNest(that), d(new Private(*that.d))
247 setBuffer(*that.buffer_);
248 d->updateChildren(this);
252 MathMacro & MathMacro::operator=(MathMacro const & that)
256 InsetMathNest::operator=(that);
258 d->updateChildren(this);
263 MathMacro::~MathMacro()
269 Inset * MathMacro::clone() const
271 MathMacro * copy = new MathMacro(*this);
272 copy->d->needsUpdate_ = true;
273 //copy->d->expanded_.clear();
278 void MathMacro::normalize(NormalStream & os) const
280 os << "[macro " << name();
281 for (size_t i = 0; i < nargs(); ++i)
282 os << ' ' << cell(i);
287 MathMacro::DisplayMode MathMacro::displayMode() const
289 return d->displayMode_;
293 bool MathMacro::extraBraces() const
295 return d->displayMode_ == DISPLAY_NORMAL && arity() > 0;
299 docstring MathMacro::name() const
301 if (d->displayMode_ == DISPLAY_UNFOLDED)
302 return asString(cell(0));
308 docstring MathMacro::macroName() const
314 void MathMacro::cursorPos(BufferView const & bv,
315 CursorSlice const & sl, bool boundary, int & x, int & y) const
317 // We may have 0 arguments, but InsetMathNest requires at least one.
319 InsetMathNest::cursorPos(bv, sl, boundary, x, y);
323 bool MathMacro::editMode(BufferView const * bv) const {
324 // find this in cursor trace
325 Cursor const & cur = bv->cursor();
326 for (size_t i = 0; i != cur.depth(); ++i)
327 if (&cur[i].inset() == this) {
328 // look if there is no other macro in edit mode above
330 for (; i != cur.depth(); ++i) {
331 InsetMath * im = cur[i].asInsetMath();
333 MathMacro const * macro = im->asMacro();
334 if (macro && macro->displayMode() == DISPLAY_NORMAL)
339 // ok, none found, I am the highest one
347 MacroData const * MathMacro::macro()
353 bool MathMacro::editMetrics(BufferView const * bv) const
355 return d->editing_[bv];
359 void MathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
361 // set edit mode for which we will have calculated metrics. But only
362 d->editing_[mi.base.bv] = editMode(mi.base.bv);
364 // calculate new metrics according to display mode
365 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
366 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
367 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
368 cell(0).metrics(mi, dim);
370 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
371 dim.wid += bsdim.width() + 1;
372 dim.asc = max(bsdim.ascent(), dim.ascent());
373 dim.des = max(bsdim.descent(), dim.descent());
375 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
376 && d->editing_[mi.base.bv]) {
377 // Macro will be edited in a old-style list mode here:
381 FontInfo labelFont = sane_font;
382 math_font_max_dim(labelFont, fontDim.asc, fontDim.des);
384 // get dimension of components of list view
386 nameDim.wid = mathed_string_width(mi.base.font, from_ascii("Macro \\") + name() + ": ");
387 nameDim.asc = fontDim.asc;
388 nameDim.des = fontDim.des;
391 argDim.wid = mathed_string_width(labelFont, from_ascii("#9: "));
392 argDim.asc = fontDim.asc;
393 argDim.des = fontDim.des;
396 d->definition_.metrics(mi, defDim);
399 dim.wid = nameDim.wid + defDim.wid;
400 dim.asc = max(nameDim.asc, defDim.asc);
401 dim.des = max(nameDim.des, defDim.des);
403 for (idx_type i = 0; i < nargs(); ++i) {
405 cell(i).metrics(mi, cdim);
406 dim.des += max(argDim.height(), cdim.height()) + 1;
407 dim.wid = max(dim.wid, argDim.wid + cdim.wid);
410 // make space for box and markers, 2 pixels
414 metricsMarkers2(dim);
418 // calculate metrics, hoping that all cells are seen
420 d->expanded_.metrics(mi, dim);
422 // otherwise do a manual metrics call
423 CoordCache & coords = mi.base.bv->coordCache();
424 for (idx_type i = 0; i < nargs(); ++i) {
425 if (!coords.getArrays().hasDim(&cell(i))) {
427 cell(i).metrics(mi, tdim);
432 // calculate dimension with label while editing
433 if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX
434 && d->editing_[mi.base.bv]) {
435 FontInfo font = mi.base.font;
436 augmentFont(font, "lyxtex");
438 mathed_string_dim(font, name(), namedim);
440 dim.wid += 2 + namedim.wid + 2 + 2;
441 dim.asc = max(dim.asc, namedim.asc) + 2;
442 dim.des = max(dim.des, namedim.des) + 2;
444 dim.wid = max(1 + namedim.wid + 1, 2 + dim.wid + 2);
445 dim.asc += 1 + namedim.height() + 1;
452 int MathMacro::kerning(BufferView const * bv) const {
453 if (d->displayMode_ == DISPLAY_NORMAL && !d->editing_[bv])
454 return d->expanded_.kerning(bv);
460 void MathMacro::updateMacro(MacroContext const & mc)
463 d->macro_ = mc.get(name());
464 if (d->macro_ && d->macroBackup_ != *d->macro_) {
465 d->macroBackup_ = *d->macro_;
466 d->needsUpdate_ = true;
474 class MathMacro::UpdateLocker
477 explicit UpdateLocker(MathMacro & mm) : mac(mm)
479 mac.d->isUpdating_ = true;
481 ~UpdateLocker() { mac.d->isUpdating_ = false; }
485 /** Avoid wrong usage of UpdateLocker.
486 To avoid wrong usage:
487 UpdateLocker(...); // wrong
488 UpdateLocker locker(...); // right
490 #define UpdateLocker(x) unnamed_UpdateLocker;
491 // Tip gotten from Bobby Schmidt's column in C/C++ Users Journal
494 void MathMacro::updateRepresentation(Cursor * cur, MacroContext const & mc,
497 // block recursive calls (bug 8999)
501 UpdateLocker locker(*this);
508 d->requires_ = d->macro_->requires();
511 // non-normal mode? We are done!
512 || (d->displayMode_ != DISPLAY_NORMAL))
515 d->needsUpdate_ = false;
517 // get default values of macro
518 vector<docstring> const & defaults = d->macro_->defaults();
520 // create MathMacroArgumentValue objects pointing to the cells of the macro
521 vector<MathData> values(nargs());
522 for (size_t i = 0; i < nargs(); ++i) {
523 ArgumentProxy * proxy;
524 if (i < defaults.size())
525 proxy = new ArgumentProxy(this, i, defaults[i]);
527 proxy = new ArgumentProxy(this, i);
528 values[i].insert(0, MathAtom(proxy));
530 // expanding macro with the values
531 // Only update the argument macros if anything was expanded, otherwise
532 // we would get an endless loop (bug 9140). UpdateLocker does not work
533 // in this case, since MacroData::expand() creates new MathMacro
534 // objects, so this would be a different recursion path than the one
535 // protected by UpdateLocker.
536 if (d->macro_->expand(values, d->expanded_)) {
537 if (utype == OutputUpdate && !d->expanded_.empty())
538 d->expanded_.updateMacros(cur, mc, utype);
540 // get definition for list edit mode
541 docstring const & display = d->macro_->display();
542 asArray(display.empty() ? d->macro_->definition() : display, d->definition_);
546 void MathMacro::draw(PainterInfo & pi, int x, int y) const
548 Dimension const dim = dimension(*pi.base.bv);
550 setPosCache(pi, x, y);
554 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
555 Changer dummy = pi.base.changeFontSet("lyxtex");
556 pi.pain.text(x, y, from_ascii("\\") + name(), pi.base.font);
557 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
558 Changer dummy = pi.base.changeFontSet("lyxtex");
559 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
560 x += mathed_string_width(pi.base.font, from_ascii("\\")) + 1;
561 cell(0).draw(pi, x, y);
562 drawMarkers(pi, expx, expy);
563 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
564 && d->editing_[pi.base.bv]) {
565 // Macro will be edited in a old-style list mode here:
567 CoordCache const & coords = pi.base.bv->coordCache();
568 FontInfo const & labelFont = sane_font;
570 // markers and box needs two pixels
573 // get maximal font height
575 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
578 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
579 pi.pain.text(x, y, label, labelFont);
580 x += mathed_string_width(labelFont, label);
583 d->definition_.draw(pi, x, y);
584 Dimension const & defDim = coords.getArrays().dim(&d->definition_);
585 y += max(fontDim.des, defDim.des);
588 docstring str = from_ascii("#9");
589 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
590 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
592 for (idx_type i = 0; i < nargs(); ++i) {
594 Dimension const & cdim = coords.getArrays().dim(&cell(i));
596 y += max(fontDim.asc, cdim.asc) + 1;
600 pi.pain.text(x, y, str, labelFont);
602 pi.pain.text(x, y, from_ascii(":"), labelFont);
606 cell(i).draw(pi, x, y);
609 y += max(fontDim.des, cdim.des);
612 pi.pain.rectangle(expx + 1, expy - dim.asc + 1, dim.wid - 3,
613 dim.height() - 2, Color_mathmacroframe);
614 drawMarkers2(pi, expx, expy);
616 bool drawBox = lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX;
617 bool upshape = currentMode() == TEXT_MODE;
618 Changer dummy = pi.base.font.changeShape(upshape ? UP_SHAPE
619 : pi.base.font.shape());
622 for (size_t i = 0; i < nargs(); ++i)
623 cell(i).setXY(*pi.base.bv, x, y);
625 if (drawBox && d->editing_[pi.base.bv]) {
626 // draw header and rectangle around
627 FontInfo font = pi.base.font;
628 augmentFont(font, "lyxtex");
629 font.setSize(FONT_SIZE_TINY);
630 font.setColor(Color_mathmacrolabel);
632 mathed_string_dim(font, name(), namedim);
634 pi.pain.fillRectangle(x, y - dim.asc, dim.wid, 1 + namedim.height() + 1, Color_mathmacrobg);
635 pi.pain.text(x + 1, y - dim.asc + namedim.asc + 2, name(), font);
636 expx += (dim.wid - d->expanded_.dimension(*pi.base.bv).width()) / 2;
639 if (d->editing_[pi.base.bv]) {
640 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
641 d->expanded_.draw(pi, expx, expy);
642 pi.pain.leaveMonochromeMode();
645 pi.pain.rectangle(x, y - dim.asc, dim.wid,
646 dim.height(), Color_mathmacroframe);
648 d->expanded_.draw(pi, expx, expy);
651 drawMarkers(pi, x, y);
654 // edit mode changed?
655 if (d->editing_[pi.base.bv] != editMode(pi.base.bv))
656 pi.base.bv->cursor().screenUpdateFlags(Update::SinglePar);
660 void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
662 // We may have 0 arguments, but InsetMathNest requires at least one.
664 InsetMathNest::drawSelection(pi, x, y);
668 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode, int appetite)
670 if (d->displayMode_ != mode) {
671 // transfer name if changing from or to DISPLAY_UNFOLDED
672 if (mode == DISPLAY_UNFOLDED) {
674 asArray(d->name_, cell(0));
675 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
676 d->name_ = asString(cell(0));
680 d->displayMode_ = mode;
681 d->needsUpdate_ = true;
684 // the interactive init mode is non-greedy by default
686 d->appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
688 d->appetite_ = size_t(appetite);
692 MathMacro::DisplayMode MathMacro::computeDisplayMode() const
694 if (d->nextFoldMode_ == true && d->macro_ && !d->macro_->locked())
695 return DISPLAY_NORMAL;
697 return DISPLAY_UNFOLDED;
701 bool MathMacro::validName() const
703 docstring n = name();
708 // converting back and force doesn't swallow anything?
711 if (asString(ma) != n)
715 for (size_t i = 0; i<n.size(); ++i) {
716 if (!(n[i] >= 'a' && n[i] <= 'z')
717 && !(n[i] >= 'A' && n[i] <= 'Z')
726 size_t MathMacro::arity() const
728 if (d->displayMode_ == DISPLAY_NORMAL )
729 return cells_.size();
735 size_t MathMacro::optionals() const
737 return d->optionals_;
741 void MathMacro::setOptionals(int n)
743 if (n <= int(nargs()))
748 size_t MathMacro::appetite() const
754 InsetMath::mode_type MathMacro::currentMode() const
756 // User defined macros are always assumed to be mathmode macros.
757 // Only the global macros defined in lib/symbols may be textmode.
759 MacroData const * data = MacroTable::globalMacros().get(name());
760 bool textmode = data && data->symbol() && data->symbol()->extra == "textmode";
761 return textmode ? TEXT_MODE : MATH_MODE;
765 void MathMacro::validate(LaTeXFeatures & features) const
767 // Immediately after a document is loaded, in some cases the MacroData
768 // of the global macros defined in the lib/symbols file may still not
769 // be known to the macro machinery because it will be set only after
770 // the first call to updateMacros(). This is not a problem unless
771 // instant preview is on for math, in which case we will be missing
772 // the corresponding requirements.
773 // In this case, we get the required info from the global macro table.
774 if (!d->requires_.empty())
775 features.require(d->requires_);
776 else if (!d->macro_) {
777 // Update requires for known global macros.
778 MacroData const * data = MacroTable::globalMacros().get(name());
779 if (data && !data->requires().empty())
780 features.require(data->requires());
783 if (name() == "binom")
784 features.require("binom");
786 // validate the cells and the definition
787 if (displayMode() == DISPLAY_NORMAL) {
788 d->definition_.validate(features);
789 InsetMathNest::validate(features);
794 void MathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
796 cur.screenUpdateFlags(Update::SinglePar);
797 InsetMathNest::edit(cur, front, entry_from);
801 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
803 // We may have 0 arguments, but InsetMathNest requires at least one.
805 cur.screenUpdateFlags(Update::SinglePar);
806 return InsetMathNest::editXY(cur, x, y);
812 void MathMacro::removeArgument(Inset::pos_type pos) {
813 if (d->displayMode_ == DISPLAY_NORMAL) {
814 LASSERT(size_t(pos) < cells_.size(), return);
815 cells_.erase(cells_.begin() + pos);
816 if (size_t(pos) < d->attachedArgsNum_)
817 --d->attachedArgsNum_;
818 if (size_t(pos) < d->optionals_) {
822 d->needsUpdate_ = true;
827 void MathMacro::insertArgument(Inset::pos_type pos) {
828 if (d->displayMode_ == DISPLAY_NORMAL) {
829 LASSERT(size_t(pos) <= cells_.size(), return);
830 cells_.insert(cells_.begin() + pos, MathData());
831 if (size_t(pos) < d->attachedArgsNum_)
832 ++d->attachedArgsNum_;
833 if (size_t(pos) < d->optionals_)
836 d->needsUpdate_ = true;
841 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
843 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
846 // strip off empty cells, but not more than arity-attachedArgsNum_
849 for (i = cells_.size(); i > d->attachedArgsNum_; --i)
850 if (!cell(i - 1).empty()) break;
854 d->attachedArgsNum_ = 0;
855 d->expanded_ = MathData();
858 d->needsUpdate_ = true;
862 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
864 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
866 d->attachedArgsNum_ = args.size();
867 cells_.resize(arity);
868 d->expanded_ = MathData();
869 d->optionals_ = optionals;
871 d->needsUpdate_ = true;
875 bool MathMacro::idxFirst(Cursor & cur) const
877 cur.screenUpdateFlags(Update::SinglePar);
878 return InsetMathNest::idxFirst(cur);
882 bool MathMacro::idxLast(Cursor & cur) const
884 cur.screenUpdateFlags(Update::SinglePar);
885 return InsetMathNest::idxLast(cur);
889 bool MathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
891 if (d->displayMode_ == DISPLAY_UNFOLDED) {
892 docstring const & unfolded_name = name();
893 if (unfolded_name != d->name_) {
894 // The macro name was changed
895 Cursor inset_cursor = old;
896 int macroSlice = inset_cursor.find(this);
897 // returning true means the cursor is "now" invalid,
899 LASSERT(macroSlice != -1, return true);
900 inset_cursor.cutOff(macroSlice);
901 inset_cursor.recordUndoInset();
903 inset_cursor.cell().erase(inset_cursor.pos());
904 inset_cursor.cell().insert(inset_cursor.pos(),
905 createInsetMath(unfolded_name, cur.buffer()));
907 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
911 cur.screenUpdateFlags(Update::Force);
912 return InsetMathNest::notifyCursorLeaves(old, cur);
916 void MathMacro::fold(Cursor & cur)
918 if (!d->nextFoldMode_) {
919 d->nextFoldMode_ = true;
920 cur.screenUpdateFlags(Update::SinglePar);
925 void MathMacro::unfold(Cursor & cur)
927 if (d->nextFoldMode_) {
928 d->nextFoldMode_ = false;
929 cur.screenUpdateFlags(Update::SinglePar);
934 bool MathMacro::folded() const
936 return d->nextFoldMode_;
940 void MathMacro::write(WriteStream & os) const
942 MacroData const * data = MacroTable::globalMacros().get(name());
943 bool textmode_macro = data && data->symbol()
944 && data->symbol()->extra == "textmode";
945 bool needs_mathmode = data && (!data->symbol()
946 || data->symbol()->extra != "textmode");
948 MathEnsurer ensurer(os, needs_mathmode, true, textmode_macro);
951 if (d->displayMode_ != DISPLAY_NORMAL) {
952 os << "\\" << name();
953 if (name().size() != 1 || isAlphaASCII(name()[0]))
954 os.pendingSpace(true);
959 // we should be ok to continue even if this fails.
962 // Always protect macros in a fragile environment
966 os << "\\" << name();
969 // Optional arguments:
970 // First find last non-empty optional argument
971 idx_type emptyOptFrom = 0;
973 for (; i < cells_.size() && i < d->optionals_; ++i) {
974 if (!cell(i).empty())
975 emptyOptFrom = i + 1;
978 // print out optionals
979 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
981 os << "[" << cell(i) << "]";
984 // skip the tailing empty optionals
987 // Print remaining arguments
988 for (; i < cells_.size(); ++i) {
989 if (cell(i).size() == 1
990 && cell(i)[0].nucleus()->asCharInset()
991 && isASCII(cell(i)[0].nucleus()->asCharInset()->getChar())) {
996 os << "{" << cell(i) << "}";
1000 // add space if there was no argument
1002 os.pendingSpace(true);
1006 void MathMacro::maple(MapleStream & os) const
1008 lyx::maple(d->expanded_, os);
1012 void MathMacro::maxima(MaximaStream & os) const
1014 lyx::maxima(d->expanded_, os);
1018 void MathMacro::mathematica(MathematicaStream & os) const
1020 lyx::mathematica(d->expanded_, os);
1024 void MathMacro::mathmlize(MathStream & os) const
1026 // macro_ is 0 if this is an unknown macro
1027 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1029 docstring const xmlname = d->macro_->xmlname();
1030 if (!xmlname.empty()) {
1031 char const * type = d->macro_->MathMLtype();
1032 os << '<' << type << "> " << xmlname << " </"
1037 if (d->expanded_.empty()) {
1038 // this means that we do not recognize the macro
1039 throw MathExportException();
1045 void MathMacro::htmlize(HtmlStream & os) const
1047 // macro_ is 0 if this is an unknown macro
1048 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1050 docstring const xmlname = d->macro_->xmlname();
1051 if (!xmlname.empty()) {
1052 os << ' ' << xmlname << ' ';
1056 if (d->expanded_.empty()) {
1057 // this means that we do not recognize the macro
1058 throw MathExportException();
1064 void MathMacro::octave(OctaveStream & os) const
1066 lyx::octave(d->expanded_, os);
1070 void MathMacro::infoize(odocstream & os) const
1072 os << bformat(_("Macro: %1$s"), name());
1076 void MathMacro::infoize2(odocstream & os) const
1078 os << bformat(_("Macro: %1$s"), name());
1082 bool MathMacro::completionSupported(Cursor const & cur) const
1084 if (displayMode() != DISPLAY_UNFOLDED)
1085 return InsetMathNest::completionSupported(cur);
1087 return lyxrc.completion_popup_math
1088 && displayMode() == DISPLAY_UNFOLDED
1089 && cur.bv().cursor().pos() == int(name().size());
1093 bool MathMacro::inlineCompletionSupported(Cursor const & cur) const
1095 if (displayMode() != DISPLAY_UNFOLDED)
1096 return InsetMathNest::inlineCompletionSupported(cur);
1098 return lyxrc.completion_inline_math
1099 && displayMode() == DISPLAY_UNFOLDED
1100 && cur.bv().cursor().pos() == int(name().size());
1104 bool MathMacro::automaticInlineCompletion() const
1106 if (displayMode() != DISPLAY_UNFOLDED)
1107 return InsetMathNest::automaticInlineCompletion();
1109 return lyxrc.completion_inline_math;
1113 bool MathMacro::automaticPopupCompletion() const
1115 if (displayMode() != DISPLAY_UNFOLDED)
1116 return InsetMathNest::automaticPopupCompletion();
1118 return lyxrc.completion_popup_math;
1122 CompletionList const *
1123 MathMacro::createCompletionList(Cursor const & cur) const
1125 if (displayMode() != DISPLAY_UNFOLDED)
1126 return InsetMathNest::createCompletionList(cur);
1128 return new MathCompletionList(cur.bv().cursor());
1132 docstring MathMacro::completionPrefix(Cursor const & cur) const
1134 if (displayMode() != DISPLAY_UNFOLDED)
1135 return InsetMathNest::completionPrefix(cur);
1137 if (!completionSupported(cur))
1140 return "\\" + name();
1144 bool MathMacro::insertCompletion(Cursor & cur, docstring const & s,
1147 if (displayMode() != DISPLAY_UNFOLDED)
1148 return InsetMathNest::insertCompletion(cur, s, finished);
1150 if (!completionSupported(cur))
1153 // append completion
1154 docstring newName = name() + s;
1155 asArray(newName, cell(0));
1156 cur.bv().cursor().pos() = name().size();
1157 cur.screenUpdateFlags(Update::SinglePar);
1161 cur.bv().cursor().pop();
1162 ++cur.bv().cursor().pos();
1163 cur.screenUpdateFlags(Update::SinglePar);
1170 void MathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
1171 Dimension & dim) const
1173 if (displayMode() != DISPLAY_UNFOLDED)
1174 InsetMathNest::completionPosAndDim(cur, x, y, dim);
1176 // get inset dimensions
1177 dim = cur.bv().coordCache().insets().dim(this);
1178 // FIXME: these 3 are no accurate, but should depend on the font.
1179 // Now the popup jumps down if you enter a char with descent > 0.
1185 = cur.bv().coordCache().insets().xy(this);