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 marker_type marker(BufferView const *) const { return NO_MARKER; }
72 InsetCode lyxCode() const { return ARGUMENT_PROXY_CODE; }
73 /// The math data to use for display
74 MathData const & displayCell(BufferView const * bv) const
76 // handle default macro arguments
77 bool use_def_arg = !mathMacro_->editMetrics(bv)
78 && mathMacro_->cell(idx_).empty();
79 return use_def_arg ? def_ : mathMacro_->cell(idx_);
82 bool addToMathRow(MathRow & mrow, MetricsInfo & mi) const
84 // macro arguments are in macros
85 LATTEST(mathMacro_->nesting() > 0);
86 /// The macro nesting can change display of insets. Change it locally.
87 Changer chg = make_change(mi.base.macro_nesting,
88 mathMacro_->nesting() == 1 ? 0 : mathMacro_->nesting());
90 MathRow::Element e_beg(mi, MathRow::BEGIN);
92 e_beg.ar = &mathMacro_->cell(idx_);
93 mrow.push_back(e_beg);
95 mathMacro_->macro()->unlock();
96 bool has_contents = displayCell(mi.base.bv).addToMathRow(mrow, mi);
97 mathMacro_->macro()->lock();
99 // if there was no contents, and the contents is editable,
100 // then we insert a box instead.
101 if (!has_contents && mathMacro_->nesting() == 1) {
102 // mathclass is ord because it should be spaced as a normal atom
103 MathRow::Element e(mi, MathRow::BOX, MC_ORD);
104 e.color = Color_mathline;
109 MathRow::Element e_end(mi, MathRow::END);
111 e_end.ar = &mathMacro_->cell(idx_);
112 mrow.push_back(e_end);
117 void beforeMetrics() const
119 mathMacro_->macro()->unlock();
122 void afterMetrics() const
124 mathMacro_->macro()->lock();
127 void beforeDraw(PainterInfo const & pi) const
129 // if the macro is being edited, then the painter is in
131 if (mathMacro_->editMetrics(pi.base.bv))
132 pi.pain.leaveMonochromeMode();
135 void afterDraw(PainterInfo const & pi) const
137 if (mathMacro_->editMetrics(pi.base.bv))
138 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
141 void metrics(MetricsInfo &, Dimension &) const {
142 // This should never be invoked, since ArgumentProxy insets are linearized
146 void draw(PainterInfo &, int, int) const {
147 // This should never be invoked, since ArgumentProxy insets are linearized
151 int kerning(BufferView const * bv) const
153 return displayCell(bv).kerning(bv);
155 // write(), normalize(), infoize() and infoize2() are not needed since
156 // MathMacro uses the definition and not the expanded cells.
158 void maple(MapleStream & ms) const { ms << mathMacro_->cell(idx_); }
160 void maxima(MaximaStream & ms) const { ms << mathMacro_->cell(idx_); }
162 void mathematica(MathematicaStream & ms) const { ms << mathMacro_->cell(idx_); }
164 void mathmlize(MathStream & ms) const { ms << mathMacro_->cell(idx_); }
166 void htmlize(HtmlStream & ms) const { ms << mathMacro_->cell(idx_); }
168 void octave(OctaveStream & os) const { os << mathMacro_->cell(idx_); }
170 MathClass mathClass() const
173 // This can be refined once the pointer issues are fixed. I did not
174 // notice any immediate crash with the following code, but it is risky
176 //return mathMacro_->cell(idx_).mathClass();
181 Inset * clone() const
183 return new ArgumentProxy(*this);
186 MathMacro * mathMacro_;
194 /// Private implementation of MathMacro
195 class MathMacro::Private {
197 Private(Buffer * buf, docstring const & name)
198 : name_(name), displayMode_(DISPLAY_INIT),
199 expanded_(buf), definition_(buf), attachedArgsNum_(0),
200 optionals_(0), nextFoldMode_(true), macroBackup_(buf),
201 macro_(0), needsUpdate_(false), isUpdating_(false),
202 appetite_(9), nesting_(0)
205 /// Update the pointers to our owner of all expanded macros.
206 /// This needs to be called every time a copy of the owner is created
208 void updateChildren(MathMacro * owner);
209 /// Recursively update the pointers of all expanded macros
210 /// appearing in the arguments of the current macro
211 void updateNestedChildren(MathMacro * owner, InsetMathNest * ni);
214 /// current display mode
215 DisplayMode displayMode_;
216 /// expanded macro with ArgumentProxies
218 /// macro definition with #1,#2,.. insets
219 MathData definition_;
220 /// number of arguments that were really attached
221 size_t attachedArgsNum_;
222 /// optional argument attached? (only in DISPLAY_NORMAL mode)
224 /// fold mode to be set in next metrics call?
226 /// if macro_ == true, then here is a copy of the macro
227 /// don't use it for locking
228 MacroData macroBackup_;
229 /// if macroNotFound_ == false, then here is a reference to the macro
230 /// this might invalidate after metrics was called
231 MacroData const * macro_;
233 mutable std::map<BufferView const *, bool> editing_;
235 std::string requires_;
236 /// update macro representation
240 /// maximal number of arguments the macro is greedy for
242 /// Level of nesting in macros (including this one)
247 void MathMacro::Private::updateChildren(MathMacro * owner)
249 for (size_t i = 0; i < expanded_.size(); ++i) {
250 ArgumentProxy * p = dynamic_cast<ArgumentProxy *>(expanded_[i].nucleus());
254 InsetMathNest * ni = expanded_[i].nucleus()->asNestInset();
256 updateNestedChildren(owner, ni);
260 // The macro_ pointer is updated when MathData::metrics() is
261 // called. However, when instant preview is on or the macro is
262 // not on screen, MathData::metrics() is not called and we may
263 // have a dangling pointer. As a safety measure, when a macro
264 // is copied, always let macro_ point to the backup copy of the
265 // MacroData structure. This backup is updated every time the
266 // macro is changed, so it will not become stale.
267 macro_ = ¯oBackup_;
272 void MathMacro::Private::updateNestedChildren(MathMacro * owner, InsetMathNest * ni)
274 for (size_t i = 0; i < ni->nargs(); ++i) {
275 MathData & ar = ni->cell(i);
276 for (size_t j = 0; j < ar.size(); ++j) {
277 ArgumentProxy * ap = dynamic_cast
278 <ArgumentProxy *>(ar[j].nucleus());
280 MathMacro::Private * md = ap->owner()->d;
282 md->macro_ = &md->macroBackup_;
285 InsetMathNest * imn = ar[j].nucleus()->asNestInset();
287 updateNestedChildren(owner, imn);
293 MathMacro::MathMacro(Buffer * buf, docstring const & name)
294 : InsetMathNest(buf, 0), d(new Private(buf, name))
298 MathMacro::MathMacro(MathMacro const & that)
299 : InsetMathNest(that), d(new Private(*that.d))
301 setBuffer(*that.buffer_);
302 d->updateChildren(this);
306 MathMacro & MathMacro::operator=(MathMacro const & that)
310 InsetMathNest::operator=(that);
312 d->updateChildren(this);
317 MathMacro::~MathMacro()
323 bool MathMacro::addToMathRow(MathRow & mrow, MetricsInfo & mi) const
325 // set edit mode for which we will have calculated row.
326 // This is the same as what is done in metrics().
327 d->editing_[mi.base.bv] = editMode(mi.base.bv);
329 // For now we do not linearize in the following cases (can be improved)
330 // - display mode different from normal
331 // - editing with parameter list
332 // - editing with box around macro
333 if (displayMode() != MathMacro::DISPLAY_NORMAL
334 || (d->editing_[mi.base.bv] && lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST))
335 return InsetMath::addToMathRow(mrow, mi);
337 /// The macro nesting can change display of insets. Change it locally.
338 Changer chg = make_change(mi.base.macro_nesting, d->nesting_);
340 MathRow::Element e_beg(mi, MathRow::BEGIN);
342 e_beg.marker = (d->nesting_ == 1) ? marker(mi.base.bv) : NO_MARKER;
343 mrow.push_back(e_beg);
346 bool has_contents = d->expanded_.addToMathRow(mrow, mi);
349 // if there was no contents and the array is editable, then we
350 // insert a grey box instead.
351 if (!has_contents && mi.base.macro_nesting == 1) {
352 // mathclass is unknown because it is irrelevant for spacing
353 MathRow::Element e(mi, MathRow::BOX);
354 e.color = Color_mathmacroblend;
359 MathRow::Element e_end(mi, MathRow::END);
361 e_end.marker = (d->nesting_ == 1) ? marker(mi.base.bv) : NO_MARKER;
362 mrow.push_back(e_end);
367 void MathMacro::beforeMetrics() const
373 void MathMacro::afterMetrics() const
379 void MathMacro::beforeDraw(PainterInfo const & pi) const
381 if (d->editing_[pi.base.bv])
382 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
386 void MathMacro::afterDraw(PainterInfo const & pi) const
388 if (d->editing_[pi.base.bv])
389 pi.pain.leaveMonochromeMode();
393 Inset * MathMacro::clone() const
395 MathMacro * copy = new MathMacro(*this);
396 copy->d->needsUpdate_ = true;
397 //copy->d->expanded_.clear();
402 void MathMacro::normalize(NormalStream & os) const
404 os << "[macro " << name();
405 for (size_t i = 0; i < nargs(); ++i)
406 os << ' ' << cell(i);
411 MathMacro::DisplayMode MathMacro::displayMode() const
413 return d->displayMode_;
417 bool MathMacro::extraBraces() const
419 return d->displayMode_ == DISPLAY_NORMAL && arity() > 0;
423 docstring MathMacro::name() const
425 if (d->displayMode_ == DISPLAY_UNFOLDED)
426 return asString(cell(0));
432 docstring MathMacro::macroName() const
438 int MathMacro::nesting() const
444 void MathMacro::cursorPos(BufferView const & bv,
445 CursorSlice const & sl, bool boundary, int & x, int & y) const
447 // We may have 0 arguments, but InsetMathNest requires at least one.
449 InsetMathNest::cursorPos(bv, sl, boundary, x, y);
453 bool MathMacro::editMode(BufferView const * bv) const {
454 // find this in cursor trace
455 Cursor const & cur = bv->cursor();
456 for (size_t i = 0; i != cur.depth(); ++i)
457 if (&cur[i].inset() == this) {
458 // look if there is no other macro in edit mode above
460 for (; i != cur.depth(); ++i) {
461 InsetMath * im = cur[i].asInsetMath();
463 MathMacro const * macro = im->asMacro();
464 if (macro && macro->displayMode() == DISPLAY_NORMAL)
469 // ok, none found, I am the highest one
477 MacroData const * MathMacro::macro() const
483 bool MathMacro::editMetrics(BufferView const * bv) const
485 return d->editing_[bv];
489 InsetMath::marker_type MathMacro::marker(BufferView const * bv) const
494 switch (d->displayMode_) {
496 case DISPLAY_INTERACTIVE_INIT:
498 case DISPLAY_UNFOLDED:
501 switch (lyxrc.macro_edit_style) {
502 case LyXRC::MACRO_EDIT_INLINE:
504 case LyXRC::MACRO_EDIT_INLINE_BOX:
505 return d->editing_[bv] ? BOX_MARKER : MARKER2;
506 case LyXRC::MACRO_EDIT_LIST:
515 void MathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
517 /// The macro nesting can change display of insets. Change it locally.
518 Changer chg = make_change(mi.base.macro_nesting, d->nesting_);
520 // set edit mode for which we will have calculated metrics. But only
521 d->editing_[mi.base.bv] = editMode(mi.base.bv);
523 // calculate new metrics according to display mode
524 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
525 Changer dummy = mi.base.changeFontSet("lyxtex");
526 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
527 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
528 Changer dummy = mi.base.changeFontSet("lyxtex");
529 cell(0).metrics(mi, dim);
531 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
532 dim.wid += bsdim.width() + 1;
533 dim.asc = max(bsdim.ascent(), dim.ascent());
534 dim.des = max(bsdim.descent(), dim.descent());
535 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
536 && d->editing_[mi.base.bv]) {
537 // Macro will be edited in a old-style list mode here:
541 FontInfo labelFont = sane_font;
542 math_font_max_dim(labelFont, fontDim.asc, fontDim.des);
544 // get dimension of components of list view
546 nameDim.wid = mathed_string_width(mi.base.font, from_ascii("Macro \\") + name() + ": ");
547 nameDim.asc = fontDim.asc;
548 nameDim.des = fontDim.des;
551 argDim.wid = mathed_string_width(labelFont, from_ascii("#9: "));
552 argDim.asc = fontDim.asc;
553 argDim.des = fontDim.des;
556 d->definition_.metrics(mi, defDim);
559 dim.wid = nameDim.wid + defDim.wid;
560 dim.asc = max(nameDim.asc, defDim.asc);
561 dim.des = max(nameDim.des, defDim.des);
563 for (idx_type i = 0; i < nargs(); ++i) {
565 cell(i).metrics(mi, cdim);
566 dim.des += max(argDim.height(), cdim.height()) + 1;
567 dim.wid = max(dim.wid, argDim.wid + cdim.wid);
570 // make space for box and markers, 2 pixels
575 // We should not be here, since the macro is linearized in this case.
581 int MathMacro::kerning(BufferView const * bv) const {
582 if (d->displayMode_ == DISPLAY_NORMAL && !d->editing_[bv])
583 return d->expanded_.kerning(bv);
589 void MathMacro::updateMacro(MacroContext const & mc)
592 d->macro_ = mc.get(name());
593 if (d->macro_ && d->macroBackup_ != *d->macro_) {
594 d->macroBackup_ = *d->macro_;
595 d->needsUpdate_ = true;
603 class MathMacro::UpdateLocker
606 explicit UpdateLocker(MathMacro & mm) : mac(mm)
608 mac.d->isUpdating_ = true;
610 ~UpdateLocker() { mac.d->isUpdating_ = false; }
614 /** Avoid wrong usage of UpdateLocker.
615 To avoid wrong usage:
616 UpdateLocker(...); // wrong
617 UpdateLocker locker(...); // right
619 #define UpdateLocker(x) unnamed_UpdateLocker;
620 // Tip gotten from Bobby Schmidt's column in C/C++ Users Journal
623 void MathMacro::updateRepresentation(Cursor * cur, MacroContext const & mc,
624 UpdateType utype, int nesting)
626 // block recursive calls (bug 8999)
630 UpdateLocker locker(*this);
636 // remember nesting level of this macro
637 d->nesting_ = nesting;
640 d->requires_ = d->macro_->requires();
643 // non-normal mode? We are done!
644 || (d->displayMode_ != DISPLAY_NORMAL))
647 d->needsUpdate_ = false;
649 // get default values of macro
650 vector<docstring> const & defaults = d->macro_->defaults();
652 // create MathMacroArgumentValue objects pointing to the cells of the macro
653 vector<MathData> values(nargs());
654 for (size_t i = 0; i < nargs(); ++i) {
655 ArgumentProxy * proxy;
656 if (i < defaults.size())
657 proxy = new ArgumentProxy(this, i, defaults[i]);
659 proxy = new ArgumentProxy(this, i);
660 values[i].insert(0, MathAtom(proxy));
662 // expanding macro with the values
663 // Only update the argument macros if anything was expanded, otherwise
664 // we would get an endless loop (bug 9140). UpdateLocker does not work
665 // in this case, since MacroData::expand() creates new MathMacro
666 // objects, so this would be a different recursion path than the one
667 // protected by UpdateLocker.
668 if (d->macro_->expand(values, d->expanded_)) {
669 if (utype == OutputUpdate && !d->expanded_.empty())
670 d->expanded_.updateMacros(cur, mc, utype, nesting);
672 // get definition for list edit mode
673 docstring const & display = d->macro_->display();
674 asArray(display.empty() ? d->macro_->definition() : display,
675 d->definition_, Parse::QUIET | Parse::MACRODEF);
679 void MathMacro::draw(PainterInfo & pi, int x, int y) const
681 Dimension const dim = dimension(*pi.base.bv);
686 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
687 Changer dummy = pi.base.changeFontSet("lyxtex");
688 pi.pain.text(x, y, from_ascii("\\") + name(), pi.base.font);
689 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
690 Changer dummy = pi.base.changeFontSet("lyxtex");
691 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
692 x += mathed_string_width(pi.base.font, from_ascii("\\")) + 1;
693 cell(0).draw(pi, x, y);
694 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
695 && d->editing_[pi.base.bv]) {
696 // Macro will be edited in a old-style list mode here:
698 CoordCache const & coords = pi.base.bv->coordCache();
699 FontInfo const & labelFont = sane_font;
701 // box needs one pixel
704 // get maximal font height
706 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
709 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
710 pi.pain.text(x, y, label, labelFont);
711 x += mathed_string_width(labelFont, label);
714 d->definition_.draw(pi, x, y);
715 Dimension const & defDim = coords.getArrays().dim(&d->definition_);
716 y += max(fontDim.des, defDim.des);
719 docstring str = from_ascii("#9");
720 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
721 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
723 for (idx_type i = 0; i < nargs(); ++i) {
725 Dimension const & cdim = coords.getArrays().dim(&cell(i));
727 y += max(fontDim.asc, cdim.asc) + 1;
731 pi.pain.text(x, y, str, labelFont);
733 pi.pain.text(x, y, from_ascii(":"), labelFont);
737 cell(i).draw(pi, x, y);
740 y += max(fontDim.des, cdim.des);
743 pi.pain.rectangle(expx, expy - dim.asc + 1, dim.wid - 1,
744 dim.height() - 2, Color_mathmacroframe);
746 // We should not be here, since the macro is linearized in this case.
750 // edit mode changed?
751 if (d->editing_[pi.base.bv] != editMode(pi.base.bv))
752 pi.base.bv->cursor().screenUpdateFlags(Update::SinglePar);
756 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode, int appetite)
758 if (d->displayMode_ != mode) {
759 // transfer name if changing from or to DISPLAY_UNFOLDED
760 if (mode == DISPLAY_UNFOLDED) {
762 asArray(d->name_, cell(0));
763 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
764 d->name_ = asString(cell(0));
768 d->displayMode_ = mode;
769 d->needsUpdate_ = true;
772 // the interactive init mode is non-greedy by default
774 d->appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
776 d->appetite_ = size_t(appetite);
780 MathMacro::DisplayMode MathMacro::computeDisplayMode() const
782 if (d->nextFoldMode_ == true && d->macro_ && !d->macro_->locked())
783 return DISPLAY_NORMAL;
785 return DISPLAY_UNFOLDED;
789 bool MathMacro::validName() const
791 docstring n = name();
796 // converting back and force doesn't swallow anything?
799 if (asString(ma) != n)
803 for (size_t i = 0; i<n.size(); ++i) {
804 if (!(n[i] >= 'a' && n[i] <= 'z')
805 && !(n[i] >= 'A' && n[i] <= 'Z')
814 size_t MathMacro::arity() const
816 if (d->displayMode_ == DISPLAY_NORMAL )
817 return cells_.size();
823 size_t MathMacro::optionals() const
825 return d->optionals_;
829 void MathMacro::setOptionals(int n)
831 if (n <= int(nargs()))
836 size_t MathMacro::appetite() const
842 MathClass MathMacro::mathClass() const
844 // This can be just a heuristic, since it is only considered for display
845 // when the macro is not linearised. Therefore it affects:
846 // * The spacing of the inset while being edited,
847 // * Intelligent splitting
848 // * Cursor word movement (Ctrl-Arrow).
849 if (MacroData const * m = macroBackup()) {
850 // If it is a global macro and is defined explicitly
852 MathClass mc = string_to_class(m->symbol()->extra);
853 if (mc != MC_UNKNOWN)
857 // Otherwise guess from the expanded macro
858 return d->expanded_.mathClass();
862 InsetMath::mode_type MathMacro::currentMode() const
864 // There is no way to guess the mode of user defined macros, so they are
865 // always assumed to be mathmode. Only the global macros defined in
866 // lib/symbols may be textmode.
867 mode_type mode = modeToEnsure();
868 return (mode == UNDECIDED_MODE) ? MATH_MODE : mode;
872 InsetMath::mode_type MathMacro::modeToEnsure() const
874 // User defined macros can be either text mode or math mode for output and
875 // display. There is no way to guess. For global macros defined in
876 // lib/symbols, we ensure textmode if flagged as such, otherwise we ensure
878 if (MacroData const * m = macroBackup())
880 return (m->symbol()->extra == "textmode") ? TEXT_MODE : MATH_MODE;
881 return UNDECIDED_MODE;
885 MacroData const * MathMacro::macroBackup() const
888 return &d->macroBackup_;
889 if (MacroData const * data = MacroTable::globalMacros().get(name()))
895 void MathMacro::validate(LaTeXFeatures & features) const
897 // Immediately after a document is loaded, in some cases the MacroData
898 // of the global macros defined in the lib/symbols file may still not
899 // be known to the macro machinery because it will be set only after
900 // the first call to updateMacros(). This is not a problem unless
901 // instant preview is on for math, in which case we will be missing
902 // the corresponding requirements.
903 // In this case, we get the required info from the global macro table.
904 if (!d->requires_.empty())
905 features.require(d->requires_);
906 else if (!d->macro_) {
907 // Update requires for known global macros.
908 MacroData const * data = MacroTable::globalMacros().get(name());
909 if (data && !data->requires().empty())
910 features.require(data->requires());
913 if (name() == "binom")
914 features.require("binom");
916 // validate the cells and the definition
917 if (displayMode() == DISPLAY_NORMAL) {
918 d->definition_.validate(features);
919 InsetMathNest::validate(features);
924 void MathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
926 cur.screenUpdateFlags(Update::SinglePar);
927 InsetMathNest::edit(cur, front, entry_from);
931 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
933 // We may have 0 arguments, but InsetMathNest requires at least one.
935 cur.screenUpdateFlags(Update::SinglePar);
936 return InsetMathNest::editXY(cur, x, y);
942 void MathMacro::removeArgument(Inset::pos_type pos) {
943 if (d->displayMode_ == DISPLAY_NORMAL) {
944 LASSERT(size_t(pos) < cells_.size(), return);
945 cells_.erase(cells_.begin() + pos);
946 if (size_t(pos) < d->attachedArgsNum_)
947 --d->attachedArgsNum_;
948 if (size_t(pos) < d->optionals_) {
952 d->needsUpdate_ = true;
957 void MathMacro::insertArgument(Inset::pos_type pos) {
958 if (d->displayMode_ == DISPLAY_NORMAL) {
959 LASSERT(size_t(pos) <= cells_.size(), return);
960 cells_.insert(cells_.begin() + pos, MathData());
961 if (size_t(pos) < d->attachedArgsNum_)
962 ++d->attachedArgsNum_;
963 if (size_t(pos) < d->optionals_)
966 d->needsUpdate_ = true;
971 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
973 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
976 // strip off empty cells, but not more than arity-attachedArgsNum_
979 for (i = cells_.size(); i > d->attachedArgsNum_; --i)
980 if (!cell(i - 1).empty()) break;
984 d->attachedArgsNum_ = 0;
985 d->expanded_ = MathData();
988 d->needsUpdate_ = true;
992 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
994 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
996 d->attachedArgsNum_ = args.size();
997 cells_.resize(arity);
998 d->expanded_ = MathData();
999 d->optionals_ = optionals;
1001 d->needsUpdate_ = true;
1005 bool MathMacro::idxFirst(Cursor & cur) const
1007 cur.screenUpdateFlags(Update::SinglePar);
1008 return InsetMathNest::idxFirst(cur);
1012 bool MathMacro::idxLast(Cursor & cur) const
1014 cur.screenUpdateFlags(Update::SinglePar);
1015 return InsetMathNest::idxLast(cur);
1019 bool MathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
1021 if (d->displayMode_ == DISPLAY_UNFOLDED) {
1022 docstring const & unfolded_name = name();
1023 if (unfolded_name != d->name_) {
1024 // The macro name was changed
1025 Cursor inset_cursor = old;
1026 int macroSlice = inset_cursor.find(this);
1027 // returning true means the cursor is "now" invalid,
1029 LASSERT(macroSlice != -1, return true);
1030 inset_cursor.cutOff(macroSlice);
1031 inset_cursor.recordUndoInset();
1033 inset_cursor.cell().erase(inset_cursor.pos());
1034 inset_cursor.cell().insert(inset_cursor.pos(),
1035 createInsetMath(unfolded_name, cur.buffer()));
1037 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
1041 cur.screenUpdateFlags(Update::Force);
1042 return InsetMathNest::notifyCursorLeaves(old, cur);
1046 void MathMacro::fold(Cursor & cur)
1048 if (!d->nextFoldMode_) {
1049 d->nextFoldMode_ = true;
1050 cur.screenUpdateFlags(Update::SinglePar);
1055 void MathMacro::unfold(Cursor & cur)
1057 if (d->nextFoldMode_) {
1058 d->nextFoldMode_ = false;
1059 cur.screenUpdateFlags(Update::SinglePar);
1064 bool MathMacro::folded() const
1066 return d->nextFoldMode_;
1070 void MathMacro::write(WriteStream & os) const
1072 mode_type mode = modeToEnsure();
1073 bool textmode_macro = mode == TEXT_MODE;
1074 bool needs_mathmode = mode == MATH_MODE;
1075 MathEnsurer ensurer(os, needs_mathmode, true, textmode_macro);
1078 if (d->displayMode_ != DISPLAY_NORMAL) {
1079 os << "\\" << name();
1080 if (name().size() != 1 || isAlphaASCII(name()[0]))
1081 os.pendingSpace(true);
1086 // we should be ok to continue even if this fails.
1089 // We may already be in the argument of a macro
1090 bool const inside_macro = os.insideMacro();
1091 os.insideMacro(true);
1093 // Enclose in braces to avoid latex errors with xargs if we have
1094 // optional arguments and are in the optional argument of a macro
1095 if (d->optionals_ && inside_macro)
1098 // Always protect macros in a fragile environment
1102 os << "\\" << name();
1105 // Optional arguments:
1106 // First find last non-empty optional argument
1107 idx_type emptyOptFrom = 0;
1109 for (; i < cells_.size() && i < d->optionals_; ++i) {
1110 if (!cell(i).empty())
1111 emptyOptFrom = i + 1;
1114 // print out optionals
1115 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
1117 os << "[" << cell(i) << "]";
1120 // skip the tailing empty optionals
1123 // Print remaining arguments
1124 for (; i < cells_.size(); ++i) {
1125 if (cell(i).size() == 1
1126 && cell(i)[0].nucleus()->asCharInset()
1127 && isASCII(cell(i)[0].nucleus()->asCharInset()->getChar())) {
1132 os << "{" << cell(i) << "}";
1136 // Close the opened brace or add space if there was no argument
1137 if (d->optionals_ && inside_macro)
1140 os.pendingSpace(true);
1142 os.insideMacro(inside_macro);
1146 void MathMacro::maple(MapleStream & os) const
1148 lyx::maple(d->expanded_, os);
1152 void MathMacro::maxima(MaximaStream & os) const
1154 lyx::maxima(d->expanded_, os);
1158 void MathMacro::mathematica(MathematicaStream & os) const
1160 lyx::mathematica(d->expanded_, os);
1164 void MathMacro::mathmlize(MathStream & os) const
1166 // macro_ is 0 if this is an unknown macro
1167 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1169 docstring const xmlname = d->macro_->xmlname();
1170 if (!xmlname.empty()) {
1171 char const * type = d->macro_->MathMLtype();
1172 os << '<' << type << "> " << xmlname << " </"
1177 if (d->expanded_.empty()) {
1178 // this means that we do not recognize the macro
1179 throw MathExportException();
1185 void MathMacro::htmlize(HtmlStream & os) const
1187 // macro_ is 0 if this is an unknown macro
1188 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1190 docstring const xmlname = d->macro_->xmlname();
1191 if (!xmlname.empty()) {
1192 os << ' ' << xmlname << ' ';
1196 if (d->expanded_.empty()) {
1197 // this means that we do not recognize the macro
1198 throw MathExportException();
1204 void MathMacro::octave(OctaveStream & os) const
1206 lyx::octave(d->expanded_, os);
1210 void MathMacro::infoize(odocstream & os) const
1212 os << bformat(_("Macro: %1$s"), name());
1216 void MathMacro::infoize2(odocstream & os) const
1218 os << bformat(_("Macro: %1$s"), name());
1222 bool MathMacro::completionSupported(Cursor const & cur) const
1224 if (displayMode() != DISPLAY_UNFOLDED)
1225 return InsetMathNest::completionSupported(cur);
1227 return lyxrc.completion_popup_math
1228 && displayMode() == DISPLAY_UNFOLDED
1229 && cur.bv().cursor().pos() == int(name().size());
1233 bool MathMacro::inlineCompletionSupported(Cursor const & cur) const
1235 if (displayMode() != DISPLAY_UNFOLDED)
1236 return InsetMathNest::inlineCompletionSupported(cur);
1238 return lyxrc.completion_inline_math
1239 && displayMode() == DISPLAY_UNFOLDED
1240 && cur.bv().cursor().pos() == int(name().size());
1244 bool MathMacro::automaticInlineCompletion() const
1246 if (displayMode() != DISPLAY_UNFOLDED)
1247 return InsetMathNest::automaticInlineCompletion();
1249 return lyxrc.completion_inline_math;
1253 bool MathMacro::automaticPopupCompletion() const
1255 if (displayMode() != DISPLAY_UNFOLDED)
1256 return InsetMathNest::automaticPopupCompletion();
1258 return lyxrc.completion_popup_math;
1262 CompletionList const *
1263 MathMacro::createCompletionList(Cursor const & cur) const
1265 if (displayMode() != DISPLAY_UNFOLDED)
1266 return InsetMathNest::createCompletionList(cur);
1268 return new MathCompletionList(cur.bv().cursor());
1272 docstring MathMacro::completionPrefix(Cursor const & cur) const
1274 if (displayMode() != DISPLAY_UNFOLDED)
1275 return InsetMathNest::completionPrefix(cur);
1277 if (!completionSupported(cur))
1280 return "\\" + name();
1284 bool MathMacro::insertCompletion(Cursor & cur, docstring const & s,
1287 if (displayMode() != DISPLAY_UNFOLDED)
1288 return InsetMathNest::insertCompletion(cur, s, finished);
1290 if (!completionSupported(cur))
1293 // append completion
1294 docstring newName = name() + s;
1295 asArray(newName, cell(0));
1296 cur.bv().cursor().pos() = name().size();
1297 cur.screenUpdateFlags(Update::SinglePar);
1301 cur.bv().cursor().pop();
1302 ++cur.bv().cursor().pos();
1303 cur.screenUpdateFlags(Update::SinglePar);
1310 void MathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
1311 Dimension & dim) const
1313 if (displayMode() != DISPLAY_UNFOLDED)
1314 InsetMathNest::completionPosAndDim(cur, x, y, dim);
1316 // get inset dimensions
1317 dim = cur.bv().coordCache().insets().dim(this);
1318 // FIXME: these 3 are no accurate, but should depend on the font.
1319 // Now the popup jumps down if you enter a char with descent > 0.
1325 = cur.bv().coordCache().insets().xy(this);