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
119 // write(), normalize(), infoize() and infoize2() are not needed since
120 // MathMacro uses the definition and not the expanded cells.
122 void maple(MapleStream & ms) const { ms << mathMacro_->cell(idx_); }
124 void maxima(MaximaStream & ms) const { ms << mathMacro_->cell(idx_); }
126 void mathematica(MathematicaStream & ms) const { ms << mathMacro_->cell(idx_); }
128 void mathmlize(MathStream & ms) const { ms << mathMacro_->cell(idx_); }
130 void htmlize(HtmlStream & ms) const { ms << mathMacro_->cell(idx_); }
132 void octave(OctaveStream & os) const { os << mathMacro_->cell(idx_); }
134 void draw(PainterInfo &, int, int) const {
135 // This should never be invoked, since ArgumentProxy insets are linearized
139 size_t idx() const { return idx_; }
141 int kerning(BufferView const * bv) const
143 return displayCell(bv).kerning(bv);
148 Inset * clone() const
150 return new ArgumentProxy(*this);
153 MathMacro * mathMacro_;
161 /// Private implementation of MathMacro
162 class MathMacro::Private {
164 Private(Buffer * buf, docstring const & name)
165 : name_(name), displayMode_(DISPLAY_INIT),
166 expanded_(buf), definition_(buf), attachedArgsNum_(0),
167 optionals_(0), nextFoldMode_(true), macroBackup_(buf),
168 macro_(0), needsUpdate_(false), isUpdating_(false),
172 /// Update the pointers to our owner of all expanded macros.
173 /// This needs to be called every time a copy of the owner is created
175 void updateChildren(MathMacro * owner);
176 /// Recursively update the pointers of all expanded macros
177 /// appearing in the arguments of the current macro
178 void updateNestedChildren(MathMacro * owner, InsetMathNest * ni);
181 /// current display mode
182 DisplayMode displayMode_;
183 /// expanded macro with ArgumentProxies
185 /// macro definition with #1,#2,.. insets
186 MathData definition_;
187 /// number of arguments that were really attached
188 size_t attachedArgsNum_;
189 /// optional argument attached? (only in DISPLAY_NORMAL mode)
191 /// fold mode to be set in next metrics call?
193 /// if macro_ == true, then here is a copy of the macro
194 /// don't use it for locking
195 MacroData macroBackup_;
196 /// if macroNotFound_ == false, then here is a reference to the macro
197 /// this might invalidate after metrics was called
198 MacroData const * macro_;
200 mutable std::map<BufferView const *, bool> editing_;
202 std::string requires_;
203 /// update macro representation
207 /// maximal number of arguments the macro is greedy for
209 /// Level of nesting in macros (including this one)
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 & 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 /// The macro nesting can change display of insets. Change it locally.
297 Changer chg = make_change(mi.base.macro_nesting, d->nesting_);
299 if (displayMode() != MathMacro::DISPLAY_NORMAL
300 || d->editing_[mi.base.bv])
301 return InsetMath::addToMathRow(mrow, mi);
303 MathRow::Element e_beg(MathRow::BEG_MACRO);
305 mrow.push_back(e_beg);
308 bool has_contents = d->expanded_.addToMathRow(mrow, mi);
311 // if there was no contents and the array is editable, then we
312 // insert a grey box instead.
313 if (!has_contents && mi.base.macro_nesting == 1) {
314 // mathclass is unknown because it is irrelevant for spacing
315 MathRow::Element e(MathRow::BOX);
316 e.color = Color_mathmacroblend;
321 MathRow::Element e_end(MathRow::END_MACRO);
323 mrow.push_back(e_end);
329 Inset * MathMacro::clone() const
331 MathMacro * copy = new MathMacro(*this);
332 copy->d->needsUpdate_ = true;
333 //copy->d->expanded_.clear();
338 void MathMacro::normalize(NormalStream & os) const
340 os << "[macro " << name();
341 for (size_t i = 0; i < nargs(); ++i)
342 os << ' ' << cell(i);
347 MathMacro::DisplayMode MathMacro::displayMode() const
349 return d->displayMode_;
353 bool MathMacro::extraBraces() const
355 return d->displayMode_ == DISPLAY_NORMAL && arity() > 0;
359 docstring MathMacro::name() const
361 if (d->displayMode_ == DISPLAY_UNFOLDED)
362 return asString(cell(0));
368 docstring MathMacro::macroName() const
374 int MathMacro::nesting() const
380 void MathMacro::cursorPos(BufferView const & bv,
381 CursorSlice const & sl, bool boundary, int & x, int & y) const
383 // We may have 0 arguments, but InsetMathNest requires at least one.
385 InsetMathNest::cursorPos(bv, sl, boundary, x, y);
389 bool MathMacro::editMode(BufferView const * bv) const {
390 // find this in cursor trace
391 Cursor const & cur = bv->cursor();
392 for (size_t i = 0; i != cur.depth(); ++i)
393 if (&cur[i].inset() == this) {
394 // look if there is no other macro in edit mode above
396 for (; i != cur.depth(); ++i) {
397 InsetMath * im = cur[i].asInsetMath();
399 MathMacro const * macro = im->asMacro();
400 if (macro && macro->displayMode() == DISPLAY_NORMAL)
405 // ok, none found, I am the highest one
413 MacroData const * MathMacro::macro() const
419 bool MathMacro::editMetrics(BufferView const * bv) const
421 return d->editing_[bv];
425 void MathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
427 /// The macro nesting can change display of insets. Change it locally.
428 Changer chg = make_change(mi.base.macro_nesting, d->nesting_);
430 // set edit mode for which we will have calculated metrics. But only
431 d->editing_[mi.base.bv] = editMode(mi.base.bv);
433 // calculate new metrics according to display mode
434 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
435 Changer dummy = mi.base.changeFontSet("lyxtex");
436 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
437 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
438 Changer dummy = mi.base.changeFontSet("lyxtex");
439 cell(0).metrics(mi, dim);
441 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
442 dim.wid += bsdim.width() + 1;
443 dim.asc = max(bsdim.ascent(), dim.ascent());
444 dim.des = max(bsdim.descent(), dim.descent());
445 metricsMarkers(mi, dim);
446 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
447 && d->editing_[mi.base.bv]) {
448 // Macro will be edited in a old-style list mode here:
452 FontInfo labelFont = sane_font;
453 math_font_max_dim(labelFont, fontDim.asc, fontDim.des);
455 // get dimension of components of list view
457 nameDim.wid = mathed_string_width(mi.base.font, from_ascii("Macro \\") + name() + ": ");
458 nameDim.asc = fontDim.asc;
459 nameDim.des = fontDim.des;
462 argDim.wid = mathed_string_width(labelFont, from_ascii("#9: "));
463 argDim.asc = fontDim.asc;
464 argDim.des = fontDim.des;
467 d->definition_.metrics(mi, defDim);
470 dim.wid = nameDim.wid + defDim.wid;
471 dim.asc = max(nameDim.asc, defDim.asc);
472 dim.des = max(nameDim.des, defDim.des);
474 for (idx_type i = 0; i < nargs(); ++i) {
476 cell(i).metrics(mi, cdim);
477 dim.des += max(argDim.height(), cdim.height()) + 1;
478 dim.wid = max(dim.wid, argDim.wid + cdim.wid);
481 // make space for box and markers, 2 pixels
485 metricsMarkers2(mi, dim);
489 Changer dummy = (currentMode() == TEXT_MODE)
490 ? mi.base.font.changeShape(UP_SHAPE)
493 // calculate metrics, hoping that all cells are seen
495 d->expanded_.metrics(mi, dim);
497 // otherwise do a manual metrics call
498 CoordCache & coords = mi.base.bv->coordCache();
499 for (idx_type i = 0; i < nargs(); ++i) {
500 if (!coords.getArrays().hasDim(&cell(i))) {
502 cell(i).metrics(mi, tdim);
507 // calculate dimension with label while editing
508 if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX
509 && d->editing_[mi.base.bv]) {
510 FontInfo font = mi.base.font;
511 augmentFont(font, "lyxtex");
513 mathed_string_dim(font, name(), namedim);
515 dim.wid += 2 + namedim.wid + 2 + 2;
516 dim.asc = max(dim.asc, namedim.asc) + 2;
517 dim.des = max(dim.des, namedim.des) + 2;
519 dim.wid = max(1 + namedim.wid + 1, 2 + dim.wid + 2);
520 dim.asc += 1 + namedim.height() + 1;
527 int MathMacro::kerning(BufferView const * bv) const {
528 if (d->displayMode_ == DISPLAY_NORMAL && !d->editing_[bv])
529 return d->expanded_.kerning(bv);
535 void MathMacro::updateMacro(MacroContext const & mc)
538 d->macro_ = mc.get(name());
539 if (d->macro_ && d->macroBackup_ != *d->macro_) {
540 d->macroBackup_ = *d->macro_;
541 d->needsUpdate_ = true;
549 class MathMacro::UpdateLocker
552 explicit UpdateLocker(MathMacro & mm) : mac(mm)
554 mac.d->isUpdating_ = true;
556 ~UpdateLocker() { mac.d->isUpdating_ = false; }
560 /** Avoid wrong usage of UpdateLocker.
561 To avoid wrong usage:
562 UpdateLocker(...); // wrong
563 UpdateLocker locker(...); // right
565 #define UpdateLocker(x) unnamed_UpdateLocker;
566 // Tip gotten from Bobby Schmidt's column in C/C++ Users Journal
569 void MathMacro::updateRepresentation(Cursor * cur, MacroContext const & mc,
570 UpdateType utype, int nesting)
572 // block recursive calls (bug 8999)
576 UpdateLocker locker(*this);
582 // remember nesting level of this macro
583 d->nesting_ = nesting;
586 d->requires_ = d->macro_->requires();
589 // non-normal mode? We are done!
590 || (d->displayMode_ != DISPLAY_NORMAL))
593 d->needsUpdate_ = false;
595 // get default values of macro
596 vector<docstring> const & defaults = d->macro_->defaults();
598 // create MathMacroArgumentValue objects pointing to the cells of the macro
599 vector<MathData> values(nargs());
600 for (size_t i = 0; i < nargs(); ++i) {
601 ArgumentProxy * proxy;
602 if (i < defaults.size())
603 proxy = new ArgumentProxy(this, i, defaults[i]);
605 proxy = new ArgumentProxy(this, i);
606 values[i].insert(0, MathAtom(proxy));
608 // expanding macro with the values
609 // Only update the argument macros if anything was expanded, otherwise
610 // we would get an endless loop (bug 9140). UpdateLocker does not work
611 // in this case, since MacroData::expand() creates new MathMacro
612 // objects, so this would be a different recursion path than the one
613 // protected by UpdateLocker.
614 if (d->macro_->expand(values, d->expanded_)) {
615 if (utype == OutputUpdate && !d->expanded_.empty())
616 d->expanded_.updateMacros(cur, mc, utype, nesting);
618 // get definition for list edit mode
619 docstring const & display = d->macro_->display();
620 asArray(display.empty() ? d->macro_->definition() : display,
621 d->definition_, Parse::QUIET);
625 void MathMacro::draw(PainterInfo & pi, int x, int y) const
627 Dimension const dim = dimension(*pi.base.bv);
629 setPosCache(pi, x, y);
633 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
634 Changer dummy = pi.base.changeFontSet("lyxtex");
635 pi.pain.text(x, y, from_ascii("\\") + name(), pi.base.font);
636 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
637 Changer dummy = pi.base.changeFontSet("lyxtex");
638 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
639 x += mathed_string_width(pi.base.font, from_ascii("\\")) + 1;
640 cell(0).draw(pi, x, y);
641 drawMarkers(pi, expx, expy);
642 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
643 && d->editing_[pi.base.bv]) {
644 // Macro will be edited in a old-style list mode here:
646 CoordCache const & coords = pi.base.bv->coordCache();
647 FontInfo const & labelFont = sane_font;
649 // markers and box needs two pixels
652 // get maximal font height
654 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
657 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
658 pi.pain.text(x, y, label, labelFont);
659 x += mathed_string_width(labelFont, label);
662 d->definition_.draw(pi, x, y);
663 Dimension const & defDim = coords.getArrays().dim(&d->definition_);
664 y += max(fontDim.des, defDim.des);
667 docstring str = from_ascii("#9");
668 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
669 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
671 for (idx_type i = 0; i < nargs(); ++i) {
673 Dimension const & cdim = coords.getArrays().dim(&cell(i));
675 y += max(fontDim.asc, cdim.asc) + 1;
679 pi.pain.text(x, y, str, labelFont);
681 pi.pain.text(x, y, from_ascii(":"), labelFont);
685 cell(i).draw(pi, x, y);
688 y += max(fontDim.des, cdim.des);
691 pi.pain.rectangle(expx + 1, expy - dim.asc + 1, dim.wid - 3,
692 dim.height() - 2, Color_mathmacroframe);
693 drawMarkers2(pi, expx, expy);
695 bool drawBox = lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX;
696 Changer dummy = (currentMode() == TEXT_MODE)
697 ? pi.base.font.changeShape(UP_SHAPE)
701 for (size_t i = 0; i < nargs(); ++i)
702 cell(i).setXY(*pi.base.bv, x, y);
704 if (drawBox && d->editing_[pi.base.bv]) {
705 // draw header and rectangle around
706 FontInfo font = pi.base.font;
707 augmentFont(font, "lyxtex");
708 font.setSize(FONT_SIZE_TINY);
709 font.setColor(Color_mathmacrolabel);
711 mathed_string_dim(font, name(), namedim);
713 pi.pain.fillRectangle(x, y - dim.asc, dim.wid, 1 + namedim.height() + 1, Color_mathmacrobg);
714 pi.pain.text(x + 1, y - dim.asc + namedim.asc + 2, name(), font);
715 expx += (dim.wid - d->expanded_.dimension(*pi.base.bv).width()) / 2;
718 if (d->editing_[pi.base.bv]) {
719 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
720 d->expanded_.draw(pi, expx, expy);
721 pi.pain.leaveMonochromeMode();
724 pi.pain.rectangle(x, y - dim.asc, dim.wid,
725 dim.height(), Color_mathmacroframe);
727 d->expanded_.draw(pi, expx, expy);
730 drawMarkers(pi, x, y);
734 // edit mode changed?
735 if (d->editing_[pi.base.bv] != editMode(pi.base.bv))
736 pi.base.bv->cursor().screenUpdateFlags(Update::SinglePar);
740 void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
742 // We may have 0 arguments, but InsetMathNest requires at least one.
744 InsetMathNest::drawSelection(pi, x, y);
748 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode, int appetite)
750 if (d->displayMode_ != mode) {
751 // transfer name if changing from or to DISPLAY_UNFOLDED
752 if (mode == DISPLAY_UNFOLDED) {
754 asArray(d->name_, cell(0));
755 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
756 d->name_ = asString(cell(0));
760 d->displayMode_ = mode;
761 d->needsUpdate_ = true;
764 // the interactive init mode is non-greedy by default
766 d->appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
768 d->appetite_ = size_t(appetite);
772 MathMacro::DisplayMode MathMacro::computeDisplayMode() const
774 if (d->nextFoldMode_ == true && d->macro_ && !d->macro_->locked())
775 return DISPLAY_NORMAL;
777 return DISPLAY_UNFOLDED;
781 bool MathMacro::validName() const
783 docstring n = name();
788 // converting back and force doesn't swallow anything?
791 if (asString(ma) != n)
795 for (size_t i = 0; i<n.size(); ++i) {
796 if (!(n[i] >= 'a' && n[i] <= 'z')
797 && !(n[i] >= 'A' && n[i] <= 'Z')
806 size_t MathMacro::arity() const
808 if (d->displayMode_ == DISPLAY_NORMAL )
809 return cells_.size();
815 size_t MathMacro::optionals() const
817 return d->optionals_;
821 void MathMacro::setOptionals(int n)
823 if (n <= int(nargs()))
828 size_t MathMacro::appetite() const
834 InsetMath::mode_type MathMacro::currentMode() const
836 // User defined macros are always assumed to be mathmode macros.
837 // Only the global macros defined in lib/symbols may be textmode.
839 MacroData const * data = MacroTable::globalMacros().get(name());
840 bool textmode = data && data->symbol() && data->symbol()->extra == "textmode";
841 return textmode ? TEXT_MODE : MATH_MODE;
845 void MathMacro::validate(LaTeXFeatures & features) const
847 // Immediately after a document is loaded, in some cases the MacroData
848 // of the global macros defined in the lib/symbols file may still not
849 // be known to the macro machinery because it will be set only after
850 // the first call to updateMacros(). This is not a problem unless
851 // instant preview is on for math, in which case we will be missing
852 // the corresponding requirements.
853 // In this case, we get the required info from the global macro table.
854 if (!d->requires_.empty())
855 features.require(d->requires_);
856 else if (!d->macro_) {
857 // Update requires for known global macros.
858 MacroData const * data = MacroTable::globalMacros().get(name());
859 if (data && !data->requires().empty())
860 features.require(data->requires());
863 if (name() == "binom")
864 features.require("binom");
866 // validate the cells and the definition
867 if (displayMode() == DISPLAY_NORMAL) {
868 d->definition_.validate(features);
869 InsetMathNest::validate(features);
874 void MathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
876 cur.screenUpdateFlags(Update::SinglePar);
877 InsetMathNest::edit(cur, front, entry_from);
881 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
883 // We may have 0 arguments, but InsetMathNest requires at least one.
885 cur.screenUpdateFlags(Update::SinglePar);
886 return InsetMathNest::editXY(cur, x, y);
892 void MathMacro::removeArgument(Inset::pos_type pos) {
893 if (d->displayMode_ == DISPLAY_NORMAL) {
894 LASSERT(size_t(pos) < cells_.size(), return);
895 cells_.erase(cells_.begin() + pos);
896 if (size_t(pos) < d->attachedArgsNum_)
897 --d->attachedArgsNum_;
898 if (size_t(pos) < d->optionals_) {
902 d->needsUpdate_ = true;
907 void MathMacro::insertArgument(Inset::pos_type pos) {
908 if (d->displayMode_ == DISPLAY_NORMAL) {
909 LASSERT(size_t(pos) <= cells_.size(), return);
910 cells_.insert(cells_.begin() + pos, MathData());
911 if (size_t(pos) < d->attachedArgsNum_)
912 ++d->attachedArgsNum_;
913 if (size_t(pos) < d->optionals_)
916 d->needsUpdate_ = true;
921 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
923 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
926 // strip off empty cells, but not more than arity-attachedArgsNum_
929 for (i = cells_.size(); i > d->attachedArgsNum_; --i)
930 if (!cell(i - 1).empty()) break;
934 d->attachedArgsNum_ = 0;
935 d->expanded_ = MathData();
938 d->needsUpdate_ = true;
942 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
944 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
946 d->attachedArgsNum_ = args.size();
947 cells_.resize(arity);
948 d->expanded_ = MathData();
949 d->optionals_ = optionals;
951 d->needsUpdate_ = true;
955 bool MathMacro::idxFirst(Cursor & cur) const
957 cur.screenUpdateFlags(Update::SinglePar);
958 return InsetMathNest::idxFirst(cur);
962 bool MathMacro::idxLast(Cursor & cur) const
964 cur.screenUpdateFlags(Update::SinglePar);
965 return InsetMathNest::idxLast(cur);
969 bool MathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
971 if (d->displayMode_ == DISPLAY_UNFOLDED) {
972 docstring const & unfolded_name = name();
973 if (unfolded_name != d->name_) {
974 // The macro name was changed
975 Cursor inset_cursor = old;
976 int macroSlice = inset_cursor.find(this);
977 // returning true means the cursor is "now" invalid,
979 LASSERT(macroSlice != -1, return true);
980 inset_cursor.cutOff(macroSlice);
981 inset_cursor.recordUndoInset();
983 inset_cursor.cell().erase(inset_cursor.pos());
984 inset_cursor.cell().insert(inset_cursor.pos(),
985 createInsetMath(unfolded_name, cur.buffer()));
987 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
991 cur.screenUpdateFlags(Update::Force);
992 return InsetMathNest::notifyCursorLeaves(old, cur);
996 void MathMacro::fold(Cursor & cur)
998 if (!d->nextFoldMode_) {
999 d->nextFoldMode_ = true;
1000 cur.screenUpdateFlags(Update::SinglePar);
1005 void MathMacro::unfold(Cursor & cur)
1007 if (d->nextFoldMode_) {
1008 d->nextFoldMode_ = false;
1009 cur.screenUpdateFlags(Update::SinglePar);
1014 bool MathMacro::folded() const
1016 return d->nextFoldMode_;
1020 void MathMacro::write(WriteStream & os) const
1022 MacroData const * data = MacroTable::globalMacros().get(name());
1023 bool textmode_macro = data && data->symbol()
1024 && data->symbol()->extra == "textmode";
1025 bool needs_mathmode = data && (!data->symbol()
1026 || data->symbol()->extra != "textmode");
1028 MathEnsurer ensurer(os, needs_mathmode, true, textmode_macro);
1031 if (d->displayMode_ != DISPLAY_NORMAL) {
1032 os << "\\" << name();
1033 if (name().size() != 1 || isAlphaASCII(name()[0]))
1034 os.pendingSpace(true);
1039 // we should be ok to continue even if this fails.
1042 // We may already be in the argument of a macro
1043 bool const inside_macro = os.insideMacro();
1044 os.insideMacro(true);
1046 // Enclose in braces to avoid latex errors with xargs if we have
1047 // optional arguments and are in the optional argument of a macro
1048 if (d->optionals_ && inside_macro)
1051 // Always protect macros in a fragile environment
1055 os << "\\" << name();
1058 // Optional arguments:
1059 // First find last non-empty optional argument
1060 idx_type emptyOptFrom = 0;
1062 for (; i < cells_.size() && i < d->optionals_; ++i) {
1063 if (!cell(i).empty())
1064 emptyOptFrom = i + 1;
1067 // print out optionals
1068 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
1070 os << "[" << cell(i) << "]";
1073 // skip the tailing empty optionals
1076 // Print remaining arguments
1077 for (; i < cells_.size(); ++i) {
1078 if (cell(i).size() == 1
1079 && cell(i)[0].nucleus()->asCharInset()
1080 && isASCII(cell(i)[0].nucleus()->asCharInset()->getChar())) {
1085 os << "{" << cell(i) << "}";
1089 // Close the opened brace or add space if there was no argument
1090 if (d->optionals_ && inside_macro)
1093 os.pendingSpace(true);
1095 os.insideMacro(inside_macro);
1099 void MathMacro::maple(MapleStream & os) const
1101 lyx::maple(d->expanded_, os);
1105 void MathMacro::maxima(MaximaStream & os) const
1107 lyx::maxima(d->expanded_, os);
1111 void MathMacro::mathematica(MathematicaStream & os) const
1113 lyx::mathematica(d->expanded_, os);
1117 void MathMacro::mathmlize(MathStream & os) const
1119 // macro_ is 0 if this is an unknown macro
1120 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1122 docstring const xmlname = d->macro_->xmlname();
1123 if (!xmlname.empty()) {
1124 char const * type = d->macro_->MathMLtype();
1125 os << '<' << type << "> " << xmlname << " </"
1130 if (d->expanded_.empty()) {
1131 // this means that we do not recognize the macro
1132 throw MathExportException();
1138 void MathMacro::htmlize(HtmlStream & os) const
1140 // macro_ is 0 if this is an unknown macro
1141 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1143 docstring const xmlname = d->macro_->xmlname();
1144 if (!xmlname.empty()) {
1145 os << ' ' << xmlname << ' ';
1149 if (d->expanded_.empty()) {
1150 // this means that we do not recognize the macro
1151 throw MathExportException();
1157 void MathMacro::octave(OctaveStream & os) const
1159 lyx::octave(d->expanded_, os);
1163 void MathMacro::infoize(odocstream & os) const
1165 os << bformat(_("Macro: %1$s"), name());
1169 void MathMacro::infoize2(odocstream & os) const
1171 os << bformat(_("Macro: %1$s"), name());
1175 bool MathMacro::completionSupported(Cursor const & cur) const
1177 if (displayMode() != DISPLAY_UNFOLDED)
1178 return InsetMathNest::completionSupported(cur);
1180 return lyxrc.completion_popup_math
1181 && displayMode() == DISPLAY_UNFOLDED
1182 && cur.bv().cursor().pos() == int(name().size());
1186 bool MathMacro::inlineCompletionSupported(Cursor const & cur) const
1188 if (displayMode() != DISPLAY_UNFOLDED)
1189 return InsetMathNest::inlineCompletionSupported(cur);
1191 return lyxrc.completion_inline_math
1192 && displayMode() == DISPLAY_UNFOLDED
1193 && cur.bv().cursor().pos() == int(name().size());
1197 bool MathMacro::automaticInlineCompletion() const
1199 if (displayMode() != DISPLAY_UNFOLDED)
1200 return InsetMathNest::automaticInlineCompletion();
1202 return lyxrc.completion_inline_math;
1206 bool MathMacro::automaticPopupCompletion() const
1208 if (displayMode() != DISPLAY_UNFOLDED)
1209 return InsetMathNest::automaticPopupCompletion();
1211 return lyxrc.completion_popup_math;
1215 CompletionList const *
1216 MathMacro::createCompletionList(Cursor const & cur) const
1218 if (displayMode() != DISPLAY_UNFOLDED)
1219 return InsetMathNest::createCompletionList(cur);
1221 return new MathCompletionList(cur.bv().cursor());
1225 docstring MathMacro::completionPrefix(Cursor const & cur) const
1227 if (displayMode() != DISPLAY_UNFOLDED)
1228 return InsetMathNest::completionPrefix(cur);
1230 if (!completionSupported(cur))
1233 return "\\" + name();
1237 bool MathMacro::insertCompletion(Cursor & cur, docstring const & s,
1240 if (displayMode() != DISPLAY_UNFOLDED)
1241 return InsetMathNest::insertCompletion(cur, s, finished);
1243 if (!completionSupported(cur))
1246 // append completion
1247 docstring newName = name() + s;
1248 asArray(newName, cell(0));
1249 cur.bv().cursor().pos() = name().size();
1250 cur.screenUpdateFlags(Update::SinglePar);
1254 cur.bv().cursor().pop();
1255 ++cur.bv().cursor().pos();
1256 cur.screenUpdateFlags(Update::SinglePar);
1263 void MathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
1264 Dimension & dim) const
1266 if (displayMode() != DISPLAY_UNFOLDED)
1267 InsetMathNest::completionPosAndDim(cur, x, y, dim);
1269 // get inset dimensions
1270 dim = cur.bv().coordCache().insets().dim(this);
1271 // FIXME: these 3 are no accurate, but should depend on the font.
1272 // Now the popup jumps down if you enter a char with descent > 0.
1278 = cur.bv().coordCache().insets().xy(this);