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, mathMacro_->nesting());
87 MathRow::Element e_beg(MathRow::BEG_ARG);
88 e_beg.macro = mathMacro_;
89 e_beg.ar = &mathMacro_->cell(idx_);
90 mrow.push_back(e_beg);
92 mathMacro_->macro()->unlock();
93 bool has_contents = displayCell(mi.base.bv).addToMathRow(mrow, mi);
94 mathMacro_->macro()->lock();
96 // if there was no contents, and the contents is editable,
97 // then we insert a box instead.
98 if (!has_contents && mathMacro_->nesting() == 1) {
99 MathRow::Element e(MathRow::BOX);
100 e.color = Color_mathline;
105 MathRow::Element e_end(MathRow::END_ARG);
106 e_end.macro = mathMacro_;
107 e_end.ar = &mathMacro_->cell(idx_);
109 mrow.push_back(e_end);
114 void metrics(MetricsInfo &, Dimension &) const {
115 // This should never be invoked, since ArgumentProxy insets are linearized
118 // write(), normalize(), infoize() and infoize2() are not needed since
119 // MathMacro uses the definition and not the expanded cells.
121 void maple(MapleStream & ms) const { ms << mathMacro_->cell(idx_); }
123 void maxima(MaximaStream & ms) const { ms << mathMacro_->cell(idx_); }
125 void mathematica(MathematicaStream & ms) const { ms << mathMacro_->cell(idx_); }
127 void mathmlize(MathStream & ms) const { ms << mathMacro_->cell(idx_); }
129 void htmlize(HtmlStream & ms) const { ms << mathMacro_->cell(idx_); }
131 void octave(OctaveStream & os) const { os << mathMacro_->cell(idx_); }
133 void draw(PainterInfo &, int, int) const {
134 // This should never be invoked, since ArgumentProxy insets are linearized
138 size_t idx() const { return idx_; }
140 int kerning(BufferView const * bv) const
142 return displayCell(bv).kerning(bv);
147 Inset * clone() const
149 return new ArgumentProxy(*this);
152 MathMacro * mathMacro_;
160 /// Private implementation of MathMacro
161 class MathMacro::Private {
163 Private(Buffer * buf, docstring const & name)
164 : name_(name), displayMode_(DISPLAY_INIT),
165 expanded_(buf), definition_(buf), attachedArgsNum_(0),
166 optionals_(0), nextFoldMode_(true), macroBackup_(buf),
167 macro_(0), needsUpdate_(false), isUpdating_(false),
171 /// Update the pointers to our owner of all expanded macros.
172 /// This needs to be called every time a copy of the owner is created
174 void updateChildren(MathMacro * owner);
175 /// Recursively update the pointers of all expanded macros
176 /// appearing in the arguments of the current macro
177 void updateNestedChildren(MathMacro * owner, InsetMathNest * ni);
180 /// current display mode
181 DisplayMode displayMode_;
182 /// expanded macro with ArgumentProxies
184 /// macro definition with #1,#2,.. insets
185 MathData definition_;
186 /// number of arguments that were really attached
187 size_t attachedArgsNum_;
188 /// optional argument attached? (only in DISPLAY_NORMAL mode)
190 /// fold mode to be set in next metrics call?
192 /// if macro_ == true, then here is a copy of the macro
193 /// don't use it for locking
194 MacroData macroBackup_;
195 /// if macroNotFound_ == false, then here is a reference to the macro
196 /// this might invalidate after metrics was called
197 MacroData const * macro_;
199 mutable std::map<BufferView const *, bool> editing_;
201 std::string requires_;
202 /// update macro representation
206 /// maximal number of arguments the macro is greedy for
208 /// Level of nesting in macros (including this one)
213 void MathMacro::Private::updateChildren(MathMacro * owner)
215 for (size_t i = 0; i < expanded_.size(); ++i) {
216 ArgumentProxy * p = dynamic_cast<ArgumentProxy *>(expanded_[i].nucleus());
220 InsetMathNest * ni = expanded_[i].nucleus()->asNestInset();
222 updateNestedChildren(owner, ni);
226 // The macro_ pointer is updated when MathData::metrics() is
227 // called. However, when instant preview is on or the macro is
228 // not on screen, MathData::metrics() is not called and we may
229 // have a dangling pointer. As a safety measure, when a macro
230 // is copied, always let macro_ point to the backup copy of the
231 // MacroData structure. This backup is updated every time the
232 // macro is changed, so it will not become stale.
233 macro_ = ¯oBackup_;
238 void MathMacro::Private::updateNestedChildren(MathMacro * owner, InsetMathNest * ni)
240 for (size_t i = 0; i < ni->nargs(); ++i) {
241 MathData & ar = ni->cell(i);
242 for (size_t j = 0; j < ar.size(); ++j) {
243 ArgumentProxy * ap = dynamic_cast
244 <ArgumentProxy *>(ar[j].nucleus());
246 MathMacro::Private * md = ap->owner()->d;
248 md->macro_ = &md->macroBackup_;
251 InsetMathNest * imn = ar[j].nucleus()->asNestInset();
253 updateNestedChildren(owner, imn);
259 MathMacro::MathMacro(Buffer * buf, docstring const & name)
260 : InsetMathNest(buf, 0), d(new Private(buf, name))
264 MathMacro::MathMacro(MathMacro const & that)
265 : InsetMathNest(that), d(new Private(*that.d))
267 setBuffer(*that.buffer_);
268 d->updateChildren(this);
272 MathMacro & MathMacro::operator=(MathMacro const & that)
276 InsetMathNest::operator=(that);
278 d->updateChildren(this);
283 MathMacro::~MathMacro()
289 bool MathMacro::addToMathRow(MathRow & mrow, MetricsInfo & mi) const
291 // set edit mode for which we will have calculated row.
292 // This is the same as what is done in metrics().
293 d->editing_[mi.base.bv] = editMode(mi.base.bv);
295 /// The macro nesting can change display of insets. Change it locally.
296 Changer chg = make_change(mi.base.macro_nesting, d->nesting_);
298 if (displayMode() != MathMacro::DISPLAY_NORMAL
299 || d->editing_[mi.base.bv])
300 return InsetMath::addToMathRow(mrow, mi);
302 MathRow::Element e_beg(MathRow::BEG_MACRO);
304 mrow.push_back(e_beg);
307 bool has_contents = d->expanded_.addToMathRow(mrow, mi);
310 // if there was no contents and the array is editable, then we
311 // insert a grey box instead.
312 if (!has_contents && mi.base.macro_nesting == 1) {
313 MathRow::Element e(MathRow::BOX);
314 e.color = Color_mathmacroblend;
319 MathRow::Element e_end(MathRow::END_MACRO);
321 mrow.push_back(e_end);
327 Inset * MathMacro::clone() const
329 MathMacro * copy = new MathMacro(*this);
330 copy->d->needsUpdate_ = true;
331 //copy->d->expanded_.clear();
336 void MathMacro::normalize(NormalStream & os) const
338 os << "[macro " << name();
339 for (size_t i = 0; i < nargs(); ++i)
340 os << ' ' << cell(i);
345 MathMacro::DisplayMode MathMacro::displayMode() const
347 return d->displayMode_;
351 bool MathMacro::extraBraces() const
353 return d->displayMode_ == DISPLAY_NORMAL && arity() > 0;
357 docstring MathMacro::name() const
359 if (d->displayMode_ == DISPLAY_UNFOLDED)
360 return asString(cell(0));
366 docstring MathMacro::macroName() const
372 int MathMacro::nesting() const
378 void MathMacro::cursorPos(BufferView const & bv,
379 CursorSlice const & sl, bool boundary, int & x, int & y) const
381 // We may have 0 arguments, but InsetMathNest requires at least one.
383 InsetMathNest::cursorPos(bv, sl, boundary, x, y);
387 bool MathMacro::editMode(BufferView const * bv) const {
388 // find this in cursor trace
389 Cursor const & cur = bv->cursor();
390 for (size_t i = 0; i != cur.depth(); ++i)
391 if (&cur[i].inset() == this) {
392 // look if there is no other macro in edit mode above
394 for (; i != cur.depth(); ++i) {
395 InsetMath * im = cur[i].asInsetMath();
397 MathMacro const * macro = im->asMacro();
398 if (macro && macro->displayMode() == DISPLAY_NORMAL)
403 // ok, none found, I am the highest one
411 MacroData const * MathMacro::macro() const
417 bool MathMacro::editMetrics(BufferView const * bv) const
419 return d->editing_[bv];
423 void MathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
425 /// The macro nesting can change display of insets. Change it locally.
426 Changer chg = make_change(mi.base.macro_nesting, d->nesting_);
428 // set edit mode for which we will have calculated metrics. But only
429 d->editing_[mi.base.bv] = editMode(mi.base.bv);
431 // calculate new metrics according to display mode
432 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
433 Changer dummy = mi.base.changeFontSet("lyxtex");
434 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
435 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
436 Changer dummy = mi.base.changeFontSet("lyxtex");
437 cell(0).metrics(mi, dim);
439 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
440 dim.wid += bsdim.width() + 1;
441 dim.asc = max(bsdim.ascent(), dim.ascent());
442 dim.des = max(bsdim.descent(), dim.descent());
443 metricsMarkers(mi, dim);
444 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
445 && d->editing_[mi.base.bv]) {
446 // Macro will be edited in a old-style list mode here:
450 FontInfo labelFont = sane_font;
451 math_font_max_dim(labelFont, fontDim.asc, fontDim.des);
453 // get dimension of components of list view
455 nameDim.wid = mathed_string_width(mi.base.font, from_ascii("Macro \\") + name() + ": ");
456 nameDim.asc = fontDim.asc;
457 nameDim.des = fontDim.des;
460 argDim.wid = mathed_string_width(labelFont, from_ascii("#9: "));
461 argDim.asc = fontDim.asc;
462 argDim.des = fontDim.des;
465 d->definition_.metrics(mi, defDim);
468 dim.wid = nameDim.wid + defDim.wid;
469 dim.asc = max(nameDim.asc, defDim.asc);
470 dim.des = max(nameDim.des, defDim.des);
472 for (idx_type i = 0; i < nargs(); ++i) {
474 cell(i).metrics(mi, cdim);
475 dim.des += max(argDim.height(), cdim.height()) + 1;
476 dim.wid = max(dim.wid, argDim.wid + cdim.wid);
479 // make space for box and markers, 2 pixels
483 metricsMarkers2(mi, dim);
487 Changer dummy = (currentMode() == TEXT_MODE)
488 ? mi.base.font.changeShape(UP_SHAPE)
491 // calculate metrics, hoping that all cells are seen
493 d->expanded_.metrics(mi, dim);
495 // otherwise do a manual metrics call
496 CoordCache & coords = mi.base.bv->coordCache();
497 for (idx_type i = 0; i < nargs(); ++i) {
498 if (!coords.getArrays().hasDim(&cell(i))) {
500 cell(i).metrics(mi, tdim);
505 // calculate dimension with label while editing
506 if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX
507 && d->editing_[mi.base.bv]) {
508 FontInfo font = mi.base.font;
509 augmentFont(font, "lyxtex");
511 mathed_string_dim(font, name(), namedim);
513 dim.wid += 2 + namedim.wid + 2 + 2;
514 dim.asc = max(dim.asc, namedim.asc) + 2;
515 dim.des = max(dim.des, namedim.des) + 2;
517 dim.wid = max(1 + namedim.wid + 1, 2 + dim.wid + 2);
518 dim.asc += 1 + namedim.height() + 1;
525 int MathMacro::kerning(BufferView const * bv) const {
526 if (d->displayMode_ == DISPLAY_NORMAL && !d->editing_[bv])
527 return d->expanded_.kerning(bv);
533 void MathMacro::updateMacro(MacroContext const & mc)
536 d->macro_ = mc.get(name());
537 if (d->macro_ && d->macroBackup_ != *d->macro_) {
538 d->macroBackup_ = *d->macro_;
539 d->needsUpdate_ = true;
547 class MathMacro::UpdateLocker
550 explicit UpdateLocker(MathMacro & mm) : mac(mm)
552 mac.d->isUpdating_ = true;
554 ~UpdateLocker() { mac.d->isUpdating_ = false; }
558 /** Avoid wrong usage of UpdateLocker.
559 To avoid wrong usage:
560 UpdateLocker(...); // wrong
561 UpdateLocker locker(...); // right
563 #define UpdateLocker(x) unnamed_UpdateLocker;
564 // Tip gotten from Bobby Schmidt's column in C/C++ Users Journal
567 void MathMacro::updateRepresentation(Cursor * cur, MacroContext const & mc,
568 UpdateType utype, int nesting)
570 // block recursive calls (bug 8999)
574 UpdateLocker locker(*this);
580 // remember nesting level of this macro
581 d->nesting_ = nesting;
584 d->requires_ = d->macro_->requires();
587 // non-normal mode? We are done!
588 || (d->displayMode_ != DISPLAY_NORMAL))
591 d->needsUpdate_ = false;
593 // get default values of macro
594 vector<docstring> const & defaults = d->macro_->defaults();
596 // create MathMacroArgumentValue objects pointing to the cells of the macro
597 vector<MathData> values(nargs());
598 for (size_t i = 0; i < nargs(); ++i) {
599 ArgumentProxy * proxy;
600 if (i < defaults.size())
601 proxy = new ArgumentProxy(this, i, defaults[i]);
603 proxy = new ArgumentProxy(this, i);
604 values[i].insert(0, MathAtom(proxy));
606 // expanding macro with the values
607 // Only update the argument macros if anything was expanded, otherwise
608 // we would get an endless loop (bug 9140). UpdateLocker does not work
609 // in this case, since MacroData::expand() creates new MathMacro
610 // objects, so this would be a different recursion path than the one
611 // protected by UpdateLocker.
612 if (d->macro_->expand(values, d->expanded_)) {
613 if (utype == OutputUpdate && !d->expanded_.empty())
614 d->expanded_.updateMacros(cur, mc, utype, nesting);
616 // get definition for list edit mode
617 docstring const & display = d->macro_->display();
618 asArray(display.empty() ? d->macro_->definition() : display,
619 d->definition_, Parse::QUIET);
623 void MathMacro::draw(PainterInfo & pi, int x, int y) const
625 Dimension const dim = dimension(*pi.base.bv);
627 setPosCache(pi, x, y);
631 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
632 Changer dummy = pi.base.changeFontSet("lyxtex");
633 pi.pain.text(x, y, from_ascii("\\") + name(), pi.base.font);
634 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
635 Changer dummy = pi.base.changeFontSet("lyxtex");
636 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
637 x += mathed_string_width(pi.base.font, from_ascii("\\")) + 1;
638 cell(0).draw(pi, x, y);
639 drawMarkers(pi, expx, expy);
640 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
641 && d->editing_[pi.base.bv]) {
642 // Macro will be edited in a old-style list mode here:
644 CoordCache const & coords = pi.base.bv->coordCache();
645 FontInfo const & labelFont = sane_font;
647 // markers and box needs two pixels
650 // get maximal font height
652 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
655 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
656 pi.pain.text(x, y, label, labelFont);
657 x += mathed_string_width(labelFont, label);
660 d->definition_.draw(pi, x, y);
661 Dimension const & defDim = coords.getArrays().dim(&d->definition_);
662 y += max(fontDim.des, defDim.des);
665 docstring str = from_ascii("#9");
666 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
667 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
669 for (idx_type i = 0; i < nargs(); ++i) {
671 Dimension const & cdim = coords.getArrays().dim(&cell(i));
673 y += max(fontDim.asc, cdim.asc) + 1;
677 pi.pain.text(x, y, str, labelFont);
679 pi.pain.text(x, y, from_ascii(":"), labelFont);
683 cell(i).draw(pi, x, y);
686 y += max(fontDim.des, cdim.des);
689 pi.pain.rectangle(expx + 1, expy - dim.asc + 1, dim.wid - 3,
690 dim.height() - 2, Color_mathmacroframe);
691 drawMarkers2(pi, expx, expy);
693 bool drawBox = lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX;
694 Changer dummy = (currentMode() == TEXT_MODE)
695 ? pi.base.font.changeShape(UP_SHAPE)
699 for (size_t i = 0; i < nargs(); ++i)
700 cell(i).setXY(*pi.base.bv, x, y);
702 if (drawBox && d->editing_[pi.base.bv]) {
703 // draw header and rectangle around
704 FontInfo font = pi.base.font;
705 augmentFont(font, "lyxtex");
706 font.setSize(FONT_SIZE_TINY);
707 font.setColor(Color_mathmacrolabel);
709 mathed_string_dim(font, name(), namedim);
711 pi.pain.fillRectangle(x, y - dim.asc, dim.wid, 1 + namedim.height() + 1, Color_mathmacrobg);
712 pi.pain.text(x + 1, y - dim.asc + namedim.asc + 2, name(), font);
713 expx += (dim.wid - d->expanded_.dimension(*pi.base.bv).width()) / 2;
716 if (d->editing_[pi.base.bv]) {
717 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
718 d->expanded_.draw(pi, expx, expy);
719 pi.pain.leaveMonochromeMode();
722 pi.pain.rectangle(x, y - dim.asc, dim.wid,
723 dim.height(), Color_mathmacroframe);
725 d->expanded_.draw(pi, expx, expy);
728 drawMarkers(pi, x, y);
732 // edit mode changed?
733 if (d->editing_[pi.base.bv] != editMode(pi.base.bv))
734 pi.base.bv->cursor().screenUpdateFlags(Update::SinglePar);
738 void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
740 // We may have 0 arguments, but InsetMathNest requires at least one.
742 InsetMathNest::drawSelection(pi, x, y);
746 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode, int appetite)
748 if (d->displayMode_ != mode) {
749 // transfer name if changing from or to DISPLAY_UNFOLDED
750 if (mode == DISPLAY_UNFOLDED) {
752 asArray(d->name_, cell(0));
753 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
754 d->name_ = asString(cell(0));
758 d->displayMode_ = mode;
759 d->needsUpdate_ = true;
762 // the interactive init mode is non-greedy by default
764 d->appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
766 d->appetite_ = size_t(appetite);
770 MathMacro::DisplayMode MathMacro::computeDisplayMode() const
772 if (d->nextFoldMode_ == true && d->macro_ && !d->macro_->locked())
773 return DISPLAY_NORMAL;
775 return DISPLAY_UNFOLDED;
779 bool MathMacro::validName() const
781 docstring n = name();
786 // converting back and force doesn't swallow anything?
789 if (asString(ma) != n)
793 for (size_t i = 0; i<n.size(); ++i) {
794 if (!(n[i] >= 'a' && n[i] <= 'z')
795 && !(n[i] >= 'A' && n[i] <= 'Z')
804 size_t MathMacro::arity() const
806 if (d->displayMode_ == DISPLAY_NORMAL )
807 return cells_.size();
813 size_t MathMacro::optionals() const
815 return d->optionals_;
819 void MathMacro::setOptionals(int n)
821 if (n <= int(nargs()))
826 size_t MathMacro::appetite() const
832 InsetMath::mode_type MathMacro::currentMode() const
834 // User defined macros are always assumed to be mathmode macros.
835 // Only the global macros defined in lib/symbols may be textmode.
837 MacroData const * data = MacroTable::globalMacros().get(name());
838 bool textmode = data && data->symbol() && data->symbol()->extra == "textmode";
839 return textmode ? TEXT_MODE : MATH_MODE;
843 void MathMacro::validate(LaTeXFeatures & features) const
845 // Immediately after a document is loaded, in some cases the MacroData
846 // of the global macros defined in the lib/symbols file may still not
847 // be known to the macro machinery because it will be set only after
848 // the first call to updateMacros(). This is not a problem unless
849 // instant preview is on for math, in which case we will be missing
850 // the corresponding requirements.
851 // In this case, we get the required info from the global macro table.
852 if (!d->requires_.empty())
853 features.require(d->requires_);
854 else if (!d->macro_) {
855 // Update requires for known global macros.
856 MacroData const * data = MacroTable::globalMacros().get(name());
857 if (data && !data->requires().empty())
858 features.require(data->requires());
861 if (name() == "binom")
862 features.require("binom");
864 // validate the cells and the definition
865 if (displayMode() == DISPLAY_NORMAL) {
866 d->definition_.validate(features);
867 InsetMathNest::validate(features);
872 void MathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
874 cur.screenUpdateFlags(Update::SinglePar);
875 InsetMathNest::edit(cur, front, entry_from);
879 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
881 // We may have 0 arguments, but InsetMathNest requires at least one.
883 cur.screenUpdateFlags(Update::SinglePar);
884 return InsetMathNest::editXY(cur, x, y);
890 void MathMacro::removeArgument(Inset::pos_type pos) {
891 if (d->displayMode_ == DISPLAY_NORMAL) {
892 LASSERT(size_t(pos) < cells_.size(), return);
893 cells_.erase(cells_.begin() + pos);
894 if (size_t(pos) < d->attachedArgsNum_)
895 --d->attachedArgsNum_;
896 if (size_t(pos) < d->optionals_) {
900 d->needsUpdate_ = true;
905 void MathMacro::insertArgument(Inset::pos_type pos) {
906 if (d->displayMode_ == DISPLAY_NORMAL) {
907 LASSERT(size_t(pos) <= cells_.size(), return);
908 cells_.insert(cells_.begin() + pos, MathData());
909 if (size_t(pos) < d->attachedArgsNum_)
910 ++d->attachedArgsNum_;
911 if (size_t(pos) < d->optionals_)
914 d->needsUpdate_ = true;
919 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
921 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
924 // strip off empty cells, but not more than arity-attachedArgsNum_
927 for (i = cells_.size(); i > d->attachedArgsNum_; --i)
928 if (!cell(i - 1).empty()) break;
932 d->attachedArgsNum_ = 0;
933 d->expanded_ = MathData();
936 d->needsUpdate_ = true;
940 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
942 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
944 d->attachedArgsNum_ = args.size();
945 cells_.resize(arity);
946 d->expanded_ = MathData();
947 d->optionals_ = optionals;
949 d->needsUpdate_ = true;
953 bool MathMacro::idxFirst(Cursor & cur) const
955 cur.screenUpdateFlags(Update::SinglePar);
956 return InsetMathNest::idxFirst(cur);
960 bool MathMacro::idxLast(Cursor & cur) const
962 cur.screenUpdateFlags(Update::SinglePar);
963 return InsetMathNest::idxLast(cur);
967 bool MathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
969 if (d->displayMode_ == DISPLAY_UNFOLDED) {
970 docstring const & unfolded_name = name();
971 if (unfolded_name != d->name_) {
972 // The macro name was changed
973 Cursor inset_cursor = old;
974 int macroSlice = inset_cursor.find(this);
975 // returning true means the cursor is "now" invalid,
977 LASSERT(macroSlice != -1, return true);
978 inset_cursor.cutOff(macroSlice);
979 inset_cursor.recordUndoInset();
981 inset_cursor.cell().erase(inset_cursor.pos());
982 inset_cursor.cell().insert(inset_cursor.pos(),
983 createInsetMath(unfolded_name, cur.buffer()));
985 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
989 cur.screenUpdateFlags(Update::Force);
990 return InsetMathNest::notifyCursorLeaves(old, cur);
994 void MathMacro::fold(Cursor & cur)
996 if (!d->nextFoldMode_) {
997 d->nextFoldMode_ = true;
998 cur.screenUpdateFlags(Update::SinglePar);
1003 void MathMacro::unfold(Cursor & cur)
1005 if (d->nextFoldMode_) {
1006 d->nextFoldMode_ = false;
1007 cur.screenUpdateFlags(Update::SinglePar);
1012 bool MathMacro::folded() const
1014 return d->nextFoldMode_;
1018 void MathMacro::write(WriteStream & os) const
1020 MacroData const * data = MacroTable::globalMacros().get(name());
1021 bool textmode_macro = data && data->symbol()
1022 && data->symbol()->extra == "textmode";
1023 bool needs_mathmode = data && (!data->symbol()
1024 || data->symbol()->extra != "textmode");
1026 MathEnsurer ensurer(os, needs_mathmode, true, textmode_macro);
1029 if (d->displayMode_ != DISPLAY_NORMAL) {
1030 os << "\\" << name();
1031 if (name().size() != 1 || isAlphaASCII(name()[0]))
1032 os.pendingSpace(true);
1037 // we should be ok to continue even if this fails.
1040 // We may already be in the argument of a macro
1041 bool const inside_macro = os.insideMacro();
1042 os.insideMacro(true);
1044 // Enclose in braces to avoid latex errors with xargs if we have
1045 // optional arguments and are in the optional argument of a macro
1046 if (d->optionals_ && inside_macro)
1049 // Always protect macros in a fragile environment
1053 os << "\\" << name();
1056 // Optional arguments:
1057 // First find last non-empty optional argument
1058 idx_type emptyOptFrom = 0;
1060 for (; i < cells_.size() && i < d->optionals_; ++i) {
1061 if (!cell(i).empty())
1062 emptyOptFrom = i + 1;
1065 // print out optionals
1066 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
1068 os << "[" << cell(i) << "]";
1071 // skip the tailing empty optionals
1074 // Print remaining arguments
1075 for (; i < cells_.size(); ++i) {
1076 if (cell(i).size() == 1
1077 && cell(i)[0].nucleus()->asCharInset()
1078 && isASCII(cell(i)[0].nucleus()->asCharInset()->getChar())) {
1083 os << "{" << cell(i) << "}";
1087 // Close the opened brace or add space if there was no argument
1088 if (d->optionals_ && inside_macro)
1091 os.pendingSpace(true);
1093 os.insideMacro(inside_macro);
1097 void MathMacro::maple(MapleStream & os) const
1099 lyx::maple(d->expanded_, os);
1103 void MathMacro::maxima(MaximaStream & os) const
1105 lyx::maxima(d->expanded_, os);
1109 void MathMacro::mathematica(MathematicaStream & os) const
1111 lyx::mathematica(d->expanded_, os);
1115 void MathMacro::mathmlize(MathStream & os) const
1117 // macro_ is 0 if this is an unknown macro
1118 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1120 docstring const xmlname = d->macro_->xmlname();
1121 if (!xmlname.empty()) {
1122 char const * type = d->macro_->MathMLtype();
1123 os << '<' << type << "> " << xmlname << " </"
1128 if (d->expanded_.empty()) {
1129 // this means that we do not recognize the macro
1130 throw MathExportException();
1136 void MathMacro::htmlize(HtmlStream & os) const
1138 // macro_ is 0 if this is an unknown macro
1139 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1141 docstring const xmlname = d->macro_->xmlname();
1142 if (!xmlname.empty()) {
1143 os << ' ' << xmlname << ' ';
1147 if (d->expanded_.empty()) {
1148 // this means that we do not recognize the macro
1149 throw MathExportException();
1155 void MathMacro::octave(OctaveStream & os) const
1157 lyx::octave(d->expanded_, os);
1161 void MathMacro::infoize(odocstream & os) const
1163 os << bformat(_("Macro: %1$s"), name());
1167 void MathMacro::infoize2(odocstream & os) const
1169 os << bformat(_("Macro: %1$s"), name());
1173 bool MathMacro::completionSupported(Cursor const & cur) const
1175 if (displayMode() != DISPLAY_UNFOLDED)
1176 return InsetMathNest::completionSupported(cur);
1178 return lyxrc.completion_popup_math
1179 && displayMode() == DISPLAY_UNFOLDED
1180 && cur.bv().cursor().pos() == int(name().size());
1184 bool MathMacro::inlineCompletionSupported(Cursor const & cur) const
1186 if (displayMode() != DISPLAY_UNFOLDED)
1187 return InsetMathNest::inlineCompletionSupported(cur);
1189 return lyxrc.completion_inline_math
1190 && displayMode() == DISPLAY_UNFOLDED
1191 && cur.bv().cursor().pos() == int(name().size());
1195 bool MathMacro::automaticInlineCompletion() const
1197 if (displayMode() != DISPLAY_UNFOLDED)
1198 return InsetMathNest::automaticInlineCompletion();
1200 return lyxrc.completion_inline_math;
1204 bool MathMacro::automaticPopupCompletion() const
1206 if (displayMode() != DISPLAY_UNFOLDED)
1207 return InsetMathNest::automaticPopupCompletion();
1209 return lyxrc.completion_popup_math;
1213 CompletionList const *
1214 MathMacro::createCompletionList(Cursor const & cur) const
1216 if (displayMode() != DISPLAY_UNFOLDED)
1217 return InsetMathNest::createCompletionList(cur);
1219 return new MathCompletionList(cur.bv().cursor());
1223 docstring MathMacro::completionPrefix(Cursor const & cur) const
1225 if (displayMode() != DISPLAY_UNFOLDED)
1226 return InsetMathNest::completionPrefix(cur);
1228 if (!completionSupported(cur))
1231 return "\\" + name();
1235 bool MathMacro::insertCompletion(Cursor & cur, docstring const & s,
1238 if (displayMode() != DISPLAY_UNFOLDED)
1239 return InsetMathNest::insertCompletion(cur, s, finished);
1241 if (!completionSupported(cur))
1244 // append completion
1245 docstring newName = name() + s;
1246 asArray(newName, cell(0));
1247 cur.bv().cursor().pos() = name().size();
1248 cur.screenUpdateFlags(Update::SinglePar);
1252 cur.bv().cursor().pop();
1253 ++cur.bv().cursor().pos();
1254 cur.screenUpdateFlags(Update::SinglePar);
1261 void MathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
1262 Dimension & dim) const
1264 if (displayMode() != DISPLAY_UNFOLDED)
1265 InsetMathNest::completionPosAndDim(cur, x, y, dim);
1267 // get inset dimensions
1268 dim = cur.bv().coordCache().insets().dim(this);
1269 // FIXME: these 3 are no accurate, but should depend on the font.
1270 // Now the popup jumps down if you enter a char with descent > 0.
1276 = cur.bv().coordCache().insets().xy(this);