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 "DocIterator.h"
17 #include "LaTeXFeatures.h"
18 #include "InsetMathBrace.h"
19 #include "InsetMathChar.h"
20 #include "InsetMathSqrt.h"
21 #include "MathMacro.h"
22 #include "MathMacroArgument.h"
23 #include "MathStream.h"
24 #include "MathParser.h"
25 #include "MathSupport.h"
26 #include "MathMacroArgument.h"
29 #include "BufferView.h"
32 #include "DispatchResult.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
38 #include "frontends/Painter.h"
40 #include "support/lassert.h"
41 #include "support/convert.h"
42 #include "support/debug.h"
43 #include "support/gettext.h"
44 #include "support/docstream.h"
45 #include "support/lstrings.h"
53 using support::bformat;
55 //////////////////////////////////////////////////////////////////////
57 class InsetLabelBox : public InsetMathNest {
60 InsetLabelBox(MathAtom const & atom, docstring label,
61 MathMacroTemplate const & parent, bool frame = false);
62 InsetLabelBox(docstring label, MathMacroTemplate const & parent,
65 void metrics(MetricsInfo & mi, Dimension & dim) const;
67 void draw(PainterInfo &, int x, int y) const;
71 MathMacroTemplate const & parent_;
73 Inset * clone() const;
75 docstring const label_;
81 InsetLabelBox::InsetLabelBox(MathAtom const & atom, docstring label,
82 MathMacroTemplate const & parent, bool frame)
83 : InsetMathNest(1), parent_(parent), label_(label), frame_(frame)
85 cell(0).insert(0, atom);
89 InsetLabelBox::InsetLabelBox(docstring label,
90 MathMacroTemplate const & parent, bool frame)
91 : InsetMathNest(1), parent_(parent), label_(label), frame_(frame)
96 Inset * InsetLabelBox::clone() const
98 return new InsetLabelBox(*this);
102 void InsetLabelBox::metrics(MetricsInfo & mi, Dimension & dim) const
105 cell(0).metrics(mi, dim);
114 // adjust to common height in main metrics phase
115 if (!parent_.premetrics()) {
116 dim.asc = max(dim.asc, parent_.commonLabelBoxAscent());
117 dim.des = max(dim.des, parent_.commonLabelBoxDescent());
121 if (parent_.editing(mi.base.bv) && label_.length() > 0) {
123 FontInfo font = sane_font;
124 font.setSize(FONT_SIZE_TINY);
125 font.setColor(Color_mathmacrolabel);
127 // make space for label and box
128 int lwid = mathed_string_width(font, label_);
131 math_font_max_dim(font, maxasc, maxdes);
133 dim.wid = max(dim.wid, lwid + 2);
135 // space for the label
136 if (!parent_.premetrics())
137 dim.des += maxasc + maxdes + 1;
142 void InsetLabelBox::draw(PainterInfo & pi, int x, int y) const
144 Dimension const dim = dimension(*pi.base.bv);
145 Dimension const cdim = cell(0).dimension(*pi.base.bv);
148 cell(0).draw(pi, x + (dim.wid - cdim.wid) / 2, y);
151 if (parent_.editing(pi.base.bv) && label_.length() > 0) {
153 FontInfo font = sane_font;
154 font.setSize(FONT_SIZE_TINY);
155 font.setColor(Color_mathmacrolabel);
157 // make space for label and box
158 int lwid = mathed_string_width(font, label_);
161 math_font_max_dim(font, maxasc, maxdes);
164 pi.pain.text(x + (dim.wid - lwid) / 2, y + dim.des - maxdes, label_, font);
166 pi.pain.text(x, y + dim.des - maxdes, label_, font);
170 int boxHeight = parent_.commonLabelBoxAscent() + parent_.commonLabelBoxDescent();
172 pi.pain.rectangle(x + 1, y - dim.ascent() + 1,
173 dim.wid - 2, boxHeight - 2,
179 //////////////////////////////////////////////////////////////////////
181 class DisplayLabelBox : public InsetLabelBox {
184 DisplayLabelBox(MathAtom const & atom, docstring label,
185 MathMacroTemplate const & parent);
188 void metrics(MetricsInfo & mi, Dimension & dim) const;
190 void draw(PainterInfo &, int x, int y) const;
194 Inset * clone() const;
198 DisplayLabelBox::DisplayLabelBox(MathAtom const & atom,
200 MathMacroTemplate const & parent)
201 : InsetLabelBox(atom, label, parent, true)
207 Inset * DisplayLabelBox::clone() const
209 return new DisplayLabelBox(*this);
213 void DisplayLabelBox::metrics(MetricsInfo & mi, Dimension & dim) const
215 InsetLabelBox::metrics(mi, dim);
216 if (!parent_.editing(mi.base.bv)
217 && parent_.cell(parent_.displayIdx()).empty()) {
225 void DisplayLabelBox::draw(PainterInfo & pi, int x, int y) const
227 if (parent_.editing(pi.base.bv)
228 || !parent_.cell(parent_.displayIdx()).empty()) {
229 InsetLabelBox::draw(pi, x, y);
231 bool enabled = pi.pain.isDrawingEnabled();
232 pi.pain.setDrawingEnabled(false);
233 InsetLabelBox::draw(pi, x, y);
234 pi.pain.setDrawingEnabled(enabled);
239 //////////////////////////////////////////////////////////////////////
241 class InsetMathWrapper : public InsetMath {
244 InsetMathWrapper(MathData const * value) : value_(value) {}
246 void metrics(MetricsInfo & mi, Dimension & dim) const;
248 void draw(PainterInfo &, int x, int y) const;
252 Inset * clone() const;
254 MathData const * value_;
258 Inset * InsetMathWrapper::clone() const
260 return new InsetMathWrapper(*this);
264 void InsetMathWrapper::metrics(MetricsInfo & mi, Dimension & dim) const
266 value_->metrics(mi, dim);
267 //metricsMarkers2(dim);
271 void InsetMathWrapper::draw(PainterInfo & pi, int x, int y) const
273 value_->draw(pi, x, y);
274 //drawMarkers(pi, x, y);
278 ///////////////////////////////////////////////////////////////////////
279 class InsetColoredCell : public InsetMathNest {
282 InsetColoredCell(ColorCode min, ColorCode max);
284 InsetColoredCell(ColorCode min, ColorCode max, MathAtom const & atom);
286 void draw(PainterInfo &, int x, int y) const;
288 void metrics(MetricsInfo & mi, Dimension & dim) const;
292 Inset * clone() const;
300 InsetColoredCell::InsetColoredCell(ColorCode min, ColorCode max)
301 : InsetMathNest(1), min_(min), max_(max)
306 InsetColoredCell::InsetColoredCell(ColorCode min, ColorCode max, MathAtom const & atom)
307 : InsetMathNest(1), min_(min), max_(max)
309 cell(0).insert(0, atom);
313 Inset * InsetColoredCell::clone() const
315 return new InsetColoredCell(*this);
319 void InsetColoredCell::metrics(MetricsInfo & mi, Dimension & dim) const
321 cell(0).metrics(mi, dim);
325 void InsetColoredCell::draw(PainterInfo & pi, int x, int y) const
327 pi.pain.enterMonochromeMode(min_, max_);
328 cell(0).draw(pi, x, y);
329 pi.pain.leaveMonochromeMode();
333 ///////////////////////////////////////////////////////////////////////
335 class InsetNameWrapper : public InsetMathWrapper {
338 InsetNameWrapper(MathData const * value, MathMacroTemplate const & parent);
340 void metrics(MetricsInfo & mi, Dimension & dim) const;
342 void draw(PainterInfo &, int x, int y) const;
346 MathMacroTemplate const & parent_;
348 Inset * clone() const;
352 InsetNameWrapper::InsetNameWrapper(MathData const * value,
353 MathMacroTemplate const & parent)
354 : InsetMathWrapper(value), parent_(parent)
359 Inset * InsetNameWrapper::clone() const
361 return new InsetNameWrapper(*this);
365 void InsetNameWrapper::metrics(MetricsInfo & mi, Dimension & dim) const
367 InsetMathWrapper::metrics(mi, dim);
368 dim.wid += mathed_string_width(mi.base.font, from_ascii("\\"));
372 void InsetNameWrapper::draw(PainterInfo & pi, int x, int y) const
375 PainterInfo namepi = pi;
376 if (parent_.validMacro())
377 namepi.base.font.setColor(Color_latex);
379 namepi.base.font.setColor(Color_error);
382 pi.pain.text(x, y, from_ascii("\\"), namepi.base.font);
383 x += mathed_string_width(namepi.base.font, from_ascii("\\"));
386 InsetMathWrapper::draw(namepi, x, y);
390 ///////////////////////////////////////////////////////////////////////
393 MathMacroTemplate::MathMacroTemplate()
394 : InsetMathNest(3), numargs_(0), argsInLook_(0), optionals_(0),
395 type_(MacroTypeNewcommand), lookOutdated_(true)
401 MathMacroTemplate::MathMacroTemplate(docstring const & name, int numargs,
402 int optionals, MacroType type,
403 vector<MathData> const & optionalValues,
404 MathData const & def, MathData const & display)
405 : InsetMathNest(optionals + 3), numargs_(numargs), argsInLook_(numargs),
406 optionals_(optionals), optionalValues_(optionalValues),
407 type_(type), lookOutdated_(true)
412 lyxerr << "MathMacroTemplate::MathMacroTemplate: wrong # of arguments: "
415 asArray(name, cell(0));
416 optionalValues_.resize(9);
417 for (int i = 0; i < optionals_; ++i)
418 cell(optIdx(i)) = optionalValues_[i];
419 cell(defIdx()) = def;
420 cell(displayIdx()) = display;
426 MathMacroTemplate::MathMacroTemplate(docstring const & str)
427 : InsetMathNest(3), numargs_(0), optionals_(0),
428 type_(MacroTypeNewcommand), lookOutdated_(true)
433 mathed_parse_cell(ar, str);
434 if (ar.size() != 1 || !ar[0]->asMacroTemplate()) {
435 lyxerr << "Cannot read macro from '" << ar << "'" << endl;
436 asArray(from_ascii("invalidmacro"), cell(0));
437 // FIXME: The macro template does not make sense after this.
438 // The whole parsing should not be in a constructor which
439 // has no chance to report failure.
442 operator=( *(ar[0]->asMacroTemplate()) );
448 Inset * MathMacroTemplate::clone() const
450 MathMacroTemplate * inset = new MathMacroTemplate(*this);
451 // the parent pointers of the proxy insets above will point to
452 // to the old template. Hence, the look must be updated.
458 docstring MathMacroTemplate::name() const
460 return asString(cell(0));
464 void MathMacroTemplate::updateToContext(MacroContext const & mc) const
466 redefinition_ = mc.get(name()) != 0;
470 void MathMacroTemplate::updateLook() const
472 lookOutdated_ = true;
476 void MathMacroTemplate::createLook(int args) const
482 look_.push_back(MathAtom(new InsetLabelBox(_("Name"), *this, false)));
483 MathData & nameData = look_[look_.size() - 1].nucleus()->cell(0);
484 nameData.push_back(MathAtom(new InsetNameWrapper(&cell(0), *this)));
488 if (optionals_ > 0) {
489 look_.push_back(MathAtom(new InsetLabelBox(_("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(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(
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(
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(MathAtom(
532 new InsetMathWrapper(&cell(defIdx()))), _("TeX"), *this, true)));
535 look_.push_back(MathAtom(
536 new DisplayLabelBox(MathAtom(
537 new InsetMathWrapper(&cell(displayIdx()))), _("LyX"), *this)));
541 void MathMacroTemplate::metrics(MetricsInfo & mi, Dimension & dim) const
543 FontSetChanger dummy1(mi.base, from_ascii("mathnormal"));
544 StyleChanger dummy2(mi.base, LM_ST_TEXT);
547 MacroData const * macro = 0;
549 macro = mi.macrocontext.get(name());
551 // updateToContext() - avoids another lookup
552 redefinition_ = macro != 0;
556 int argsInDef = maxArgumentInDefinition();
557 if (lookOutdated_ || argsInDef != argsInLook_) {
558 lookOutdated_ = false;
559 createLook(argsInDef);
562 /// metrics for inset contents
566 // first phase, premetric:
568 look_.metrics(mi, dim);
569 labelBoxAscent_ = dim.asc;
570 labelBoxDescent_ = dim.des;
572 // second phase, main metric:
574 look_.metrics(mi, dim);
583 setDimCache(mi, dim);
587 void MathMacroTemplate::draw(PainterInfo & pi, int x, int y) const
589 FontSetChanger dummy1(pi.base, from_ascii("mathnormal"));
590 StyleChanger dummy2(pi.base, LM_ST_TEXT);
592 setPosCache(pi, x, y);
593 Dimension const dim = dimension(*pi.base.bv);
596 int const a = y - dim.asc + 1;
597 int const w = dim.wid - 2;
598 int const h = dim.height() - 2;
599 pi.pain.rectangle(x, a, w, h, Color_mathframe);
601 // just to be sure: set some dummy values for coord cache
602 for (idx_type i = 0; i < nargs(); ++i)
603 cell(i).setXY(*pi.base.bv, x, y);
606 look_.draw(pi, x + 3, y);
610 void MathMacroTemplate::edit(Cursor & cur, bool front, EntryDirection entry_from)
613 cur.updateFlags(Update::SinglePar);
614 InsetMathNest::edit(cur, front, entry_from);
618 bool MathMacroTemplate::notifyCursorLeaves(Cursor const & old, Cursor & cur)
620 // find this in cursor old
621 Cursor insetCur = old;
622 int scriptSlice = insetCur.find(this);
623 LASSERT(scriptSlice != -1, /**/);
624 insetCur.cutOff(scriptSlice);
626 commitEditChanges(insetCur);
628 cur.updateFlags(Update::Force);
629 return InsetMathNest::notifyCursorLeaves(old, cur);
633 void MathMacroTemplate::removeArguments(Cursor & cur, int from, int to)
635 for (DocIterator it = doc_iterator_begin(&buffer(), this); it; it.forwardChar()) {
638 if (it.nextInset()->lyxCode() != MATHMACROARG_CODE)
640 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
641 int n = arg->number() - 1;
642 if (from <= n && n <= to) {
643 int cellSlice = cur.find(it.cell());
644 if (cellSlice != -1 && cur[cellSlice].pos() > it.pos())
645 --cur[cellSlice].pos();
647 it.cell().erase(it.pos());
655 void MathMacroTemplate::shiftArguments(size_t from, int by)
657 for (DocIterator it = doc_iterator_begin(&buffer(), this); it; it.forwardChar()) {
660 if (it.nextInset()->lyxCode() != MATHMACROARG_CODE)
662 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
663 if (arg->number() >= int(from) + 1)
664 arg->setNumber(arg->number() + by);
671 int MathMacroTemplate::maxArgumentInDefinition() const
674 DocIterator it = doc_iterator_begin(&buffer(), this);
676 for (; it; it.forwardChar()) {
679 if (it.nextInset()->lyxCode() != MATHMACROARG_CODE)
681 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
682 maxArg = std::max(int(arg->number()), maxArg);
688 void MathMacroTemplate::insertMissingArguments(int maxArg)
690 bool found[9] = { false, false, false, false, false, false, false, false, false };
691 idx_type idx = cell(displayIdx()).empty() ? defIdx() : displayIdx();
693 // search for #n macros arguments
694 DocIterator it = doc_iterator_begin(&buffer(), this);
696 for (; it && it[0].idx() == idx; it.forwardChar()) {
699 if (it.nextInset()->lyxCode() != MATHMACROARG_CODE)
701 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
702 found[arg->number() - 1] = true;
706 for (int i = 0; i < maxArg; ++i) {
710 cell(idx).push_back(MathAtom(new MathMacroArgument(i + 1)));
715 void MathMacroTemplate::changeArity(Cursor & cur, int newNumArg)
717 // remove parameter which do not appear anymore in the definition
718 for (int i = numargs_; i > newNumArg; --i)
719 removeParameter(cur, numargs_ - 1, false);
721 // add missing parameter
722 for (int i = numargs_; i < newNumArg; ++i)
723 insertParameter(cur, numargs_, false, false);
727 void MathMacroTemplate::commitEditChanges(Cursor & cur)
729 int argsInDef = maxArgumentInDefinition();
730 if (argsInDef != numargs_) {
731 cur.recordUndoFullDocument();
732 changeArity(cur, argsInDef);
734 insertMissingArguments(argsInDef);
738 // FIXME: factorize those functions here with a functional style, maybe using Boost's function
741 void fixMacroInstancesAddRemove(Cursor const & from, docstring const & name, int n, bool insert) {
744 for (; dit; dit.forwardPos()) {
745 // only until a macro is redefined
746 if (dit.inset().lyxCode() == MATHMACRO_CODE) {
747 MathMacroTemplate const & macroTemplate
748 = static_cast<MathMacroTemplate const &>(dit.inset());
749 if (macroTemplate.name() == name)
753 // in front of macro instance?
754 Inset * inset = dit.nextInset();
757 InsetMath * insetMath = inset->asInsetMath();
761 MathMacro * macro = insetMath->asMacro();
762 if (macro && macro->name() == name && macro->folded()) {
763 // found macro instance
765 macro->insertArgument(n);
767 macro->removeArgument(n);
773 void fixMacroInstancesOptional(Cursor const & from, docstring const & name, int optionals) {
776 for (; dit; dit.forwardPos()) {
777 // only until a macro is redefined
778 if (dit.inset().lyxCode() == MATHMACRO_CODE) {
779 MathMacroTemplate const & macroTemplate
780 = static_cast<MathMacroTemplate const &>(dit.inset());
781 if (macroTemplate.name() == name)
785 // in front of macro instance?
786 Inset * inset = dit.nextInset();
789 InsetMath * insetMath = inset->asInsetMath();
792 MathMacro * macro = insetMath->asMacro();
793 if (macro && macro->name() == name && macro->folded()) {
794 // found macro instance
795 macro->setOptionals(optionals);
802 void fixMacroInstancesFunctional(Cursor const & from,
803 docstring const & name, F & fix) {
806 for (; dit; dit.forwardPos()) {
807 // only until a macro is redefined
808 if (dit.inset().lyxCode() == MATHMACRO_CODE) {
809 MathMacroTemplate const & macroTemplate
810 = static_cast<MathMacroTemplate const &>(dit.inset());
811 if (macroTemplate.name() == name)
815 // in front of macro instance?
816 Inset * inset = dit.nextInset();
819 InsetMath * insetMath = inset->asInsetMath();
822 MathMacro * macro = insetMath->asMacro();
823 if (macro && macro->name() == name && macro->folded())
829 void MathMacroTemplate::insertParameter(Cursor & cur, int pos, bool greedy, bool addarg)
831 if (pos <= numargs_ && pos >= optionals_ && numargs_ < 9) {
836 shiftArguments(pos, 1);
838 cell(defIdx()).push_back(MathAtom(new MathMacroArgument(pos + 1)));
839 if (!cell(displayIdx()).empty())
840 cell(displayIdx()).push_back(MathAtom(new MathMacroArgument(pos + 1)));
845 dit.leaveInset(*this);
846 // TODO: this was dit.forwardPosNoDescend before. Check that this is the same
847 dit.top().forwardPos();
849 // fix macro instances
850 fixMacroInstancesAddRemove(dit, name(), pos, true);
858 void MathMacroTemplate::removeParameter(Cursor & cur, int pos, bool greedy)
860 if (pos < numargs_ && pos >= 0) {
862 removeArguments(cur, pos, pos);
863 shiftArguments(pos + 1, -1);
865 // removed optional parameter?
866 if (pos < optionals_) {
868 optionalValues_[pos] = cell(optIdx(pos));
869 cells_.erase(cells_.begin() + optIdx(pos));
872 int macroSlice = cur.find(this);
873 if (macroSlice != -1) {
874 if (cur[macroSlice].idx() == optIdx(pos)) {
875 cur.cutOff(macroSlice);
876 cur[macroSlice].idx() = 1;
877 cur[macroSlice].pos() = 0;
878 } else if (cur[macroSlice].idx() > optIdx(pos))
879 --cur[macroSlice].idx();
884 // fix macro instances
885 //boost::function<void(MathMacro *)> fix = _1->insertArgument(n);
886 //fixMacroInstancesFunctional(dit, name(), fix);
888 dit.leaveInset(*this);
889 // TODO: this was dit.forwardPosNoDescend before. Check that this is the same
890 dit.top().forwardPos();
891 fixMacroInstancesAddRemove(dit, name(), pos, false);
899 void MathMacroTemplate::makeOptional(Cursor & cur) {
900 if (numargs_ > 0 && optionals_ < numargs_) {
902 cells_.insert(cells_.begin() + optIdx(optionals_ - 1), optionalValues_[optionals_ - 1]);
904 int macroSlice = cur.find(this);
905 if (macroSlice != -1 && cur[macroSlice].idx() >= optIdx(optionals_ - 1))
906 ++cur[macroSlice].idx();
908 // fix macro instances
910 dit.leaveInset(*this);
911 // TODO: this was dit.forwardPosNoDescend before. Check that this is the same
912 dit.top().forwardPos();
913 fixMacroInstancesOptional(dit, name(), optionals_);
920 void MathMacroTemplate::makeNonOptional(Cursor & cur) {
921 if (numargs_ > 0 && optionals_ > 0) {
924 // store default value for later if the user changes his mind
925 optionalValues_[optionals_] = cell(optIdx(optionals_));
926 cells_.erase(cells_.begin() + optIdx(optionals_));
929 int macroSlice = cur.find(this);
930 if (macroSlice != -1) {
931 if (cur[macroSlice].idx() > optIdx(optionals_))
932 --cur[macroSlice].idx();
933 else if (cur[macroSlice].idx() == optIdx(optionals_)) {
934 cur.cutOff(macroSlice);
935 cur[macroSlice].idx() = optIdx(optionals_);
936 cur[macroSlice].pos() = 0;
940 // fix macro instances
942 dit.leaveInset(*this);
943 // TODO: this was dit.forwardPosNoDescend before. Check that this is the same
944 dit.top().forwardPos();
945 fixMacroInstancesOptional(dit, name(), optionals_);
952 void MathMacroTemplate::doDispatch(Cursor & cur, FuncRequest & cmd)
954 string const arg = to_utf8(cmd.argument());
955 switch (cmd.action) {
957 case LFUN_MATH_MACRO_ADD_PARAM:
959 commitEditChanges(cur);
960 cur.recordUndoFullDocument();
961 size_t pos = numargs_;
963 pos = (size_t)convert<int>(arg) - 1; // it is checked for >=0 in getStatus
964 insertParameter(cur, pos);
969 case LFUN_MATH_MACRO_REMOVE_PARAM:
971 commitEditChanges(cur);
972 cur.recordUndoFullDocument();
973 size_t pos = numargs_ - 1;
975 pos = (size_t)convert<int>(arg) - 1; // it is checked for >=0 in getStatus
976 removeParameter(cur, pos);
980 case LFUN_MATH_MACRO_APPEND_GREEDY_PARAM:
982 commitEditChanges(cur);
983 cur.recordUndoFullDocument();
984 insertParameter(cur, numargs_, true);
988 case LFUN_MATH_MACRO_REMOVE_GREEDY_PARAM:
990 commitEditChanges(cur);
991 cur.recordUndoFullDocument();
992 removeParameter(cur, numargs_ - 1, true);
996 case LFUN_MATH_MACRO_MAKE_OPTIONAL:
997 commitEditChanges(cur);
998 cur.recordUndoFullDocument();
1002 case LFUN_MATH_MACRO_MAKE_NONOPTIONAL:
1003 commitEditChanges(cur);
1004 cur.recordUndoFullDocument();
1005 makeNonOptional(cur);
1008 case LFUN_MATH_MACRO_ADD_OPTIONAL_PARAM:
1010 commitEditChanges(cur);
1011 cur.recordUndoFullDocument();
1012 insertParameter(cur, optionals_);
1017 case LFUN_MATH_MACRO_REMOVE_OPTIONAL_PARAM:
1018 if (optionals_ > 0) {
1019 commitEditChanges(cur);
1020 cur.recordUndoFullDocument();
1021 removeParameter(cur, optionals_ - 1);
1024 case LFUN_MATH_MACRO_ADD_GREEDY_OPTIONAL_PARAM:
1025 if (numargs_ == optionals_) {
1026 commitEditChanges(cur);
1027 cur.recordUndoFullDocument();
1028 insertParameter(cur, 0, true);
1034 InsetMathNest::doDispatch(cur, cmd);
1040 bool MathMacroTemplate::getStatus(Cursor & /*cur*/, FuncRequest const & cmd,
1041 FuncStatus & flag) const
1044 string const arg = to_utf8(cmd.argument());
1045 switch (cmd.action) {
1046 case LFUN_MATH_MACRO_ADD_PARAM: {
1047 int num = numargs_ + 1;
1048 if (arg.size() != 0)
1049 num = convert<int>(arg);
1050 bool on = (num >= optionals_
1051 && numargs_ < 9 && num <= numargs_ + 1);
1052 flag.setEnabled(on);
1056 case LFUN_MATH_MACRO_APPEND_GREEDY_PARAM:
1057 flag.setEnabled(numargs_ < 9);
1060 case LFUN_MATH_MACRO_REMOVE_PARAM: {
1062 if (arg.size() != 0)
1063 num = convert<int>(arg);
1064 flag.setEnabled(num >= 1 && num <= numargs_);
1068 case LFUN_MATH_MACRO_MAKE_OPTIONAL:
1069 flag.setEnabled(numargs_ > 0
1070 && optionals_ < numargs_
1071 && type_ != MacroTypeDef);
1074 case LFUN_MATH_MACRO_MAKE_NONOPTIONAL:
1075 flag.setEnabled(optionals_ > 0
1076 && type_ != MacroTypeDef);
1079 case LFUN_MATH_MACRO_ADD_OPTIONAL_PARAM:
1080 flag.setEnabled(numargs_ < 9);
1083 case LFUN_MATH_MACRO_REMOVE_OPTIONAL_PARAM:
1084 flag.setEnabled(optionals_ > 0);
1087 case LFUN_MATH_MACRO_ADD_GREEDY_OPTIONAL_PARAM:
1088 flag.setEnabled(numargs_ == 0
1089 && type_ != MacroTypeDef);
1092 case LFUN_IN_MATHMACROTEMPLATE:
1093 flag.setEnabled(true);
1104 void MathMacroTemplate::read(Lexer & lex)
1107 mathed_parse_cell(ar, lex.getStream());
1108 if (ar.size() != 1 || !ar[0]->asMacroTemplate()) {
1109 lyxerr << "Cannot read macro from '" << ar << "'" << endl;
1110 lyxerr << "Read: " << to_utf8(asString(ar)) << endl;
1113 operator=( *(ar[0]->asMacroTemplate()) );
1119 void MathMacroTemplate::write(ostream & os) const
1121 odocstringstream oss;
1122 WriteStream wi(oss, false, false, false);
1123 oss << "FormulaMacro\n";
1125 os << to_utf8(oss.str());
1129 void MathMacroTemplate::write(WriteStream & os) const
1135 void MathMacroTemplate::write(WriteStream & os, bool overwriteRedefinition) const
1138 if (optionals_ > 0) {
1139 // macros with optionals use the xargs package, e.g.:
1140 // \newcommandx{\foo}[2][usedefault, addprefix=\global,1=default]{#1,#2}
1141 // \long is implicit by xargs
1142 if (redefinition_ && !overwriteRedefinition)
1143 os << "\\renewcommandx";
1145 os << "\\newcommandx";
1147 os << "\\" << name()
1148 << "[" << numargs_ << "]"
1149 << "[usedefault, addprefix=\\global";
1150 for (int i = 0; i < optionals_; ++i) {
1151 docstring optValue = asString(cell(optIdx(i)));
1152 if (optValue.find(']') != docstring::npos
1153 || optValue.find(',') != docstring::npos)
1154 os << ", " << i + 1 << "="
1155 << "{" << cell(optIdx(i)) << "}";
1157 os << ", " << i + 1 << "="
1162 // Macros without optionals use standard _global_ \def macros:
1163 // \global\def\long\foo#1#2{#1,#2}
1164 // We use the \long prefix as this is the equivalent to \newcommand.
1165 // We cannot use \newcommand directly because \global does not work with it.
1166 os << "\\global\\long\\def\\" << name();
1167 docstring param = from_ascii("#0");
1168 for (int i = 1; i <= numargs_; ++i) {
1174 // in LyX output we use some pseudo syntax which is implementation
1175 // independent, e.g.
1176 // \newcommand{\foo}[2][default]{#1,#2}
1177 if (redefinition_ && !overwriteRedefinition)
1178 os << "\\renewcommand";
1180 os << "\\newcommand";
1181 os << "{\\" << name() << '}';
1183 os << '[' << numargs_ << ']';
1185 for (int i = 0; i < optionals_; ++i) {
1186 docstring optValue = asString(cell(optIdx(i)));
1187 if (optValue.find(']') != docstring::npos)
1188 os << "[{" << cell(optIdx(i)) << "}]";
1190 os << "[" << cell(optIdx(i)) << "]";
1194 os << "{" << cell(defIdx()) << "}";
1197 // writing .tex. done.
1200 // writing .lyx, write special .tex export only if necessary
1201 if (!cell(displayIdx()).empty())
1202 os << "\n{" << cell(displayIdx()) << '}';
1207 int MathMacroTemplate::plaintext(odocstream & os,
1208 OutputParams const &) const
1210 static docstring const str = '[' + buffer().B_("math macro") + ']';
1217 bool MathMacroTemplate::validName() const
1219 docstring n = name();
1225 // converting back and force doesn't swallow anything?
1228 if (asString(ma) != n)
1231 // valid characters?
1232 for (size_t i = 0; i < n.size(); ++i) {
1233 if (!(n[i] >= 'a' && n[i] <= 'z')
1234 && !(n[i] >= 'A' && n[i] <= 'Z')
1243 bool MathMacroTemplate::validMacro() const
1249 bool MathMacroTemplate::fixNameAndCheckIfValid()
1251 // check all the characters/insets in the name cell
1253 MathData & data = cell(0);
1254 while (i < data.size()) {
1255 InsetMathChar const * cinset = data[i]->asCharInset();
1257 // valid character in [a-zA-Z]?
1258 char_type c = cinset->getChar();
1259 if ((c >= 'a' && c <= 'z')
1260 || (c >= 'A' && c <= 'Z')) {
1270 // now it should be valid if anything in the name survived
1271 return data.size() > 0;
1275 void MathMacroTemplate::validate(LaTeXFeatures & features) const
1277 // we need global optional macro arguments. They are not available
1278 // with \def, and \newcommand does not support global macros. So we
1279 // are bound to xargs also for the single-optional-parameter case.
1281 features.require("xargs");
1284 void MathMacroTemplate::getDefaults(vector<docstring> & defaults) const
1286 defaults.resize(numargs_);
1287 for (int i = 0; i < optionals_; ++i)
1288 defaults[i] = asString(cell(optIdx(i)));
1292 docstring MathMacroTemplate::definition() const
1294 return asString(cell(defIdx()));
1298 docstring MathMacroTemplate::displayDefinition() const
1300 return asString(cell(displayIdx()));
1304 size_t MathMacroTemplate::numArgs() const
1310 size_t MathMacroTemplate::numOptionals() const
1316 void MathMacroTemplate::infoize(odocstream & os) const
1318 os << "Math Macro: \\" << name();
1322 docstring MathMacroTemplate::contextMenu(BufferView const &, int, int) const
1324 return from_ascii("context-math-macro-definition");