2 * \file MathMacroTemplate.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
14 #include "MathMacroTemplate.h"
16 #include "InsetMathBrace.h"
17 #include "InsetMathChar.h"
18 #include "InsetMathHull.h"
19 #include "InsetMathSqrt.h"
20 #include "MathMacro.h"
21 #include "MathMacroArgument.h"
22 #include "MathStream.h"
23 #include "MathParser.h"
24 #include "MathSupport.h"
25 #include "MathMacroArgument.h"
28 #include "BufferView.h"
31 #include "DispatchResult.h"
32 #include "DocIterator.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
35 #include "LaTeXFeatures.h"
37 #include "MetricsInfo.h"
38 #include "TocBackend.h"
40 #include "frontends/Painter.h"
42 #include "insets/RenderPreview.h"
44 #include "support/lassert.h"
45 #include "support/convert.h"
46 #include "support/debug.h"
47 #include "support/gettext.h"
48 #include "support/docstream.h"
49 #include "support/lstrings.h"
58 using support::bformat;
60 //////////////////////////////////////////////////////////////////////
62 class InsetLabelBox : public InsetMathNest {
65 InsetLabelBox(Buffer * buf, MathAtom const & atom, docstring label,
66 MathMacroTemplate const & parent, bool frame = false);
67 InsetLabelBox(Buffer * buf, docstring label, MathMacroTemplate const & parent,
70 void metrics(MetricsInfo & mi, Dimension & dim) const;
72 void draw(PainterInfo &, int x, int y) const;
76 MathMacroTemplate const & parent_;
78 Inset * clone() const;
80 docstring const label_;
86 InsetLabelBox::InsetLabelBox(Buffer * buf, MathAtom const & atom, docstring label,
87 MathMacroTemplate const & parent, bool frame)
88 : InsetMathNest(buf, 1), parent_(parent), label_(label), frame_(frame)
90 cell(0).insert(0, atom);
94 InsetLabelBox::InsetLabelBox(Buffer * buf, docstring label,
95 MathMacroTemplate const & parent, bool frame)
96 : InsetMathNest(buf, 1), parent_(parent), label_(label), frame_(frame)
101 Inset * InsetLabelBox::clone() const
103 return new InsetLabelBox(*this);
107 void InsetLabelBox::metrics(MetricsInfo & mi, Dimension & dim) const
110 cell(0).metrics(mi, dim);
119 // adjust to common height in main metrics phase
120 if (!parent_.premetrics()) {
121 dim.asc = max(dim.asc, parent_.commonLabelBoxAscent());
122 dim.des = max(dim.des, parent_.commonLabelBoxDescent());
126 if (parent_.editing(mi.base.bv) && label_.length() > 0) {
128 FontInfo font = sane_font;
129 font.setSize(FONT_SIZE_TINY);
130 font.setColor(Color_mathmacrolabel);
132 // make space for label and box
133 int lwid = mathed_string_width(font, label_);
136 math_font_max_dim(font, maxasc, maxdes);
138 dim.wid = max(dim.wid, lwid + 2);
140 // space for the label
141 if (!parent_.premetrics())
142 dim.des += maxasc + maxdes + 1;
147 void InsetLabelBox::draw(PainterInfo & pi, int x, int y) const
149 Dimension const dim = dimension(*pi.base.bv);
150 Dimension const cdim = cell(0).dimension(*pi.base.bv);
153 cell(0).draw(pi, x + (dim.wid - cdim.wid) / 2, y);
156 if (parent_.editing(pi.base.bv) && label_.length() > 0) {
158 FontInfo font = sane_font;
159 font.setSize(FONT_SIZE_TINY);
160 font.setColor(Color_mathmacrolabel);
162 // make space for label and box
163 int lwid = mathed_string_width(font, label_);
166 math_font_max_dim(font, maxasc, maxdes);
169 pi.pain.text(x + (dim.wid - lwid) / 2, y + dim.des - maxdes, label_, font);
171 pi.pain.text(x, y + dim.des - maxdes, label_, font);
175 int boxHeight = parent_.commonLabelBoxAscent() + parent_.commonLabelBoxDescent();
177 pi.pain.rectangle(x + 1, y - dim.ascent() + 1,
178 dim.wid - 2, boxHeight - 2,
184 //////////////////////////////////////////////////////////////////////
186 class DisplayLabelBox : public InsetLabelBox {
189 DisplayLabelBox(Buffer * buf, MathAtom const & atom, docstring label,
190 MathMacroTemplate const & parent);
193 void metrics(MetricsInfo & mi, Dimension & dim) const;
195 void draw(PainterInfo &, int x, int y) const;
199 Inset * clone() const;
203 DisplayLabelBox::DisplayLabelBox(Buffer * buf, MathAtom const & atom,
205 MathMacroTemplate const & parent)
206 : InsetLabelBox(buf, atom, label, parent, true)
212 Inset * DisplayLabelBox::clone() const
214 return new DisplayLabelBox(*this);
218 void DisplayLabelBox::metrics(MetricsInfo & mi, Dimension & dim) const
220 InsetLabelBox::metrics(mi, dim);
221 if (!parent_.editing(mi.base.bv)
222 && parent_.cell(parent_.displayIdx()).empty()) {
230 void DisplayLabelBox::draw(PainterInfo & pi, int x, int y) const
232 if (parent_.editing(pi.base.bv)
233 || !parent_.cell(parent_.displayIdx()).empty()) {
234 InsetLabelBox::draw(pi, x, y);
236 bool enabled = pi.pain.isDrawingEnabled();
237 pi.pain.setDrawingEnabled(false);
238 InsetLabelBox::draw(pi, x, y);
239 pi.pain.setDrawingEnabled(enabled);
244 //////////////////////////////////////////////////////////////////////
246 class InsetMathWrapper : public InsetMath {
249 InsetMathWrapper(MathData const * value) : value_(value) {}
251 void metrics(MetricsInfo & mi, Dimension & dim) const;
253 void draw(PainterInfo &, int x, int y) const;
257 Inset * clone() const;
259 MathData const * value_;
263 Inset * InsetMathWrapper::clone() const
265 return new InsetMathWrapper(*this);
269 void InsetMathWrapper::metrics(MetricsInfo & mi, Dimension & dim) const
271 value_->metrics(mi, dim);
275 void InsetMathWrapper::draw(PainterInfo & pi, int x, int y) const
277 value_->draw(pi, x, y);
281 ///////////////////////////////////////////////////////////////////////
282 class InsetColoredCell : public InsetMathNest {
285 InsetColoredCell(Buffer * buf, ColorCode min, ColorCode max);
287 InsetColoredCell(Buffer * buf, ColorCode min, ColorCode max, MathAtom const & atom);
289 void draw(PainterInfo &, int x, int y) const;
291 void metrics(MetricsInfo & mi, Dimension & dim) const;
295 Inset * clone() const;
303 InsetColoredCell::InsetColoredCell(Buffer * buf, ColorCode min, ColorCode max)
304 : InsetMathNest(buf, 1), min_(min), max_(max)
309 InsetColoredCell::InsetColoredCell(Buffer * buf, ColorCode min, ColorCode max, MathAtom const & atom)
310 : InsetMathNest(buf, 1), min_(min), max_(max)
312 cell(0).insert(0, atom);
316 Inset * InsetColoredCell::clone() const
318 return new InsetColoredCell(*this);
322 void InsetColoredCell::metrics(MetricsInfo & mi, Dimension & dim) const
324 cell(0).metrics(mi, dim);
328 void InsetColoredCell::draw(PainterInfo & pi, int x, int y) const
330 pi.pain.enterMonochromeMode(min_, max_);
331 cell(0).draw(pi, x, y);
332 pi.pain.leaveMonochromeMode();
336 ///////////////////////////////////////////////////////////////////////
338 class InsetNameWrapper : public InsetMathWrapper {
341 InsetNameWrapper(MathData const * value, MathMacroTemplate const & parent);
343 void metrics(MetricsInfo & mi, Dimension & dim) const;
345 void draw(PainterInfo &, int x, int y) const;
349 MathMacroTemplate const & parent_;
351 Inset * clone() const;
355 InsetNameWrapper::InsetNameWrapper(MathData const * value,
356 MathMacroTemplate const & parent)
357 : InsetMathWrapper(value), parent_(parent)
362 Inset * InsetNameWrapper::clone() const
364 return new InsetNameWrapper(*this);
368 void InsetNameWrapper::metrics(MetricsInfo & mi, Dimension & dim) const
370 Changer dummy = mi.base.changeFontSet("textit");
371 InsetMathWrapper::metrics(mi, dim);
372 dim.wid += mathed_string_width(mi.base.font, from_ascii("\\"));
376 void InsetNameWrapper::draw(PainterInfo & pi, int x, int y) const
378 ColorCode const color = parent_.validMacro() ? Color_latex : Color_error;
380 Changer dummy = pi.base.changeFontSet("textit");
381 Changer dummy2 = pi.base.font.changeColor(color);
384 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
385 x += mathed_string_width(pi.base.font, from_ascii("\\"));
388 InsetMathWrapper::draw(pi, x, y);
392 ///////////////////////////////////////////////////////////////////////
395 MathMacroTemplate::MathMacroTemplate(Buffer * buf)
396 : InsetMathNest(buf, 3), numargs_(0), argsInLook_(0), optionals_(0),
397 type_(MacroTypeNewcommand), redefinition_(false), lookOutdated_(true),
398 premetrics_(false), labelBoxAscent_(0), labelBoxDescent_(0)
404 MathMacroTemplate::MathMacroTemplate(Buffer * buf, docstring const & name, int numargs,
405 int optionals, MacroType type, vector<MathData> const & optionalValues,
406 MathData const & def, MathData const & display)
407 : InsetMathNest(buf, optionals + 3), numargs_(numargs), argsInLook_(numargs),
408 optionals_(optionals), optionalValues_(optionalValues),
409 type_(type), redefinition_(false), lookOutdated_(true),
410 premetrics_(false), labelBoxAscent_(0), labelBoxDescent_(0)
415 lyxerr << "MathMacroTemplate::MathMacroTemplate: wrong # of arguments: "
418 asArray(name, cell(0));
419 optionalValues_.resize(9);
420 for (int i = 0; i < optionals_; ++i)
421 cell(optIdx(i)) = optionalValues_[i];
422 cell(defIdx()) = def;
423 cell(displayIdx()) = display;
429 bool MathMacroTemplate::fromString(docstring const & str)
431 MathData ar(buffer_);
432 mathed_parse_cell(ar, str, Parse::NORMAL);
433 if (ar.size() != 1 || !ar[0]->asMacroTemplate()) {
434 lyxerr << "Cannot read macro from '" << ar << "'" << endl;
435 asArray(from_ascii("invalidmacro"), cell(0));
436 // The macro template does not make sense after this.
439 operator=( *(ar[0]->asMacroTemplate()) );
446 Inset * MathMacroTemplate::clone() const
448 MathMacroTemplate * inset = new MathMacroTemplate(*this);
449 // the parent pointers of the proxy insets above will point to
450 // to the old template. Hence, the look must be updated.
456 docstring MathMacroTemplate::name() const
458 return asString(cell(0));
462 void MathMacroTemplate::updateToContext(MacroContext const & mc)
464 redefinition_ = mc.get(name()) != 0;
468 void MathMacroTemplate::updateLook() const
470 lookOutdated_ = true;
474 void MathMacroTemplate::createLook(int args) const
480 look_.push_back(MathAtom(
481 new InsetLabelBox(buffer_, _("Name"), *this, false)));
482 MathData & nameData = look_[look_.size() - 1].nucleus()->cell(0);
483 nameData.push_back(MathAtom(new InsetNameWrapper(&cell(0), *this)));
487 if (optionals_ > 0) {
488 look_.push_back(MathAtom(
489 new InsetLabelBox(buffer_, _("optional"), *this, false)));
491 MathData * optData = &look_[look_.size() - 1].nucleus()->cell(0);
492 for (; i < optionals_; ++i) {
493 // color it light grey, if it is to be removed when the cursor leaves
494 if (i == argsInLook_) {
495 optData->push_back(MathAtom(
496 new InsetColoredCell(buffer_, Color_mathbg, Color_mathmacrooldarg)));
497 optData = &(*optData)[optData->size() - 1].nucleus()->cell(0);
500 optData->push_back(MathAtom(new InsetMathChar('[')));
501 optData->push_back(MathAtom(new InsetMathWrapper(&cell(1 + i))));
502 optData->push_back(MathAtom(new InsetMathChar(']')));
507 for (; i < numargs_; ++i) {
509 arg.push_back(MathAtom(new MathMacroArgument(i + 1)));
510 if (i >= argsInLook_) {
511 look_.push_back(MathAtom(new InsetColoredCell(buffer_,
512 Color_mathbg, Color_mathmacrooldarg,
513 MathAtom(new InsetMathBrace(arg)))));
515 look_.push_back(MathAtom(new InsetMathBrace(arg)));
517 for (; i < argsInLook_; ++i) {
519 arg.push_back(MathAtom(new MathMacroArgument(i + 1)));
520 look_.push_back(MathAtom(new InsetColoredCell(buffer_,
521 Color_mathbg, Color_mathmacronewarg,
522 MathAtom(new InsetMathBrace(arg)))));
526 look_.push_back(MathAtom(new InsetMathChar(':')));
527 look_.push_back(MathAtom(new InsetMathChar('=')));
530 look_.push_back(MathAtom(
531 new InsetLabelBox(buffer_, MathAtom(
532 new InsetMathWrapper(&cell(defIdx()))), _("TeX"), *this, true)));
535 look_.push_back(MathAtom(
536 new DisplayLabelBox(buffer_, MathAtom(
537 new InsetMathWrapper(&cell(displayIdx()))), _("LyX"), *this)));
541 void MathMacroTemplate::metrics(MetricsInfo & mi, Dimension & dim) const
543 Changer dummy1 = mi.base.changeFontSet("mathnormal");
544 Changer dummy2 = mi.base.font.changeStyle(LM_ST_TEXT);
547 MacroData const * macro = 0;
549 macro = mi.macrocontext.get(name());
552 int argsInDef = maxArgumentInDefinition();
553 if (lookOutdated_ || argsInDef != argsInLook_) {
554 lookOutdated_ = false;
555 createLook(argsInDef);
558 /// metrics for inset contents
562 // first phase, premetric:
564 look_.metrics(mi, dim);
565 labelBoxAscent_ = dim.asc;
566 labelBoxDescent_ = dim.des;
568 // second phase, main metric:
570 look_.metrics(mi, dim);
581 void MathMacroTemplate::draw(PainterInfo & pi, int x, int y) const
583 // FIXME: Calling Changer on the same object repeatedly is inefficient.
584 Changer dummy0 = pi.base.font.changeColor(Color_math);
585 Changer dummy1 = pi.base.changeFontSet("mathnormal");
586 Changer dummy2 = pi.base.font.changeStyle(LM_ST_TEXT);
588 Dimension const dim = dimension(*pi.base.bv);
591 int const a = y - dim.asc + 1;
592 int const w = dim.wid - 2;
593 int const h = dim.height() - 2;
594 pi.pain.rectangle(x + 1, a, w, h, Color_mathframe);
596 // just to be sure: set some dummy values for coord cache
597 for (idx_type i = 0; i < nargs(); ++i)
598 cell(i).setXY(*pi.base.bv, x, y);
601 look_.draw(pi, x + 3, y);
605 void MathMacroTemplate::edit(Cursor & cur, bool front, EntryDirection entry_from)
608 cur.screenUpdateFlags(Update::SinglePar);
609 InsetMathNest::edit(cur, front, entry_from);
613 bool MathMacroTemplate::notifyCursorLeaves(Cursor const & old, Cursor & cur)
615 unsigned int const nargs_before = nargs();
616 commitEditChanges(cur, old);
618 cur.screenUpdateFlags(Update::Force);
619 // If we have removed a cell, we might have invalidated the cursor
620 return InsetMathNest::notifyCursorLeaves(old, cur)
621 || nargs() < nargs_before;
625 void MathMacroTemplate::removeArguments(Cursor & cur,
626 DocIterator const & /*inset_pos*/, int from, int to)
628 DocIterator it = doc_iterator_begin(&buffer(), this);
629 for (; it; it.forwardChar()) {
632 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
634 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
635 int n = arg->number() - 1;
636 if (from <= n && n <= to) {
637 int cellSlice = cur.find(it.cell());
638 if (cellSlice != -1 && cur[cellSlice].pos() > it.pos())
639 --cur[cellSlice].pos();
641 it.cell().erase(it.pos());
649 void MathMacroTemplate::shiftArguments(size_t from, int by)
651 for (DocIterator it = doc_iterator_begin(&buffer(), this); it; it.forwardChar()) {
654 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
656 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
657 if (arg->number() >= int(from) + 1)
658 arg->setNumber(arg->number() + by);
665 int MathMacroTemplate::maxArgumentInDefinition() const
667 // We don't have a buffer when pasting from the clipboard (bug 6014).
668 Buffer const * macro_buffer = isBufferLoaded() ? &buffer() : 0;
670 DocIterator it = doc_iterator_begin(macro_buffer, this);
672 for (; it; it.forwardChar()) {
675 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
677 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
678 maxArg = std::max(int(arg->number()), maxArg);
684 void MathMacroTemplate::insertMissingArguments(int maxArg)
686 bool found[9] = { false, false, false, false, false, false, false, false, false };
687 idx_type idx = cell(displayIdx()).empty() ? defIdx() : displayIdx();
689 // search for #n macros arguments
690 DocIterator it = doc_iterator_begin(&buffer(), this);
692 for (; it && it[0].idx() == idx; it.forwardChar()) {
695 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
697 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
698 found[arg->number() - 1] = true;
702 for (int i = 0; i < maxArg; ++i) {
706 cell(idx).push_back(MathAtom(new MathMacroArgument(i + 1)));
711 void MathMacroTemplate::changeArity(Cursor & cur,
712 DocIterator const & inset_pos, int newNumArg)
714 // remove parameter which do not appear anymore in the definition
715 for (int i = numargs_; i > newNumArg; --i)
716 removeParameter(cur, inset_pos, numargs_ - 1, true);
718 // add missing parameter
719 for (int i = numargs_; i < newNumArg; ++i)
720 insertParameter(cur, inset_pos, numargs_, true, false);
725 class AddRemoveMacroInstanceFix
729 AddRemoveMacroInstanceFix(int n, bool insert) : n_(n), insert_(insert) {}
731 void operator()(MathMacro * macro)
733 if (macro->folded()) {
735 macro->insertArgument(n_);
737 macro->removeArgument(n_);
750 class OptionalsMacroInstanceFix
754 OptionalsMacroInstanceFix(int optionals) : optionals_(optionals) {}
756 void operator()(MathMacro * macro)
758 macro->setOptionals(optionals_);
768 class NullMacroInstanceFix
772 void operator()(MathMacro * ) {}
777 void fixMacroInstances(Cursor & cur, DocIterator const & inset_pos,
778 docstring const & name, F & fix)
780 // goto position behind macro template
781 DocIterator dit = inset_pos;
783 dit.top().forwardPos();
785 // remember hull to trigger preview reload
786 DocIterator hull(dit.buffer());
787 bool preview_reload_needed = false;
788 set<DocIterator> preview_hulls;
790 // iterate over all positions until macro is redefined
791 for (; dit; dit.forwardPos()) {
792 // left the outer hull?
793 if (!hull.empty() && dit.depth() == hull.depth()) {
794 // schedule reload of the preview if necessary
795 if (preview_reload_needed) {
796 preview_hulls.insert(hull);
797 preview_reload_needed = false;
802 // only until a macro is redefined
803 if (dit.inset().lyxCode() == MATHMACRO_CODE) {
804 MathMacroTemplate const & macroTemplate
805 = static_cast<MathMacroTemplate const &>(dit.inset());
806 if (macroTemplate.name() == name)
810 // in front of macro instance?
811 Inset * inset = dit.nextInset();
814 InsetMath * insetMath = inset->asInsetMath();
818 // in front of outer hull?
819 InsetMathHull * inset_hull = insetMath->asHullInset();
820 if (inset_hull && hull.empty()) {
821 // remember this for later preview reload
825 MathMacro * macro = insetMath->asMacro();
826 if (macro && macro->name() == name && macro->folded()) {
828 if (RenderPreview::previewMath())
829 preview_reload_needed = true;
833 if (!preview_hulls.empty()) {
834 // reload the scheduled previews
835 set<DocIterator>::const_iterator sit = preview_hulls.begin();
836 set<DocIterator>::const_iterator end = preview_hulls.end();
837 for (; sit != end; ++sit) {
838 InsetMathHull * inset_hull =
839 sit->nextInset()->asInsetMath()->asHullInset();
841 inset_hull->reloadPreview(*sit);
843 cur.screenUpdateFlags(Update::Force);
848 void MathMacroTemplate::commitEditChanges(Cursor & cur,
849 DocIterator const & inset_pos)
851 int args_in_def = maxArgumentInDefinition();
852 if (args_in_def != numargs_) {
853 // FIXME: implement precise undo handling (only a few places
855 cur.recordUndoFullBuffer();
856 changeArity(cur, inset_pos, args_in_def);
858 insertMissingArguments(args_in_def);
860 // make sure the preview are up to date
861 NullMacroInstanceFix fix;
862 fixMacroInstances(cur, inset_pos, name(), fix);
866 void MathMacroTemplate::insertParameter(Cursor & cur,
867 DocIterator const & inset_pos, int pos, bool greedy, bool addarg)
869 if (pos <= numargs_ && pos >= optionals_ && numargs_ < 9) {
874 shiftArguments(pos, 1);
876 cell(defIdx()).push_back(MathAtom(new MathMacroArgument(pos + 1)));
877 if (!cell(displayIdx()).empty())
878 cell(displayIdx()).push_back(MathAtom(new MathMacroArgument(pos + 1)));
882 // fix macro instances
883 AddRemoveMacroInstanceFix fix(pos, true);
884 fixMacroInstances(cur, inset_pos, name(), fix);
892 void MathMacroTemplate::removeParameter(Cursor & cur,
893 DocIterator const & inset_pos, int pos, bool greedy)
895 if (pos < numargs_ && pos >= 0) {
897 removeArguments(cur, inset_pos, pos, pos);
898 shiftArguments(pos + 1, -1);
900 // removed optional parameter?
901 if (pos < optionals_) {
903 optionalValues_[pos] = cell(optIdx(pos));
904 cells_.erase(cells_.begin() + optIdx(pos));
907 int macroSlice = cur.find(this);
908 if (macroSlice != -1) {
909 if (cur[macroSlice].idx() == optIdx(pos)) {
910 cur.cutOff(macroSlice);
911 cur[macroSlice].idx() = 1;
912 cur[macroSlice].pos() = 0;
913 } else if (cur[macroSlice].idx() > optIdx(pos))
914 --cur[macroSlice].idx();
919 // fix macro instances
920 AddRemoveMacroInstanceFix fix(pos, false);
921 fixMacroInstances(cur, inset_pos, name(), fix);
929 void MathMacroTemplate::makeOptional(Cursor & cur,
930 DocIterator const & inset_pos)
932 if (numargs_ > 0 && optionals_ < numargs_) {
934 cells_.insert(cells_.begin() + optIdx(optionals_ - 1), optionalValues_[optionals_ - 1]);
936 int macroSlice = cur.find(this);
937 if (macroSlice != -1 && cur[macroSlice].idx() >= optIdx(optionals_ - 1))
938 ++cur[macroSlice].idx();
940 // fix macro instances
941 OptionalsMacroInstanceFix fix(optionals_);
942 fixMacroInstances(cur, inset_pos, name(), fix);
949 void MathMacroTemplate::makeNonOptional(Cursor & cur,
950 DocIterator const & inset_pos)
952 if (numargs_ > 0 && optionals_ > 0) {
955 // store default value for later if the user changes his mind
956 optionalValues_[optionals_] = cell(optIdx(optionals_));
957 cells_.erase(cells_.begin() + optIdx(optionals_));
960 int macroSlice = cur.find(this);
961 if (macroSlice != -1) {
962 if (cur[macroSlice].idx() > optIdx(optionals_))
963 --cur[macroSlice].idx();
964 else if (cur[macroSlice].idx() == optIdx(optionals_)) {
965 cur.cutOff(macroSlice);
966 cur[macroSlice].idx() = optIdx(optionals_);
967 cur[macroSlice].pos() = 0;
971 // fix macro instances
972 OptionalsMacroInstanceFix fix(optionals_);
973 fixMacroInstances(cur, inset_pos, name(), fix);
980 void MathMacroTemplate::doDispatch(Cursor & cur, FuncRequest & cmd)
982 string const arg = to_utf8(cmd.argument());
983 switch (cmd.action()) {
985 case LFUN_MATH_MACRO_ADD_PARAM:
987 commitEditChanges(cur, cur);
988 // FIXME: implement precise undo handling (only a few places
990 cur.recordUndoFullBuffer();
991 size_t pos = numargs_;
993 pos = (size_t)convert<int>(arg) - 1; // it is checked for >=0 in getStatus
994 insertParameter(cur, cur, pos);
999 case LFUN_MATH_MACRO_REMOVE_PARAM:
1001 commitEditChanges(cur, cur);
1002 // FIXME: implement precise undo handling (only a few places
1004 cur.recordUndoFullBuffer();
1005 size_t pos = numargs_ - 1;
1007 pos = (size_t)convert<int>(arg) - 1; // it is checked for >=0 in getStatus
1008 removeParameter(cur, cur, pos);
1012 case LFUN_MATH_MACRO_APPEND_GREEDY_PARAM:
1014 commitEditChanges(cur, cur);
1015 // FIXME: implement precise undo handling (only a few places
1017 cur.recordUndoFullBuffer();
1018 insertParameter(cur, cur, numargs_, true);
1022 case LFUN_MATH_MACRO_REMOVE_GREEDY_PARAM:
1024 commitEditChanges(cur, cur);
1025 // FIXME: implement precise undo handling (only a few places
1027 cur.recordUndoFullBuffer();
1028 removeParameter(cur, cur, numargs_ - 1, true);
1032 case LFUN_MATH_MACRO_MAKE_OPTIONAL:
1033 commitEditChanges(cur, cur);
1034 // FIXME: implement precise undo handling (only a few places
1036 cur.recordUndoFullBuffer();
1037 makeOptional(cur, cur);
1040 case LFUN_MATH_MACRO_MAKE_NONOPTIONAL:
1041 commitEditChanges(cur, cur);
1042 // FIXME: implement precise undo handling (only a few places
1044 cur.recordUndoFullBuffer();
1045 makeNonOptional(cur, cur);
1048 case LFUN_MATH_MACRO_ADD_OPTIONAL_PARAM:
1050 commitEditChanges(cur, cur);
1051 // FIXME: implement precise undo handling (only a few places
1053 cur.recordUndoFullBuffer();
1054 insertParameter(cur, cur, optionals_);
1055 makeOptional(cur, cur);
1059 case LFUN_MATH_MACRO_REMOVE_OPTIONAL_PARAM:
1060 if (optionals_ > 0) {
1061 commitEditChanges(cur, cur);
1062 // FIXME: implement precise undo handling (only a few places
1064 cur.recordUndoFullBuffer();
1065 removeParameter(cur, cur, optionals_ - 1);
1068 case LFUN_MATH_MACRO_ADD_GREEDY_OPTIONAL_PARAM:
1069 if (numargs_ == optionals_) {
1070 commitEditChanges(cur, cur);
1071 // FIXME: implement precise undo handling (only a few places
1073 cur.recordUndoFullBuffer();
1074 insertParameter(cur, cur, 0, true);
1075 makeOptional(cur, cur);
1080 InsetMathNest::doDispatch(cur, cmd);
1086 bool MathMacroTemplate::getStatus(Cursor & cur, FuncRequest const & cmd,
1087 FuncStatus & flag) const
1090 string const arg = to_utf8(cmd.argument());
1091 switch (cmd.action()) {
1092 case LFUN_MATH_MACRO_ADD_PARAM: {
1093 int num = numargs_ + 1;
1095 num = convert<int>(arg);
1096 bool on = (num >= optionals_
1097 && numargs_ < 9 && num <= numargs_ + 1);
1098 flag.setEnabled(on);
1102 case LFUN_MATH_MACRO_APPEND_GREEDY_PARAM:
1103 flag.setEnabled(numargs_ < 9);
1106 case LFUN_MATH_MACRO_REMOVE_GREEDY_PARAM:
1107 case LFUN_MATH_MACRO_REMOVE_PARAM: {
1110 num = convert<int>(arg);
1111 flag.setEnabled(num >= 1 && num <= numargs_);
1115 case LFUN_MATH_MACRO_MAKE_OPTIONAL:
1116 flag.setEnabled(numargs_ > 0
1117 && optionals_ < numargs_
1118 && type_ != MacroTypeDef);
1121 case LFUN_MATH_MACRO_MAKE_NONOPTIONAL:
1122 flag.setEnabled(optionals_ > 0
1123 && type_ != MacroTypeDef);
1126 case LFUN_MATH_MACRO_ADD_OPTIONAL_PARAM:
1127 flag.setEnabled(numargs_ < 9);
1130 case LFUN_MATH_MACRO_REMOVE_OPTIONAL_PARAM:
1131 flag.setEnabled(optionals_ > 0);
1134 case LFUN_MATH_MACRO_ADD_GREEDY_OPTIONAL_PARAM:
1135 flag.setEnabled(numargs_ == 0
1136 && type_ != MacroTypeDef);
1139 case LFUN_IN_MATHMACROTEMPLATE:
1140 flag.setEnabled(true);
1144 ret = InsetMathNest::getStatus(cur, cmd, flag);
1151 void MathMacroTemplate::read(Lexer & lex)
1153 MathData ar(buffer_);
1154 mathed_parse_cell(ar, lex.getStream(), Parse::TRACKMACRO);
1155 if (ar.size() != 1 || !ar[0]->asMacroTemplate()) {
1156 lyxerr << "Cannot read macro from '" << ar << "'" << endl;
1157 lyxerr << "Read: " << to_utf8(asString(ar)) << endl;
1160 operator=( *(ar[0]->asMacroTemplate()) );
1166 void MathMacroTemplate::write(ostream & os) const
1168 odocstringstream oss;
1169 otexrowstream ots(oss);
1170 WriteStream wi(ots, false, false, WriteStream::wsDefault);
1171 oss << "FormulaMacro\n";
1173 os << to_utf8(oss.str());
1177 void MathMacroTemplate::write(WriteStream & os) const
1183 int MathMacroTemplate::write(WriteStream & os, bool overwriteRedefinition) const
1188 if (optionals_ > 0) {
1189 // macros with optionals use the xargs package, e.g.:
1190 // \newcommandx{\foo}[2][usedefault, addprefix=\global,1=default]{#1,#2}
1191 // \long is implicit by xargs
1192 if (redefinition_ && !overwriteRedefinition)
1193 os << "\\renewcommandx";
1195 os << "\\newcommandx";
1197 os << "\\" << name()
1198 << "[" << numargs_ << "]"
1199 << "[usedefault, addprefix=\\global";
1200 for (int i = 0; i < optionals_; ++i) {
1201 docstring optValue = asString(cell(optIdx(i)));
1202 if (optValue.find(']') != docstring::npos
1203 || optValue.find(',') != docstring::npos)
1204 os << ", " << i + 1 << "="
1205 << "{" << cell(optIdx(i)) << "}";
1207 os << ", " << i + 1 << "="
1212 // Macros without optionals use standard _global_ \def macros:
1213 // \global\def\long\foo#1#2{#1,#2}
1214 // We use the \long prefix as this is the equivalent to \newcommand.
1215 // We cannot use \newcommand directly because \global does not work with it.
1216 os << "\\global\\long\\def\\" << name();
1217 docstring param = from_ascii("#0");
1218 for (int i = 1; i <= numargs_; ++i) {
1224 // in LyX output we use some pseudo syntax which is implementation
1225 // independent, e.g.
1226 // \newcommand{\foo}[2][default]{#1,#2}
1227 if (redefinition_ && !overwriteRedefinition)
1228 os << "\\renewcommand";
1230 os << "\\newcommand";
1231 os << "{\\" << name() << '}';
1233 os << '[' << numargs_ << ']';
1235 for (int i = 0; i < optionals_; ++i) {
1236 docstring optValue = asString(cell(optIdx(i)));
1237 if (optValue.find(']') != docstring::npos)
1238 os << "[{" << cell(optIdx(i)) << "}]";
1240 os << "[" << cell(optIdx(i)) << "]";
1244 os << "{" << cell(defIdx()) << "}";
1247 // writing .tex. done.
1251 // writing .lyx, write special .tex export only if necessary
1252 if (!cell(displayIdx()).empty()) {
1253 os << "\n{" << cell(displayIdx()) << '}';
1262 docstring MathMacroTemplate::xhtml(XHTMLStream &, OutputParams const &) const
1267 int MathMacroTemplate::plaintext(odocstringstream & os,
1268 OutputParams const &, size_t) const
1270 docstring const str = '[' + buffer().B_("math macro") + ']';
1277 bool MathMacroTemplate::validName() const
1279 docstring n = name();
1284 // converting back and force doesn't swallow anything?
1287 if (asString(ma) != n)
1290 // valid characters?
1291 for (size_t i = 0; i < n.size(); ++i) {
1292 if (!(n[i] >= 'a' && n[i] <= 'z')
1293 && !(n[i] >= 'A' && n[i] <= 'Z')
1302 bool MathMacroTemplate::validMacro() const
1308 bool MathMacroTemplate::fixNameAndCheckIfValid()
1310 // check all the characters/insets in the name cell
1312 MathData & data = cell(0);
1313 while (i < data.size()) {
1314 InsetMathChar const * cinset = data[i]->asCharInset();
1316 // valid character in [a-zA-Z]?
1317 char_type c = cinset->getChar();
1318 if ((c >= 'a' && c <= 'z')
1319 || (c >= 'A' && c <= 'Z')) {
1329 // now it should be valid if anything in the name survived
1330 return !data.empty();
1334 void MathMacroTemplate::validate(LaTeXFeatures & features) const
1336 // we need global optional macro arguments. They are not available
1337 // with \def, and \newcommand does not support global macros. So we
1338 // are bound to xargs also for the single-optional-parameter case.
1340 features.require("xargs");
1343 void MathMacroTemplate::getDefaults(vector<docstring> & defaults) const
1345 defaults.resize(numargs_);
1346 for (int i = 0; i < optionals_; ++i)
1347 defaults[i] = asString(cell(optIdx(i)));
1351 docstring MathMacroTemplate::definition() const
1353 return asString(cell(defIdx()));
1357 docstring MathMacroTemplate::displayDefinition() const
1359 return asString(cell(displayIdx()));
1363 size_t MathMacroTemplate::numArgs() const
1369 size_t MathMacroTemplate::numOptionals() const
1375 void MathMacroTemplate::infoize(odocstream & os) const
1377 os << bformat(_("Math Macro: \\%1$s"), name());
1381 string MathMacroTemplate::contextMenuName() const
1383 return "context-math-macro-definition";
1387 void MathMacroTemplate::addToToc(DocIterator const & pit, bool output_active,
1388 UpdateType, TocBackend & backend) const
1392 str = bformat(_("Invalid macro! \\%1$s"), name());
1394 str = "\\" + name();
1395 TocBuilder & b = backend.builder("math-macro");
1396 b.pushItem(pit, str, output_active);