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 bool addToMathRow(MathRow & mrow, MetricsInfo const & mi) const
73 MathRow::Element e(MathRow::BEG_ARG);
75 e.ar = &mathMacro_->cell(idx_);
78 mathMacro_->macro()->unlock();
79 bool const has_contents = mathMacro_->cell(idx_).addToMathRow(mrow, mi);
80 mathMacro_->macro()->lock();
82 e.type = MathRow::END_ARG;
87 // if there was no contents, then we insert the empty macro inset
89 return InsetMath::addToMathRow(mrow, mi);
92 void metrics(MetricsInfo & mi, Dimension & dim) const {
93 mathMacro_->macro()->unlock();
94 mathMacro_->cell(idx_).metrics(mi, dim);
96 if (!mathMacro_->editMetrics(mi.base.bv)
97 && mathMacro_->cell(idx_).empty())
98 def_.metrics(mi, dim);
100 mathMacro_->macro()->lock();
102 // write(), normalize(), infoize() and infoize2() are not needed since
103 // MathMacro uses the definition and not the expanded cells.
105 void maple(MapleStream & ms) const { ms << mathMacro_->cell(idx_); }
107 void maxima(MaximaStream & ms) const { ms << mathMacro_->cell(idx_); }
109 void mathematica(MathematicaStream & ms) const { ms << mathMacro_->cell(idx_); }
111 void mathmlize(MathStream & ms) const { ms << mathMacro_->cell(idx_); }
113 void htmlize(HtmlStream & ms) const { ms << mathMacro_->cell(idx_); }
115 void octave(OctaveStream & os) const { os << mathMacro_->cell(idx_); }
117 void draw(PainterInfo & pi, int x, int y) const {
118 if (mathMacro_->editMetrics(pi.base.bv)) {
119 // The only way a ArgumentProxy can appear is in a cell of the
120 // MathMacro. Moreover the cells are only drawn in the DISPLAY_FOLDED
121 // mode and then, if the macro is edited the monochrome
122 // mode is entered by the MathMacro before calling the cells' draw
123 // method. Then eventually this code is reached and the proxy leaves
124 // monochrome mode temporarely. Hence, if it is not in monochrome
125 // here (and the assert triggers in pain.leaveMonochromeMode())
127 pi.pain.leaveMonochromeMode();
128 mathMacro_->cell(idx_).draw(pi, x, y);
129 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
130 } else if (mathMacro_->cell(idx_).empty()) {
131 mathMacro_->cell(idx_).setXY(*pi.base.bv, x, y);
134 mathMacro_->cell(idx_).draw(pi, x, y);
137 size_t idx() const { return idx_; }
139 int kerning(BufferView const * bv) const
141 if (mathMacro_->editMetrics(bv)
142 || !mathMacro_->cell(idx_).empty())
143 return mathMacro_->cell(idx_).kerning(bv);
145 return def_.kerning(bv);
150 Inset * clone() const
152 return new ArgumentProxy(*this);
155 MathMacro * mathMacro_;
163 /// Private implementation of MathMacro
164 class MathMacro::Private {
166 Private(Buffer * buf, docstring const & name)
167 : name_(name), displayMode_(DISPLAY_INIT),
168 expanded_(buf), definition_(buf), attachedArgsNum_(0),
169 optionals_(0), nextFoldMode_(true), macroBackup_(buf),
170 macro_(0), needsUpdate_(false), isUpdating_(false),
174 /// Update the pointers to our owner of all expanded macros.
175 /// This needs to be called every time a copy of the owner is created
177 void updateChildren(MathMacro * owner);
178 /// Recursively update the pointers of all expanded macros
179 /// appearing in the arguments of the current macro
180 void updateNestedChildren(MathMacro * owner, InsetMathNest * ni);
183 /// current display mode
184 DisplayMode displayMode_;
185 /// expanded macro with ArgumentProxies
187 /// macro definition with #1,#2,.. insets
188 MathData definition_;
189 /// number of arguments that were really attached
190 size_t attachedArgsNum_;
191 /// optional argument attached? (only in DISPLAY_NORMAL mode)
193 /// fold mode to be set in next metrics call?
195 /// if macro_ == true, then here is a copy of the macro
196 /// don't use it for locking
197 MacroData macroBackup_;
198 /// if macroNotFound_ == false, then here is a reference to the macro
199 /// this might invalidate after metrics was called
200 MacroData const * macro_;
202 mutable std::map<BufferView const *, bool> editing_;
204 std::string requires_;
205 /// update macro representation
209 /// maximal number of arguments the macro is greedy for
214 void MathMacro::Private::updateChildren(MathMacro * owner)
216 for (size_t i = 0; i < expanded_.size(); ++i) {
217 ArgumentProxy * p = dynamic_cast<ArgumentProxy *>(expanded_[i].nucleus());
221 InsetMathNest * ni = expanded_[i].nucleus()->asNestInset();
223 updateNestedChildren(owner, ni);
227 // The macro_ pointer is updated when MathData::metrics() is
228 // called. However, when instant preview is on or the macro is
229 // not on screen, MathData::metrics() is not called and we may
230 // have a dangling pointer. As a safety measure, when a macro
231 // is copied, always let macro_ point to the backup copy of the
232 // MacroData structure. This backup is updated every time the
233 // macro is changed, so it will not become stale.
234 macro_ = ¯oBackup_;
239 void MathMacro::Private::updateNestedChildren(MathMacro * owner, InsetMathNest * ni)
241 for (size_t i = 0; i < ni->nargs(); ++i) {
242 MathData & ar = ni->cell(i);
243 for (size_t j = 0; j < ar.size(); ++j) {
244 ArgumentProxy * ap = dynamic_cast
245 <ArgumentProxy *>(ar[j].nucleus());
247 MathMacro::Private * md = ap->owner()->d;
249 md->macro_ = &md->macroBackup_;
252 InsetMathNest * imn = ar[j].nucleus()->asNestInset();
254 updateNestedChildren(owner, imn);
260 MathMacro::MathMacro(Buffer * buf, docstring const & name)
261 : InsetMathNest(buf, 0), d(new Private(buf, name))
265 MathMacro::MathMacro(MathMacro const & that)
266 : InsetMathNest(that), d(new Private(*that.d))
268 setBuffer(*that.buffer_);
269 d->updateChildren(this);
273 MathMacro & MathMacro::operator=(MathMacro const & that)
277 InsetMathNest::operator=(that);
279 d->updateChildren(this);
284 MathMacro::~MathMacro()
290 bool MathMacro::addToMathRow(MathRow & mrow, MetricsInfo const & mi) const
292 // set edit mode for which we will have calculated row.
293 // This is the same as what is done in metrics().
294 d->editing_[mi.base.bv] = editMode(mi.base.bv);
296 if (displayMode() == MathMacro::DISPLAY_NORMAL
297 && !d->editing_[mi.base.bv]) {
298 MathRow::Element e(MathRow::BEG_MACRO);
303 bool const has_contents = d->expanded_.addToMathRow(mrow, mi);
306 e.type = MathRow::END_MACRO;
311 // if there was no contents, then we insert the empty macro inset
314 return InsetMath::addToMathRow(mrow, mi);
318 Inset * MathMacro::clone() const
320 MathMacro * copy = new MathMacro(*this);
321 copy->d->needsUpdate_ = true;
322 //copy->d->expanded_.clear();
327 void MathMacro::normalize(NormalStream & os) const
329 os << "[macro " << name();
330 for (size_t i = 0; i < nargs(); ++i)
331 os << ' ' << cell(i);
336 MathMacro::DisplayMode MathMacro::displayMode() const
338 return d->displayMode_;
342 bool MathMacro::extraBraces() const
344 return d->displayMode_ == DISPLAY_NORMAL && arity() > 0;
348 docstring MathMacro::name() const
350 if (d->displayMode_ == DISPLAY_UNFOLDED)
351 return asString(cell(0));
357 docstring MathMacro::macroName() const
363 void MathMacro::cursorPos(BufferView const & bv,
364 CursorSlice const & sl, bool boundary, int & x, int & y) const
366 // We may have 0 arguments, but InsetMathNest requires at least one.
368 InsetMathNest::cursorPos(bv, sl, boundary, x, y);
372 bool MathMacro::editMode(BufferView const * bv) const {
373 // find this in cursor trace
374 Cursor const & cur = bv->cursor();
375 for (size_t i = 0; i != cur.depth(); ++i)
376 if (&cur[i].inset() == this) {
377 // look if there is no other macro in edit mode above
379 for (; i != cur.depth(); ++i) {
380 InsetMath * im = cur[i].asInsetMath();
382 MathMacro const * macro = im->asMacro();
383 if (macro && macro->displayMode() == DISPLAY_NORMAL)
388 // ok, none found, I am the highest one
396 MacroData const * MathMacro::macro() const
402 bool MathMacro::editMetrics(BufferView const * bv) const
404 return d->editing_[bv];
408 void MathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
410 // set edit mode for which we will have calculated metrics. But only
411 d->editing_[mi.base.bv] = editMode(mi.base.bv);
413 // calculate new metrics according to display mode
414 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
415 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
416 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
417 cell(0).metrics(mi, dim);
419 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
420 dim.wid += bsdim.width() + 1;
421 dim.asc = max(bsdim.ascent(), dim.ascent());
422 dim.des = max(bsdim.descent(), dim.descent());
424 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
425 && d->editing_[mi.base.bv]) {
426 // Macro will be edited in a old-style list mode here:
430 FontInfo labelFont = sane_font;
431 math_font_max_dim(labelFont, fontDim.asc, fontDim.des);
433 // get dimension of components of list view
435 nameDim.wid = mathed_string_width(mi.base.font, from_ascii("Macro \\") + name() + ": ");
436 nameDim.asc = fontDim.asc;
437 nameDim.des = fontDim.des;
440 argDim.wid = mathed_string_width(labelFont, from_ascii("#9: "));
441 argDim.asc = fontDim.asc;
442 argDim.des = fontDim.des;
445 d->definition_.metrics(mi, defDim);
448 dim.wid = nameDim.wid + defDim.wid;
449 dim.asc = max(nameDim.asc, defDim.asc);
450 dim.des = max(nameDim.des, defDim.des);
452 for (idx_type i = 0; i < nargs(); ++i) {
454 cell(i).metrics(mi, cdim);
455 dim.des += max(argDim.height(), cdim.height()) + 1;
456 dim.wid = max(dim.wid, argDim.wid + cdim.wid);
459 // make space for box and markers, 2 pixels
463 metricsMarkers2(dim);
467 // calculate metrics, hoping that all cells are seen
469 d->expanded_.metrics(mi, dim);
471 // otherwise do a manual metrics call
472 CoordCache & coords = mi.base.bv->coordCache();
473 for (idx_type i = 0; i < nargs(); ++i) {
474 if (!coords.getArrays().hasDim(&cell(i))) {
476 cell(i).metrics(mi, tdim);
481 // calculate dimension with label while editing
482 if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX
483 && d->editing_[mi.base.bv]) {
484 FontInfo font = mi.base.font;
485 augmentFont(font, "lyxtex");
487 mathed_string_dim(font, name(), namedim);
489 dim.wid += 2 + namedim.wid + 2 + 2;
490 dim.asc = max(dim.asc, namedim.asc) + 2;
491 dim.des = max(dim.des, namedim.des) + 2;
493 dim.wid = max(1 + namedim.wid + 1, 2 + dim.wid + 2);
494 dim.asc += 1 + namedim.height() + 1;
501 int MathMacro::kerning(BufferView const * bv) const {
502 if (d->displayMode_ == DISPLAY_NORMAL && !d->editing_[bv])
503 return d->expanded_.kerning(bv);
509 void MathMacro::updateMacro(MacroContext const & mc)
512 d->macro_ = mc.get(name());
513 if (d->macro_ && d->macroBackup_ != *d->macro_) {
514 d->macroBackup_ = *d->macro_;
515 d->needsUpdate_ = true;
523 class MathMacro::UpdateLocker
526 explicit UpdateLocker(MathMacro & mm) : mac(mm)
528 mac.d->isUpdating_ = true;
530 ~UpdateLocker() { mac.d->isUpdating_ = false; }
534 /** Avoid wrong usage of UpdateLocker.
535 To avoid wrong usage:
536 UpdateLocker(...); // wrong
537 UpdateLocker locker(...); // right
539 #define UpdateLocker(x) unnamed_UpdateLocker;
540 // Tip gotten from Bobby Schmidt's column in C/C++ Users Journal
543 void MathMacro::updateRepresentation(Cursor * cur, MacroContext const & mc,
546 // block recursive calls (bug 8999)
550 UpdateLocker locker(*this);
557 d->requires_ = d->macro_->requires();
560 // non-normal mode? We are done!
561 || (d->displayMode_ != DISPLAY_NORMAL))
564 d->needsUpdate_ = false;
566 // get default values of macro
567 vector<docstring> const & defaults = d->macro_->defaults();
569 // create MathMacroArgumentValue objects pointing to the cells of the macro
570 vector<MathData> values(nargs());
571 for (size_t i = 0; i < nargs(); ++i) {
572 ArgumentProxy * proxy;
573 if (i < defaults.size())
574 proxy = new ArgumentProxy(this, i, defaults[i]);
576 proxy = new ArgumentProxy(this, i);
577 values[i].insert(0, MathAtom(proxy));
579 // expanding macro with the values
580 // Only update the argument macros if anything was expanded, otherwise
581 // we would get an endless loop (bug 9140). UpdateLocker does not work
582 // in this case, since MacroData::expand() creates new MathMacro
583 // objects, so this would be a different recursion path than the one
584 // protected by UpdateLocker.
585 if (d->macro_->expand(values, d->expanded_)) {
586 if (utype == OutputUpdate && !d->expanded_.empty())
587 d->expanded_.updateMacros(cur, mc, utype);
589 // get definition for list edit mode
590 docstring const & display = d->macro_->display();
591 asArray(display.empty() ? d->macro_->definition() : display,
592 d->definition_, Parse::QUIET);
596 void MathMacro::draw(PainterInfo & pi, int x, int y) const
598 Dimension const dim = dimension(*pi.base.bv);
600 setPosCache(pi, x, y);
604 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
605 Changer dummy = pi.base.changeFontSet("lyxtex");
606 pi.pain.text(x, y, from_ascii("\\") + name(), pi.base.font);
607 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
608 Changer dummy = pi.base.changeFontSet("lyxtex");
609 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
610 x += mathed_string_width(pi.base.font, from_ascii("\\")) + 1;
611 cell(0).draw(pi, x, y);
612 drawMarkers(pi, expx, expy);
613 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
614 && d->editing_[pi.base.bv]) {
615 // Macro will be edited in a old-style list mode here:
617 CoordCache const & coords = pi.base.bv->coordCache();
618 FontInfo const & labelFont = sane_font;
620 // markers and box needs two pixels
623 // get maximal font height
625 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
628 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
629 pi.pain.text(x, y, label, labelFont);
630 x += mathed_string_width(labelFont, label);
633 d->definition_.draw(pi, x, y);
634 Dimension const & defDim = coords.getArrays().dim(&d->definition_);
635 y += max(fontDim.des, defDim.des);
638 docstring str = from_ascii("#9");
639 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
640 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
642 for (idx_type i = 0; i < nargs(); ++i) {
644 Dimension const & cdim = coords.getArrays().dim(&cell(i));
646 y += max(fontDim.asc, cdim.asc) + 1;
650 pi.pain.text(x, y, str, labelFont);
652 pi.pain.text(x, y, from_ascii(":"), labelFont);
656 cell(i).draw(pi, x, y);
659 y += max(fontDim.des, cdim.des);
662 pi.pain.rectangle(expx + 1, expy - dim.asc + 1, dim.wid - 3,
663 dim.height() - 2, Color_mathmacroframe);
664 drawMarkers2(pi, expx, expy);
666 bool drawBox = lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX;
667 bool upshape = currentMode() == TEXT_MODE;
668 Changer dummy = pi.base.font.changeShape(upshape ? UP_SHAPE
669 : pi.base.font.shape());
672 for (size_t i = 0; i < nargs(); ++i)
673 cell(i).setXY(*pi.base.bv, x, y);
675 if (drawBox && d->editing_[pi.base.bv]) {
676 // draw header and rectangle around
677 FontInfo font = pi.base.font;
678 augmentFont(font, "lyxtex");
679 font.setSize(FONT_SIZE_TINY);
680 font.setColor(Color_mathmacrolabel);
682 mathed_string_dim(font, name(), namedim);
684 pi.pain.fillRectangle(x, y - dim.asc, dim.wid, 1 + namedim.height() + 1, Color_mathmacrobg);
685 pi.pain.text(x + 1, y - dim.asc + namedim.asc + 2, name(), font);
686 expx += (dim.wid - d->expanded_.dimension(*pi.base.bv).width()) / 2;
689 if (d->editing_[pi.base.bv]) {
690 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
691 d->expanded_.draw(pi, expx, expy);
692 pi.pain.leaveMonochromeMode();
695 pi.pain.rectangle(x, y - dim.asc, dim.wid,
696 dim.height(), Color_mathmacroframe);
698 d->expanded_.draw(pi, expx, expy);
701 drawMarkers(pi, x, y);
704 // edit mode changed?
705 if (d->editing_[pi.base.bv] != editMode(pi.base.bv))
706 pi.base.bv->cursor().screenUpdateFlags(Update::SinglePar);
710 void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
712 // We may have 0 arguments, but InsetMathNest requires at least one.
714 InsetMathNest::drawSelection(pi, x, y);
718 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode, int appetite)
720 if (d->displayMode_ != mode) {
721 // transfer name if changing from or to DISPLAY_UNFOLDED
722 if (mode == DISPLAY_UNFOLDED) {
724 asArray(d->name_, cell(0));
725 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
726 d->name_ = asString(cell(0));
730 d->displayMode_ = mode;
731 d->needsUpdate_ = true;
734 // the interactive init mode is non-greedy by default
736 d->appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
738 d->appetite_ = size_t(appetite);
742 MathMacro::DisplayMode MathMacro::computeDisplayMode() const
744 if (d->nextFoldMode_ == true && d->macro_ && !d->macro_->locked())
745 return DISPLAY_NORMAL;
747 return DISPLAY_UNFOLDED;
751 bool MathMacro::validName() const
753 docstring n = name();
758 // converting back and force doesn't swallow anything?
761 if (asString(ma) != n)
765 for (size_t i = 0; i<n.size(); ++i) {
766 if (!(n[i] >= 'a' && n[i] <= 'z')
767 && !(n[i] >= 'A' && n[i] <= 'Z')
776 size_t MathMacro::arity() const
778 if (d->displayMode_ == DISPLAY_NORMAL )
779 return cells_.size();
785 size_t MathMacro::optionals() const
787 return d->optionals_;
791 void MathMacro::setOptionals(int n)
793 if (n <= int(nargs()))
798 size_t MathMacro::appetite() const
804 InsetMath::mode_type MathMacro::currentMode() const
806 // User defined macros are always assumed to be mathmode macros.
807 // Only the global macros defined in lib/symbols may be textmode.
809 MacroData const * data = MacroTable::globalMacros().get(name());
810 bool textmode = data && data->symbol() && data->symbol()->extra == "textmode";
811 return textmode ? TEXT_MODE : MATH_MODE;
815 void MathMacro::validate(LaTeXFeatures & features) const
817 // Immediately after a document is loaded, in some cases the MacroData
818 // of the global macros defined in the lib/symbols file may still not
819 // be known to the macro machinery because it will be set only after
820 // the first call to updateMacros(). This is not a problem unless
821 // instant preview is on for math, in which case we will be missing
822 // the corresponding requirements.
823 // In this case, we get the required info from the global macro table.
824 if (!d->requires_.empty())
825 features.require(d->requires_);
826 else if (!d->macro_) {
827 // Update requires for known global macros.
828 MacroData const * data = MacroTable::globalMacros().get(name());
829 if (data && !data->requires().empty())
830 features.require(data->requires());
833 if (name() == "binom")
834 features.require("binom");
836 // validate the cells and the definition
837 if (displayMode() == DISPLAY_NORMAL) {
838 d->definition_.validate(features);
839 InsetMathNest::validate(features);
844 void MathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
846 cur.screenUpdateFlags(Update::SinglePar);
847 InsetMathNest::edit(cur, front, entry_from);
851 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
853 // We may have 0 arguments, but InsetMathNest requires at least one.
855 cur.screenUpdateFlags(Update::SinglePar);
856 return InsetMathNest::editXY(cur, x, y);
862 void MathMacro::removeArgument(Inset::pos_type pos) {
863 if (d->displayMode_ == DISPLAY_NORMAL) {
864 LASSERT(size_t(pos) < cells_.size(), return);
865 cells_.erase(cells_.begin() + pos);
866 if (size_t(pos) < d->attachedArgsNum_)
867 --d->attachedArgsNum_;
868 if (size_t(pos) < d->optionals_) {
872 d->needsUpdate_ = true;
877 void MathMacro::insertArgument(Inset::pos_type pos) {
878 if (d->displayMode_ == DISPLAY_NORMAL) {
879 LASSERT(size_t(pos) <= cells_.size(), return);
880 cells_.insert(cells_.begin() + pos, MathData());
881 if (size_t(pos) < d->attachedArgsNum_)
882 ++d->attachedArgsNum_;
883 if (size_t(pos) < d->optionals_)
886 d->needsUpdate_ = true;
891 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
893 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
896 // strip off empty cells, but not more than arity-attachedArgsNum_
899 for (i = cells_.size(); i > d->attachedArgsNum_; --i)
900 if (!cell(i - 1).empty()) break;
904 d->attachedArgsNum_ = 0;
905 d->expanded_ = MathData();
908 d->needsUpdate_ = true;
912 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
914 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
916 d->attachedArgsNum_ = args.size();
917 cells_.resize(arity);
918 d->expanded_ = MathData();
919 d->optionals_ = optionals;
921 d->needsUpdate_ = true;
925 bool MathMacro::idxFirst(Cursor & cur) const
927 cur.screenUpdateFlags(Update::SinglePar);
928 return InsetMathNest::idxFirst(cur);
932 bool MathMacro::idxLast(Cursor & cur) const
934 cur.screenUpdateFlags(Update::SinglePar);
935 return InsetMathNest::idxLast(cur);
939 bool MathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
941 if (d->displayMode_ == DISPLAY_UNFOLDED) {
942 docstring const & unfolded_name = name();
943 if (unfolded_name != d->name_) {
944 // The macro name was changed
945 Cursor inset_cursor = old;
946 int macroSlice = inset_cursor.find(this);
947 // returning true means the cursor is "now" invalid,
949 LASSERT(macroSlice != -1, return true);
950 inset_cursor.cutOff(macroSlice);
951 inset_cursor.recordUndoInset();
953 inset_cursor.cell().erase(inset_cursor.pos());
954 inset_cursor.cell().insert(inset_cursor.pos(),
955 createInsetMath(unfolded_name, cur.buffer()));
957 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
961 cur.screenUpdateFlags(Update::Force);
962 return InsetMathNest::notifyCursorLeaves(old, cur);
966 void MathMacro::fold(Cursor & cur)
968 if (!d->nextFoldMode_) {
969 d->nextFoldMode_ = true;
970 cur.screenUpdateFlags(Update::SinglePar);
975 void MathMacro::unfold(Cursor & cur)
977 if (d->nextFoldMode_) {
978 d->nextFoldMode_ = false;
979 cur.screenUpdateFlags(Update::SinglePar);
984 bool MathMacro::folded() const
986 return d->nextFoldMode_;
990 void MathMacro::write(WriteStream & os) const
992 MacroData const * data = MacroTable::globalMacros().get(name());
993 bool textmode_macro = data && data->symbol()
994 && data->symbol()->extra == "textmode";
995 bool needs_mathmode = data && (!data->symbol()
996 || data->symbol()->extra != "textmode");
998 MathEnsurer ensurer(os, needs_mathmode, true, textmode_macro);
1001 if (d->displayMode_ != DISPLAY_NORMAL) {
1002 os << "\\" << name();
1003 if (name().size() != 1 || isAlphaASCII(name()[0]))
1004 os.pendingSpace(true);
1009 // we should be ok to continue even if this fails.
1012 // Always protect macros in a fragile environment
1016 os << "\\" << name();
1019 // Optional arguments:
1020 // First find last non-empty optional argument
1021 idx_type emptyOptFrom = 0;
1023 for (; i < cells_.size() && i < d->optionals_; ++i) {
1024 if (!cell(i).empty())
1025 emptyOptFrom = i + 1;
1028 // print out optionals
1029 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
1031 os << "[" << cell(i) << "]";
1034 // skip the tailing empty optionals
1037 // Print remaining arguments
1038 for (; i < cells_.size(); ++i) {
1039 if (cell(i).size() == 1
1040 && cell(i)[0].nucleus()->asCharInset()
1041 && isASCII(cell(i)[0].nucleus()->asCharInset()->getChar())) {
1046 os << "{" << cell(i) << "}";
1050 // add space if there was no argument
1052 os.pendingSpace(true);
1056 void MathMacro::maple(MapleStream & os) const
1058 lyx::maple(d->expanded_, os);
1062 void MathMacro::maxima(MaximaStream & os) const
1064 lyx::maxima(d->expanded_, os);
1068 void MathMacro::mathematica(MathematicaStream & os) const
1070 lyx::mathematica(d->expanded_, os);
1074 void MathMacro::mathmlize(MathStream & os) const
1076 // macro_ is 0 if this is an unknown macro
1077 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1079 docstring const xmlname = d->macro_->xmlname();
1080 if (!xmlname.empty()) {
1081 char const * type = d->macro_->MathMLtype();
1082 os << '<' << type << "> " << xmlname << " </"
1087 if (d->expanded_.empty()) {
1088 // this means that we do not recognize the macro
1089 throw MathExportException();
1095 void MathMacro::htmlize(HtmlStream & os) const
1097 // macro_ is 0 if this is an unknown macro
1098 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1100 docstring const xmlname = d->macro_->xmlname();
1101 if (!xmlname.empty()) {
1102 os << ' ' << xmlname << ' ';
1106 if (d->expanded_.empty()) {
1107 // this means that we do not recognize the macro
1108 throw MathExportException();
1114 void MathMacro::octave(OctaveStream & os) const
1116 lyx::octave(d->expanded_, os);
1120 void MathMacro::infoize(odocstream & os) const
1122 os << bformat(_("Macro: %1$s"), name());
1126 void MathMacro::infoize2(odocstream & os) const
1128 os << bformat(_("Macro: %1$s"), name());
1132 bool MathMacro::completionSupported(Cursor const & cur) const
1134 if (displayMode() != DISPLAY_UNFOLDED)
1135 return InsetMathNest::completionSupported(cur);
1137 return lyxrc.completion_popup_math
1138 && displayMode() == DISPLAY_UNFOLDED
1139 && cur.bv().cursor().pos() == int(name().size());
1143 bool MathMacro::inlineCompletionSupported(Cursor const & cur) const
1145 if (displayMode() != DISPLAY_UNFOLDED)
1146 return InsetMathNest::inlineCompletionSupported(cur);
1148 return lyxrc.completion_inline_math
1149 && displayMode() == DISPLAY_UNFOLDED
1150 && cur.bv().cursor().pos() == int(name().size());
1154 bool MathMacro::automaticInlineCompletion() const
1156 if (displayMode() != DISPLAY_UNFOLDED)
1157 return InsetMathNest::automaticInlineCompletion();
1159 return lyxrc.completion_inline_math;
1163 bool MathMacro::automaticPopupCompletion() const
1165 if (displayMode() != DISPLAY_UNFOLDED)
1166 return InsetMathNest::automaticPopupCompletion();
1168 return lyxrc.completion_popup_math;
1172 CompletionList const *
1173 MathMacro::createCompletionList(Cursor const & cur) const
1175 if (displayMode() != DISPLAY_UNFOLDED)
1176 return InsetMathNest::createCompletionList(cur);
1178 return new MathCompletionList(cur.bv().cursor());
1182 docstring MathMacro::completionPrefix(Cursor const & cur) const
1184 if (displayMode() != DISPLAY_UNFOLDED)
1185 return InsetMathNest::completionPrefix(cur);
1187 if (!completionSupported(cur))
1190 return "\\" + name();
1194 bool MathMacro::insertCompletion(Cursor & cur, docstring const & s,
1197 if (displayMode() != DISPLAY_UNFOLDED)
1198 return InsetMathNest::insertCompletion(cur, s, finished);
1200 if (!completionSupported(cur))
1203 // append completion
1204 docstring newName = name() + s;
1205 asArray(newName, cell(0));
1206 cur.bv().cursor().pos() = name().size();
1207 cur.screenUpdateFlags(Update::SinglePar);
1211 cur.bv().cursor().pop();
1212 ++cur.bv().cursor().pos();
1213 cur.screenUpdateFlags(Update::SinglePar);
1220 void MathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
1221 Dimension & dim) const
1223 if (displayMode() != DISPLAY_UNFOLDED)
1224 InsetMathNest::completionPosAndDim(cur, x, y, dim);
1226 // get inset dimensions
1227 dim = cur.bv().coordCache().insets().dim(this);
1228 // FIXME: these 3 are no accurate, but should depend on the font.
1229 // Now the popup jumps down if you enter a char with descent > 0.
1235 = cur.bv().coordCache().insets().xy(this);