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 // mathclass is ord because it should be spaced as a normal atom
100 MathRow::Element e(MathRow::BOX, MC_ORD);
101 e.color = Color_mathline;
106 MathRow::Element e_end(MathRow::END_ARG);
107 e_end.macro = mathMacro_;
108 e_end.ar = &mathMacro_->cell(idx_);
110 mrow.push_back(e_end);
115 void metrics(MetricsInfo &, Dimension &) const {
116 // This should never be invoked, since ArgumentProxy insets are linearized
120 int kerning(BufferView const * bv) const
122 return displayCell(bv).kerning(bv);
125 void draw(PainterInfo &, int, int) const {
126 // This should never be invoked, since ArgumentProxy insets are linearized
129 // write(), normalize(), infoize() and infoize2() are not needed since
130 // MathMacro uses the definition and not the expanded cells.
132 void maple(MapleStream & ms) const { ms << mathMacro_->cell(idx_); }
134 void maxima(MaximaStream & ms) const { ms << mathMacro_->cell(idx_); }
136 void mathematica(MathematicaStream & ms) const { ms << mathMacro_->cell(idx_); }
138 void mathmlize(MathStream & ms) const { ms << mathMacro_->cell(idx_); }
140 void htmlize(HtmlStream & ms) const { ms << mathMacro_->cell(idx_); }
142 void octave(OctaveStream & os) const { os << mathMacro_->cell(idx_); }
146 Inset * clone() const
148 return new ArgumentProxy(*this);
151 MathMacro * mathMacro_;
159 /// Private implementation of MathMacro
160 class MathMacro::Private {
162 Private(Buffer * buf, docstring const & name)
163 : name_(name), displayMode_(DISPLAY_INIT),
164 expanded_(buf), definition_(buf), attachedArgsNum_(0),
165 optionals_(0), nextFoldMode_(true), macroBackup_(buf),
166 macro_(0), needsUpdate_(false), isUpdating_(false),
170 /// Update the pointers to our owner of all expanded macros.
171 /// This needs to be called every time a copy of the owner is created
173 void updateChildren(MathMacro * owner);
174 /// Recursively update the pointers of all expanded macros
175 /// appearing in the arguments of the current macro
176 void updateNestedChildren(MathMacro * owner, InsetMathNest * ni);
179 /// current display mode
180 DisplayMode displayMode_;
181 /// expanded macro with ArgumentProxies
183 /// macro definition with #1,#2,.. insets
184 MathData definition_;
185 /// number of arguments that were really attached
186 size_t attachedArgsNum_;
187 /// optional argument attached? (only in DISPLAY_NORMAL mode)
189 /// fold mode to be set in next metrics call?
191 /// if macro_ == true, then here is a copy of the macro
192 /// don't use it for locking
193 MacroData macroBackup_;
194 /// if macroNotFound_ == false, then here is a reference to the macro
195 /// this might invalidate after metrics was called
196 MacroData const * macro_;
198 mutable std::map<BufferView const *, bool> editing_;
200 std::string requires_;
201 /// update macro representation
205 /// maximal number of arguments the macro is greedy for
207 /// Level of nesting in macros (including this one)
212 void MathMacro::Private::updateChildren(MathMacro * owner)
214 for (size_t i = 0; i < expanded_.size(); ++i) {
215 ArgumentProxy * p = dynamic_cast<ArgumentProxy *>(expanded_[i].nucleus());
219 InsetMathNest * ni = expanded_[i].nucleus()->asNestInset();
221 updateNestedChildren(owner, ni);
225 // The macro_ pointer is updated when MathData::metrics() is
226 // called. However, when instant preview is on or the macro is
227 // not on screen, MathData::metrics() is not called and we may
228 // have a dangling pointer. As a safety measure, when a macro
229 // is copied, always let macro_ point to the backup copy of the
230 // MacroData structure. This backup is updated every time the
231 // macro is changed, so it will not become stale.
232 macro_ = ¯oBackup_;
237 void MathMacro::Private::updateNestedChildren(MathMacro * owner, InsetMathNest * ni)
239 for (size_t i = 0; i < ni->nargs(); ++i) {
240 MathData & ar = ni->cell(i);
241 for (size_t j = 0; j < ar.size(); ++j) {
242 ArgumentProxy * ap = dynamic_cast
243 <ArgumentProxy *>(ar[j].nucleus());
245 MathMacro::Private * md = ap->owner()->d;
247 md->macro_ = &md->macroBackup_;
250 InsetMathNest * imn = ar[j].nucleus()->asNestInset();
252 updateNestedChildren(owner, imn);
258 MathMacro::MathMacro(Buffer * buf, docstring const & name)
259 : InsetMathNest(buf, 0), d(new Private(buf, name))
263 MathMacro::MathMacro(MathMacro const & that)
264 : InsetMathNest(that), d(new Private(*that.d))
266 setBuffer(*that.buffer_);
267 d->updateChildren(this);
271 MathMacro & MathMacro::operator=(MathMacro const & that)
275 InsetMathNest::operator=(that);
277 d->updateChildren(this);
282 MathMacro::~MathMacro()
288 bool MathMacro::addToMathRow(MathRow & mrow, MetricsInfo & mi) const
290 // set edit mode for which we will have calculated row.
291 // This is the same as what is done in metrics().
292 d->editing_[mi.base.bv] = editMode(mi.base.bv);
294 /// The macro nesting can change display of insets. Change it locally.
295 Changer chg = make_change(mi.base.macro_nesting, d->nesting_);
297 if (displayMode() != MathMacro::DISPLAY_NORMAL
298 || d->editing_[mi.base.bv])
299 return InsetMath::addToMathRow(mrow, mi);
301 MathRow::Element e_beg(MathRow::BEG_MACRO);
303 mrow.push_back(e_beg);
306 bool has_contents = d->expanded_.addToMathRow(mrow, mi);
309 // if there was no contents and the array is editable, then we
310 // insert a grey box instead.
311 if (!has_contents && mi.base.macro_nesting == 1) {
312 // mathclass is unknown because it is irrelevant for spacing
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);
630 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
631 Changer dummy = pi.base.changeFontSet("lyxtex");
632 pi.pain.text(x, y, from_ascii("\\") + name(), pi.base.font);
633 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
634 Changer dummy = pi.base.changeFontSet("lyxtex");
635 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
636 x += mathed_string_width(pi.base.font, from_ascii("\\")) + 1;
637 cell(0).draw(pi, x, y);
638 drawMarkers(pi, expx, expy);
639 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
640 && d->editing_[pi.base.bv]) {
641 // Macro will be edited in a old-style list mode here:
643 CoordCache const & coords = pi.base.bv->coordCache();
644 FontInfo const & labelFont = sane_font;
646 // markers and box needs two pixels
649 // get maximal font height
651 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
654 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
655 pi.pain.text(x, y, label, labelFont);
656 x += mathed_string_width(labelFont, label);
659 d->definition_.draw(pi, x, y);
660 Dimension const & defDim = coords.getArrays().dim(&d->definition_);
661 y += max(fontDim.des, defDim.des);
664 docstring str = from_ascii("#9");
665 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
666 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
668 for (idx_type i = 0; i < nargs(); ++i) {
670 Dimension const & cdim = coords.getArrays().dim(&cell(i));
672 y += max(fontDim.asc, cdim.asc) + 1;
676 pi.pain.text(x, y, str, labelFont);
678 pi.pain.text(x, y, from_ascii(":"), labelFont);
682 cell(i).draw(pi, x, y);
685 y += max(fontDim.des, cdim.des);
688 pi.pain.rectangle(expx + 1, expy - dim.asc + 1, dim.wid - 3,
689 dim.height() - 2, Color_mathmacroframe);
690 drawMarkers2(pi, expx, expy);
692 bool drawBox = lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX;
693 Changer dummy = (currentMode() == TEXT_MODE)
694 ? pi.base.font.changeShape(UP_SHAPE)
698 for (size_t i = 0; i < nargs(); ++i)
699 cell(i).setXY(*pi.base.bv, x, y);
701 if (drawBox && d->editing_[pi.base.bv]) {
702 // draw header and rectangle around
703 FontInfo font = pi.base.font;
704 augmentFont(font, "lyxtex");
705 font.setSize(FONT_SIZE_TINY);
706 font.setColor(Color_mathmacrolabel);
708 mathed_string_dim(font, name(), namedim);
710 pi.pain.fillRectangle(x, y - dim.asc, dim.wid, 1 + namedim.height() + 1, Color_mathmacrobg);
711 pi.pain.text(x + 1, y - dim.asc + namedim.asc + 2, name(), font);
712 expx += (dim.wid - d->expanded_.dimension(*pi.base.bv).width()) / 2;
715 if (d->editing_[pi.base.bv]) {
716 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
717 d->expanded_.draw(pi, expx, expy);
718 pi.pain.leaveMonochromeMode();
721 pi.pain.rectangle(x, y - dim.asc, dim.wid,
722 dim.height(), Color_mathmacroframe);
724 d->expanded_.draw(pi, expx, expy);
727 drawMarkers(pi, x, y);
731 // edit mode changed?
732 if (d->editing_[pi.base.bv] != editMode(pi.base.bv))
733 pi.base.bv->cursor().screenUpdateFlags(Update::SinglePar);
737 void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
739 // We may have 0 arguments, but InsetMathNest requires at least one.
741 InsetMathNest::drawSelection(pi, x, y);
745 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode, int appetite)
747 if (d->displayMode_ != mode) {
748 // transfer name if changing from or to DISPLAY_UNFOLDED
749 if (mode == DISPLAY_UNFOLDED) {
751 asArray(d->name_, cell(0));
752 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
753 d->name_ = asString(cell(0));
757 d->displayMode_ = mode;
758 d->needsUpdate_ = true;
761 // the interactive init mode is non-greedy by default
763 d->appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
765 d->appetite_ = size_t(appetite);
769 MathMacro::DisplayMode MathMacro::computeDisplayMode() const
771 if (d->nextFoldMode_ == true && d->macro_ && !d->macro_->locked())
772 return DISPLAY_NORMAL;
774 return DISPLAY_UNFOLDED;
778 bool MathMacro::validName() const
780 docstring n = name();
785 // converting back and force doesn't swallow anything?
788 if (asString(ma) != n)
792 for (size_t i = 0; i<n.size(); ++i) {
793 if (!(n[i] >= 'a' && n[i] <= 'z')
794 && !(n[i] >= 'A' && n[i] <= 'Z')
803 size_t MathMacro::arity() const
805 if (d->displayMode_ == DISPLAY_NORMAL )
806 return cells_.size();
812 size_t MathMacro::optionals() const
814 return d->optionals_;
818 void MathMacro::setOptionals(int n)
820 if (n <= int(nargs()))
825 size_t MathMacro::appetite() const
831 InsetMath::mode_type MathMacro::currentMode() const
833 // User defined macros are always assumed to be mathmode macros.
834 // Only the global macros defined in lib/symbols may be textmode.
836 MacroData const * data = MacroTable::globalMacros().get(name());
837 bool textmode = data && data->symbol() && data->symbol()->extra == "textmode";
838 return textmode ? TEXT_MODE : MATH_MODE;
842 void MathMacro::validate(LaTeXFeatures & features) const
844 // Immediately after a document is loaded, in some cases the MacroData
845 // of the global macros defined in the lib/symbols file may still not
846 // be known to the macro machinery because it will be set only after
847 // the first call to updateMacros(). This is not a problem unless
848 // instant preview is on for math, in which case we will be missing
849 // the corresponding requirements.
850 // In this case, we get the required info from the global macro table.
851 if (!d->requires_.empty())
852 features.require(d->requires_);
853 else if (!d->macro_) {
854 // Update requires for known global macros.
855 MacroData const * data = MacroTable::globalMacros().get(name());
856 if (data && !data->requires().empty())
857 features.require(data->requires());
860 if (name() == "binom")
861 features.require("binom");
863 // validate the cells and the definition
864 if (displayMode() == DISPLAY_NORMAL) {
865 d->definition_.validate(features);
866 InsetMathNest::validate(features);
871 void MathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
873 cur.screenUpdateFlags(Update::SinglePar);
874 InsetMathNest::edit(cur, front, entry_from);
878 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
880 // We may have 0 arguments, but InsetMathNest requires at least one.
882 cur.screenUpdateFlags(Update::SinglePar);
883 return InsetMathNest::editXY(cur, x, y);
889 void MathMacro::removeArgument(Inset::pos_type pos) {
890 if (d->displayMode_ == DISPLAY_NORMAL) {
891 LASSERT(size_t(pos) < cells_.size(), return);
892 cells_.erase(cells_.begin() + pos);
893 if (size_t(pos) < d->attachedArgsNum_)
894 --d->attachedArgsNum_;
895 if (size_t(pos) < d->optionals_) {
899 d->needsUpdate_ = true;
904 void MathMacro::insertArgument(Inset::pos_type pos) {
905 if (d->displayMode_ == DISPLAY_NORMAL) {
906 LASSERT(size_t(pos) <= cells_.size(), return);
907 cells_.insert(cells_.begin() + pos, MathData());
908 if (size_t(pos) < d->attachedArgsNum_)
909 ++d->attachedArgsNum_;
910 if (size_t(pos) < d->optionals_)
913 d->needsUpdate_ = true;
918 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
920 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
923 // strip off empty cells, but not more than arity-attachedArgsNum_
926 for (i = cells_.size(); i > d->attachedArgsNum_; --i)
927 if (!cell(i - 1).empty()) break;
931 d->attachedArgsNum_ = 0;
932 d->expanded_ = MathData();
935 d->needsUpdate_ = true;
939 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
941 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
943 d->attachedArgsNum_ = args.size();
944 cells_.resize(arity);
945 d->expanded_ = MathData();
946 d->optionals_ = optionals;
948 d->needsUpdate_ = true;
952 bool MathMacro::idxFirst(Cursor & cur) const
954 cur.screenUpdateFlags(Update::SinglePar);
955 return InsetMathNest::idxFirst(cur);
959 bool MathMacro::idxLast(Cursor & cur) const
961 cur.screenUpdateFlags(Update::SinglePar);
962 return InsetMathNest::idxLast(cur);
966 bool MathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
968 if (d->displayMode_ == DISPLAY_UNFOLDED) {
969 docstring const & unfolded_name = name();
970 if (unfolded_name != d->name_) {
971 // The macro name was changed
972 Cursor inset_cursor = old;
973 int macroSlice = inset_cursor.find(this);
974 // returning true means the cursor is "now" invalid,
976 LASSERT(macroSlice != -1, return true);
977 inset_cursor.cutOff(macroSlice);
978 inset_cursor.recordUndoInset();
980 inset_cursor.cell().erase(inset_cursor.pos());
981 inset_cursor.cell().insert(inset_cursor.pos(),
982 createInsetMath(unfolded_name, cur.buffer()));
984 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
988 cur.screenUpdateFlags(Update::Force);
989 return InsetMathNest::notifyCursorLeaves(old, cur);
993 void MathMacro::fold(Cursor & cur)
995 if (!d->nextFoldMode_) {
996 d->nextFoldMode_ = true;
997 cur.screenUpdateFlags(Update::SinglePar);
1002 void MathMacro::unfold(Cursor & cur)
1004 if (d->nextFoldMode_) {
1005 d->nextFoldMode_ = false;
1006 cur.screenUpdateFlags(Update::SinglePar);
1011 bool MathMacro::folded() const
1013 return d->nextFoldMode_;
1017 void MathMacro::write(WriteStream & os) const
1019 MacroData const * data = MacroTable::globalMacros().get(name());
1020 bool textmode_macro = data && data->symbol()
1021 && data->symbol()->extra == "textmode";
1022 bool needs_mathmode = data && (!data->symbol()
1023 || data->symbol()->extra != "textmode");
1025 MathEnsurer ensurer(os, needs_mathmode, true, textmode_macro);
1028 if (d->displayMode_ != DISPLAY_NORMAL) {
1029 os << "\\" << name();
1030 if (name().size() != 1 || isAlphaASCII(name()[0]))
1031 os.pendingSpace(true);
1036 // we should be ok to continue even if this fails.
1039 // We may already be in the argument of a macro
1040 bool const inside_macro = os.insideMacro();
1041 os.insideMacro(true);
1043 // Enclose in braces to avoid latex errors with xargs if we have
1044 // optional arguments and are in the optional argument of a macro
1045 if (d->optionals_ && inside_macro)
1048 // Always protect macros in a fragile environment
1052 os << "\\" << name();
1055 // Optional arguments:
1056 // First find last non-empty optional argument
1057 idx_type emptyOptFrom = 0;
1059 for (; i < cells_.size() && i < d->optionals_; ++i) {
1060 if (!cell(i).empty())
1061 emptyOptFrom = i + 1;
1064 // print out optionals
1065 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
1067 os << "[" << cell(i) << "]";
1070 // skip the tailing empty optionals
1073 // Print remaining arguments
1074 for (; i < cells_.size(); ++i) {
1075 if (cell(i).size() == 1
1076 && cell(i)[0].nucleus()->asCharInset()
1077 && isASCII(cell(i)[0].nucleus()->asCharInset()->getChar())) {
1082 os << "{" << cell(i) << "}";
1086 // Close the opened brace or add space if there was no argument
1087 if (d->optionals_ && inside_macro)
1090 os.pendingSpace(true);
1092 os.insideMacro(inside_macro);
1096 void MathMacro::maple(MapleStream & os) const
1098 lyx::maple(d->expanded_, os);
1102 void MathMacro::maxima(MaximaStream & os) const
1104 lyx::maxima(d->expanded_, os);
1108 void MathMacro::mathematica(MathematicaStream & os) const
1110 lyx::mathematica(d->expanded_, os);
1114 void MathMacro::mathmlize(MathStream & os) const
1116 // macro_ is 0 if this is an unknown macro
1117 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1119 docstring const xmlname = d->macro_->xmlname();
1120 if (!xmlname.empty()) {
1121 char const * type = d->macro_->MathMLtype();
1122 os << '<' << type << "> " << xmlname << " </"
1127 if (d->expanded_.empty()) {
1128 // this means that we do not recognize the macro
1129 throw MathExportException();
1135 void MathMacro::htmlize(HtmlStream & os) const
1137 // macro_ is 0 if this is an unknown macro
1138 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1140 docstring const xmlname = d->macro_->xmlname();
1141 if (!xmlname.empty()) {
1142 os << ' ' << xmlname << ' ';
1146 if (d->expanded_.empty()) {
1147 // this means that we do not recognize the macro
1148 throw MathExportException();
1154 void MathMacro::octave(OctaveStream & os) const
1156 lyx::octave(d->expanded_, os);
1160 void MathMacro::infoize(odocstream & os) const
1162 os << bformat(_("Macro: %1$s"), name());
1166 void MathMacro::infoize2(odocstream & os) const
1168 os << bformat(_("Macro: %1$s"), name());
1172 bool MathMacro::completionSupported(Cursor const & cur) const
1174 if (displayMode() != DISPLAY_UNFOLDED)
1175 return InsetMathNest::completionSupported(cur);
1177 return lyxrc.completion_popup_math
1178 && displayMode() == DISPLAY_UNFOLDED
1179 && cur.bv().cursor().pos() == int(name().size());
1183 bool MathMacro::inlineCompletionSupported(Cursor const & cur) const
1185 if (displayMode() != DISPLAY_UNFOLDED)
1186 return InsetMathNest::inlineCompletionSupported(cur);
1188 return lyxrc.completion_inline_math
1189 && displayMode() == DISPLAY_UNFOLDED
1190 && cur.bv().cursor().pos() == int(name().size());
1194 bool MathMacro::automaticInlineCompletion() const
1196 if (displayMode() != DISPLAY_UNFOLDED)
1197 return InsetMathNest::automaticInlineCompletion();
1199 return lyxrc.completion_inline_math;
1203 bool MathMacro::automaticPopupCompletion() const
1205 if (displayMode() != DISPLAY_UNFOLDED)
1206 return InsetMathNest::automaticPopupCompletion();
1208 return lyxrc.completion_popup_math;
1212 CompletionList const *
1213 MathMacro::createCompletionList(Cursor const & cur) const
1215 if (displayMode() != DISPLAY_UNFOLDED)
1216 return InsetMathNest::createCompletionList(cur);
1218 return new MathCompletionList(cur.bv().cursor());
1222 docstring MathMacro::completionPrefix(Cursor const & cur) const
1224 if (displayMode() != DISPLAY_UNFOLDED)
1225 return InsetMathNest::completionPrefix(cur);
1227 if (!completionSupported(cur))
1230 return "\\" + name();
1234 bool MathMacro::insertCompletion(Cursor & cur, docstring const & s,
1237 if (displayMode() != DISPLAY_UNFOLDED)
1238 return InsetMathNest::insertCompletion(cur, s, finished);
1240 if (!completionSupported(cur))
1243 // append completion
1244 docstring newName = name() + s;
1245 asArray(newName, cell(0));
1246 cur.bv().cursor().pos() = name().size();
1247 cur.screenUpdateFlags(Update::SinglePar);
1251 cur.bv().cursor().pop();
1252 ++cur.bv().cursor().pos();
1253 cur.screenUpdateFlags(Update::SinglePar);
1260 void MathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
1261 Dimension & dim) const
1263 if (displayMode() != DISPLAY_UNFOLDED)
1264 InsetMathNest::completionPosAndDim(cur, x, y, dim);
1266 // get inset dimensions
1267 dim = cur.bv().coordCache().insets().dim(this);
1268 // FIXME: these 3 are no accurate, but should depend on the font.
1269 // Now the popup jumps down if you enter a char with descent > 0.
1275 = cur.bv().coordCache().insets().xy(this);