2 * \file MathMacroTemplate.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * Full author contact details are available in file CREDITS.
13 #include "MathMacroTemplate.h"
15 #include "DocIterator.h"
16 #include "LaTeXFeatures.h"
17 #include "InsetMathBrace.h"
18 #include "InsetMathChar.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 "FuncRequest.h"
33 #include "FuncStatus.h"
37 #include "frontends/Painter.h"
39 #include "support/convert.h"
40 #include "support/debug.h"
41 #include "support/gettext.h"
42 #include "support/docstream.h"
43 #include "support/lstrings.h"
51 using support::bformat;
53 //////////////////////////////////////////////////////////////////////
55 class InsetLabelBox : public InsetMathNest {
58 InsetLabelBox(MathAtom const & atom, docstring label,
59 MathMacroTemplate const & parent, bool frame = false);
60 InsetLabelBox(docstring label, MathMacroTemplate const & parent,
63 void metrics(MetricsInfo & mi, Dimension & dim) const;
65 void draw(PainterInfo &, int x, int y) const;
69 MathMacroTemplate const & parent_;
71 Inset * clone() const;
73 docstring const label_;
79 InsetLabelBox::InsetLabelBox(MathAtom const & atom, docstring label,
80 MathMacroTemplate const & parent, bool frame)
81 : InsetMathNest(1), parent_(parent), label_(label), frame_(frame)
83 cell(0).insert(0, atom);
87 InsetLabelBox::InsetLabelBox(docstring label,
88 MathMacroTemplate const & parent, bool frame)
89 : InsetMathNest(1), parent_(parent), label_(label), frame_(frame)
94 Inset * InsetLabelBox::clone() const
96 return new InsetLabelBox(*this);
100 void InsetLabelBox::metrics(MetricsInfo & mi, Dimension & dim) const
103 cell(0).metrics(mi, dim);
112 // adjust to common height in main metrics phase
113 if (!parent_.premetrics()) {
114 dim.asc = max(dim.asc, parent_.commonLabelBoxAscent());
115 dim.des = max(dim.des, parent_.commonLabelBoxDescent());
119 if (parent_.editing(mi.base.bv) && label_.length() > 0) {
121 FontInfo font = sane_font;
122 font.setSize(FONT_SIZE_TINY);
123 font.setColor(Color_mathmacrolabel);
125 // make space for label and box
126 int lwid = mathed_string_width(font, label_);
129 math_font_max_dim(font, maxasc, maxdes);
131 dim.wid = max(dim.wid, lwid + 2);
133 // space for the label
134 if (!parent_.premetrics())
135 dim.des += maxasc + maxdes + 1;
140 void InsetLabelBox::draw(PainterInfo & pi, int x, int y) const
142 Dimension const dim = dimension(*pi.base.bv);
143 Dimension const cdim = cell(0).dimension(*pi.base.bv);
146 cell(0).draw(pi, x + (dim.wid - cdim.wid) / 2, y);
149 if (parent_.editing(pi.base.bv) && label_.length() > 0) {
151 FontInfo font = sane_font;
152 font.setSize(FONT_SIZE_TINY);
153 font.setColor(Color_mathmacrolabel);
155 // make space for label and box
156 int lwid = mathed_string_width(font, label_);
159 math_font_max_dim(font, maxasc, maxdes);
162 pi.pain.text(x + (dim.wid - lwid) / 2, y + dim.des - maxdes, label_, font);
164 pi.pain.text(x, y + dim.des - maxdes, label_, font);
168 int boxHeight = parent_.commonLabelBoxAscent() + parent_.commonLabelBoxDescent();
170 pi.pain.rectangle(x + 1, y - dim.ascent() + 1,
171 dim.wid - 2, boxHeight - 2,
177 //////////////////////////////////////////////////////////////////////
179 class DisplayLabelBox : public InsetLabelBox {
182 DisplayLabelBox(MathAtom const & atom, docstring label,
183 MathMacroTemplate const & parent);
186 void metrics(MetricsInfo & mi, Dimension & dim) const;
188 void draw(PainterInfo &, int x, int y) const;
192 Inset * clone() const;
196 DisplayLabelBox::DisplayLabelBox(MathAtom const & atom,
198 MathMacroTemplate const & parent)
199 : InsetLabelBox(atom, label, parent, true)
205 Inset * DisplayLabelBox::clone() const
207 return new DisplayLabelBox(*this);
211 void DisplayLabelBox::metrics(MetricsInfo & mi, Dimension & dim) const
213 InsetLabelBox::metrics(mi, dim);
214 if (!parent_.editing(mi.base.bv)
215 && parent_.cell(parent_.displayIdx()).empty()) {
223 void DisplayLabelBox::draw(PainterInfo & pi, int x, int y) const
225 if (parent_.editing(pi.base.bv)
226 || !parent_.cell(parent_.displayIdx()).empty()) {
227 InsetLabelBox::draw(pi, x, y);
229 bool enabled = pi.pain.isDrawingEnabled();
230 pi.pain.setDrawingEnabled(false);
231 InsetLabelBox::draw(pi, x, y);
232 pi.pain.setDrawingEnabled(enabled);
237 //////////////////////////////////////////////////////////////////////
239 class InsetMathWrapper : public InsetMath {
242 InsetMathWrapper(MathData const * value) : value_(value) {}
244 void metrics(MetricsInfo & mi, Dimension & dim) const;
246 void draw(PainterInfo &, int x, int y) const;
250 Inset * clone() const;
252 MathData const * value_;
256 Inset * InsetMathWrapper::clone() const
258 return new InsetMathWrapper(*this);
262 void InsetMathWrapper::metrics(MetricsInfo & mi, Dimension & dim) const
264 value_->metrics(mi, dim);
265 //metricsMarkers2(dim);
269 void InsetMathWrapper::draw(PainterInfo & pi, int x, int y) const
271 value_->draw(pi, x, y);
272 //drawMarkers(pi, x, y);
276 ///////////////////////////////////////////////////////////////////////
277 class InsetColoredCell : public InsetMathNest {
280 InsetColoredCell(ColorCode min, ColorCode max);
282 InsetColoredCell(ColorCode min, ColorCode max, MathAtom const & atom);
284 void draw(PainterInfo &, int x, int y) const;
286 void metrics(MetricsInfo & mi, Dimension & dim) const;
290 Inset * clone() const;
298 InsetColoredCell::InsetColoredCell(ColorCode min, ColorCode max)
299 : InsetMathNest(1), min_(min), max_(max)
304 InsetColoredCell::InsetColoredCell(ColorCode min, ColorCode max, MathAtom const & atom)
305 : InsetMathNest(1), min_(min), max_(max)
307 cell(0).insert(0, atom);
311 Inset * InsetColoredCell::clone() const
313 return new InsetColoredCell(*this);
317 void InsetColoredCell::metrics(MetricsInfo & mi, Dimension & dim) const
319 cell(0).metrics(mi, dim);
323 void InsetColoredCell::draw(PainterInfo & pi, int x, int y) const
325 pi.pain.enterMonochromeMode(min_, max_);
326 cell(0).draw(pi, x, y);
327 pi.pain.leaveMonochromeMode();
331 ///////////////////////////////////////////////////////////////////////
333 class InsetNameWrapper : public InsetMathWrapper {
336 InsetNameWrapper(MathData const * value, MathMacroTemplate const & parent);
338 void metrics(MetricsInfo & mi, Dimension & dim) const;
340 void draw(PainterInfo &, int x, int y) const;
344 MathMacroTemplate const & parent_;
346 Inset * clone() const;
350 InsetNameWrapper::InsetNameWrapper(MathData const * value,
351 MathMacroTemplate const & parent)
352 : InsetMathWrapper(value), parent_(parent)
357 Inset * InsetNameWrapper::clone() const
359 return new InsetNameWrapper(*this);
363 void InsetNameWrapper::metrics(MetricsInfo & mi, Dimension & dim) const
365 InsetMathWrapper::metrics(mi, dim);
366 dim.wid += mathed_string_width(mi.base.font, from_ascii("\\"));
370 void InsetNameWrapper::draw(PainterInfo & pi, int x, int y) const
373 PainterInfo namepi = pi;
374 if (parent_.validMacro())
375 namepi.base.font.setColor(Color_latex);
377 namepi.base.font.setColor(Color_error);
380 pi.pain.text(x, y, from_ascii("\\"), namepi.base.font);
381 x += mathed_string_width(namepi.base.font, from_ascii("\\"));
384 InsetMathWrapper::draw(namepi, x, y);
388 ///////////////////////////////////////////////////////////////////////
391 MathMacroTemplate::MathMacroTemplate()
392 : InsetMathNest(3), numargs_(0), argsInLook_(0), optionals_(0),
393 type_(MacroTypeNewcommand), lookOutdated_(true)
399 MathMacroTemplate::MathMacroTemplate(docstring const & name, int numargs,
400 int optionals, MacroType type,
401 vector<MathData> const & optionalValues,
402 MathData const & def, MathData const & display)
403 : InsetMathNest(optionals + 3), numargs_(numargs), argsInLook_(numargs),
404 optionals_(optionals), optionalValues_(optionalValues),
405 type_(type), lookOutdated_(true)
410 lyxerr << "MathMacroTemplate::MathMacroTemplate: wrong # of arguments: "
413 asArray(name, cell(0));
414 optionalValues_.resize(9);
415 for (int i = 0; i < optionals_; ++i)
416 cell(optIdx(i)) = optionalValues_[i];
417 cell(defIdx()) = def;
418 cell(displayIdx()) = display;
424 MathMacroTemplate::MathMacroTemplate(docstring const & str)
425 : InsetMathNest(3), numargs_(0), optionals_(0),
426 type_(MacroTypeNewcommand), lookOutdated_(true)
431 mathed_parse_cell(ar, str);
432 if (ar.size() != 1 || !ar[0]->asMacroTemplate()) {
433 lyxerr << "Cannot read macro from '" << ar << "'" << endl;
434 asArray(from_ascii("invalidmacro"), cell(0));
435 // FIXME: The macro template does not make sense after this.
436 // The whole parsing should not be in a constructor which
437 // has no chance to report failure.
440 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) const
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(new InsetLabelBox(_("Name"), *this, false)));
481 MathData & nameData = look_[look_.size() - 1].nucleus()->cell(0);
482 nameData.push_back(MathAtom(new InsetNameWrapper(&cell(0), *this)));
486 if (optionals_ > 0) {
487 look_.push_back(MathAtom(new InsetLabelBox(_("optional"), *this, false)));
489 MathData * optData = &look_[look_.size() - 1].nucleus()->cell(0);
490 for (; i < optionals_; ++i) {
491 // color it light grey, if it is to be removed when the cursor leaves
492 if (i == argsInLook_) {
493 optData->push_back(MathAtom(
494 new InsetColoredCell(Color_mathbg, Color_mathmacrooldarg)));
495 optData = &(*optData)[optData->size() - 1].nucleus()->cell(0);
498 optData->push_back(MathAtom(new InsetMathChar('[')));
499 optData->push_back(MathAtom(new InsetMathWrapper(&cell(1 + i))));
500 optData->push_back(MathAtom(new InsetMathChar(']')));
505 for (; i < numargs_; ++i) {
507 arg.push_back(MathAtom(new MathMacroArgument(i + 1)));
508 if (i >= argsInLook_) {
509 look_.push_back(MathAtom(new InsetColoredCell(
510 Color_mathbg, Color_mathmacrooldarg,
511 MathAtom(new InsetMathBrace(arg)))));
513 look_.push_back(MathAtom(new InsetMathBrace(arg)));
515 for (; i < argsInLook_; ++i) {
517 arg.push_back(MathAtom(new MathMacroArgument(i + 1)));
518 look_.push_back(MathAtom(new InsetColoredCell(
519 Color_mathbg, Color_mathmacronewarg,
520 MathAtom(new InsetMathBrace(arg)))));
524 look_.push_back(MathAtom(new InsetMathChar(':')));
525 look_.push_back(MathAtom(new InsetMathChar('=')));
528 look_.push_back(MathAtom(
529 new InsetLabelBox(MathAtom(
530 new InsetMathWrapper(&cell(defIdx()))), _("TeX"), *this, true)));
533 look_.push_back(MathAtom(
534 new DisplayLabelBox(MathAtom(
535 new InsetMathWrapper(&cell(displayIdx()))), _("LyX"), *this)));
539 void MathMacroTemplate::metrics(MetricsInfo & mi, Dimension & dim) const
541 FontSetChanger dummy1(mi.base, from_ascii("mathnormal"));
542 StyleChanger dummy2(mi.base, LM_ST_TEXT);
545 MacroData const * macro = 0;
547 macro = mi.macrocontext.get(name());
549 // updateToContext() - avoids another lookup
550 redefinition_ = macro != 0;
554 int argsInDef = maxArgumentInDefinition();
555 if (lookOutdated_ || argsInDef != argsInLook_) {
556 lookOutdated_ = false;
557 createLook(argsInDef);
560 /// metrics for inset contents
564 // first phase, premetric:
566 look_.metrics(mi, dim);
567 labelBoxAscent_ = dim.asc;
568 labelBoxDescent_ = dim.des;
570 // second phase, main metric:
572 look_.metrics(mi, dim);
581 setDimCache(mi, dim);
585 void MathMacroTemplate::draw(PainterInfo & pi, int x, int y) const
587 FontSetChanger dummy1(pi.base, from_ascii("mathnormal"));
588 StyleChanger dummy2(pi.base, LM_ST_TEXT);
590 setPosCache(pi, x, y);
591 Dimension const dim = dimension(*pi.base.bv);
594 int const a = y - dim.asc + 1;
595 int const w = dim.wid - 2;
596 int const h = dim.height() - 2;
597 pi.pain.rectangle(x, a, w, h, Color_mathframe);
599 // just to be sure: set some dummy values for coord cache
600 for (idx_type i = 0; i < nargs(); ++i)
601 cell(i).setXY(*pi.base.bv, x, y);
604 look_.draw(pi, x + 3, y);
608 void MathMacroTemplate::edit(Cursor & cur, bool front, EntryDirection entry_from)
611 cur.updateFlags(Update::SinglePar);
612 InsetMathNest::edit(cur, front, entry_from);
616 bool MathMacroTemplate::notifyCursorLeaves(Cursor const & old, Cursor & cur)
618 // find this in cursor old
619 Cursor insetCur = old;
620 int scriptSlice = insetCur.find(this);
621 BOOST_ASSERT(scriptSlice != -1);
622 insetCur.cutOff(scriptSlice);
624 commitEditChanges(insetCur);
626 cur.updateFlags(Update::Force);
627 return InsetMathNest::notifyCursorLeaves(old, cur);
631 void MathMacroTemplate::removeArguments(Cursor & cur, int from, int to) {
632 for (DocIterator it = doc_iterator_begin(*this); it; it.forwardChar()) {
635 if (it.nextInset()->lyxCode() != MATHMACROARG_CODE)
637 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
638 int n = arg->number() - 1;
639 if (from <= n && n <= to) {
640 int cellSlice = cur.find(it.cell());
641 if (cellSlice != -1 && cur[cellSlice].pos() > it.pos())
642 --cur[cellSlice].pos();
644 it.cell().erase(it.pos());
652 void MathMacroTemplate::shiftArguments(size_t from, int by) {
653 for (DocIterator it = doc_iterator_begin(*this); it; it.forwardChar()) {
656 if (it.nextInset()->lyxCode() != MATHMACROARG_CODE)
658 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
659 if (arg->number() >= from + 1)
660 arg->setNumber(arg->number() + by);
667 int MathMacroTemplate::maxArgumentInDefinition() const
670 MathMacroTemplate * nonConst = const_cast<MathMacroTemplate *>(this);
671 DocIterator it = doc_iterator_begin(*nonConst);
673 for (; it; it.forwardChar()) {
676 if (it.nextInset()->lyxCode() != MATHMACROARG_CODE)
678 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
679 maxArg = std::max(int(arg->number()), maxArg);
685 void MathMacroTemplate::insertMissingArguments(int maxArg)
687 bool found[9] = { false, false, false, false, false, false, false, false, false };
688 idx_type idx = cell(displayIdx()).empty() ? defIdx() : displayIdx();
690 // search for #n macros arguments
691 DocIterator it = doc_iterator_begin(*this);
693 for (; it && it[0].idx() == idx; it.forwardChar()) {
696 if (it.nextInset()->lyxCode() != MATHMACROARG_CODE)
698 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
699 found[arg->number() - 1] = true;
703 for (int i = 0; i < maxArg; ++i) {
707 cell(idx).push_back(MathAtom(new MathMacroArgument(i + 1)));
712 void MathMacroTemplate::changeArity(Cursor & cur, int newNumArg)
714 // remove parameter which do not appear anymore in the definition
715 for (int i = numargs_; i > newNumArg; --i)
716 removeParameter(cur, numargs_ - 1, false);
718 // add missing parameter
719 for (int i = numargs_; i < newNumArg; ++i)
720 insertParameter(cur, numargs_, false, false);
724 void MathMacroTemplate::commitEditChanges(Cursor & cur)
726 int argsInDef = maxArgumentInDefinition();
727 if (argsInDef != numargs_) {
728 cur.recordUndoFullDocument();
729 changeArity(cur, argsInDef);
731 insertMissingArguments(argsInDef);
735 // FIXME: factorize those functions here with a functional style, maybe using Boost's function
738 void fixMacroInstancesAddRemove(Cursor const & from, docstring const & name, int n, bool insert) {
741 for (; dit; dit.forwardPos()) {
742 // only until a macro is redefined
743 if (dit.inset().lyxCode() == MATHMACRO_CODE) {
744 MathMacroTemplate const & macroTemplate
745 = static_cast<MathMacroTemplate const &>(dit.inset());
746 if (macroTemplate.name() == name)
750 // in front of macro instance?
751 Inset * inset = dit.nextInset();
754 InsetMath * insetMath = inset->asInsetMath();
758 MathMacro * macro = insetMath->asMacro();
759 if (macro && macro->name() == name && macro->folded()) {
760 // found macro instance
762 macro->insertArgument(n);
764 macro->removeArgument(n);
770 void fixMacroInstancesOptional(Cursor const & from, docstring const & name, int optionals) {
773 for (; dit; dit.forwardPos()) {
774 // only until a macro is redefined
775 if (dit.inset().lyxCode() == MATHMACRO_CODE) {
776 MathMacroTemplate const & macroTemplate
777 = static_cast<MathMacroTemplate const &>(dit.inset());
778 if (macroTemplate.name() == name)
782 // in front of macro instance?
783 Inset * inset = dit.nextInset();
786 InsetMath * insetMath = inset->asInsetMath();
789 MathMacro * macro = insetMath->asMacro();
790 if (macro && macro->name() == name && macro->folded()) {
791 // found macro instance
792 macro->setOptionals(optionals);
799 void fixMacroInstancesFunctional(Cursor const & from,
800 docstring const & name, F & fix) {
803 for (; dit; dit.forwardPos()) {
804 // only until a macro is redefined
805 if (dit.inset().lyxCode() == MATHMACRO_CODE) {
806 MathMacroTemplate const & macroTemplate
807 = static_cast<MathMacroTemplate const &>(dit.inset());
808 if (macroTemplate.name() == name)
812 // in front of macro instance?
813 Inset * inset = dit.nextInset();
816 InsetMath * insetMath = inset->asInsetMath();
819 MathMacro * macro = insetMath->asMacro();
820 if (macro && macro->name() == name && macro->folded())
826 void MathMacroTemplate::insertParameter(Cursor & cur, int pos, bool greedy, bool addarg)
828 if (pos <= numargs_ && pos >= optionals_ && numargs_ < 9) {
833 shiftArguments(pos, 1);
835 cell(defIdx()).push_back(MathAtom(new MathMacroArgument(pos + 1)));
836 if (!cell(displayIdx()).empty())
837 cell(displayIdx()).push_back(MathAtom(new MathMacroArgument(pos + 1)));
842 dit.leaveInset(*this);
843 // TODO: this was dit.forwardPosNoDescend before. Check that this is the same
844 dit.top().forwardPos();
846 // fix macro instances
847 fixMacroInstancesAddRemove(dit, name(), pos, true);
855 void MathMacroTemplate::removeParameter(Cursor & cur, int pos, bool greedy)
857 if (pos < numargs_ && pos >= 0) {
859 removeArguments(cur, pos, pos);
860 shiftArguments(pos + 1, -1);
862 // removed optional parameter?
863 if (pos < optionals_) {
865 optionalValues_[pos] = cell(optIdx(pos));
866 cells_.erase(cells_.begin() + optIdx(pos));
869 int macroSlice = cur.find(this);
870 if (macroSlice != -1) {
871 if (cur[macroSlice].idx() == optIdx(pos)) {
872 cur.cutOff(macroSlice);
873 cur[macroSlice].idx() = 1;
874 cur[macroSlice].pos() = 0;
875 } else if (cur[macroSlice].idx() > optIdx(pos))
876 --cur[macroSlice].idx();
881 // fix macro instances
882 //boost::function<void(MathMacro *)> fix = _1->insertArgument(n);
883 //fixMacroInstancesFunctional(dit, name(), fix);
885 dit.leaveInset(*this);
886 // TODO: this was dit.forwardPosNoDescend before. Check that this is the same
887 dit.top().forwardPos();
888 fixMacroInstancesAddRemove(dit, name(), pos, false);
896 void MathMacroTemplate::makeOptional(Cursor & cur) {
897 if (numargs_ > 0 && optionals_ < numargs_) {
899 cells_.insert(cells_.begin() + optIdx(optionals_ - 1), optionalValues_[optionals_ - 1]);
901 int macroSlice = cur.find(this);
902 if (macroSlice != -1 && cur[macroSlice].idx() >= optIdx(optionals_ - 1))
903 ++cur[macroSlice].idx();
905 // fix macro instances
907 dit.leaveInset(*this);
908 // TODO: this was dit.forwardPosNoDescend before. Check that this is the same
909 dit.top().forwardPos();
910 fixMacroInstancesOptional(dit, name(), optionals_);
917 void MathMacroTemplate::makeNonOptional(Cursor & cur) {
918 if (numargs_ > 0 && optionals_ > 0) {
921 // store default value for later if the user changes his mind
922 optionalValues_[optionals_] = cell(optIdx(optionals_));
923 cells_.erase(cells_.begin() + optIdx(optionals_));
926 int macroSlice = cur.find(this);
927 if (macroSlice != -1) {
928 if (cur[macroSlice].idx() > optIdx(optionals_))
929 --cur[macroSlice].idx();
930 else if (cur[macroSlice].idx() == optIdx(optionals_)) {
931 cur.cutOff(macroSlice);
932 cur[macroSlice].idx() = optIdx(optionals_);
933 cur[macroSlice].pos() = 0;
937 // fix macro instances
939 dit.leaveInset(*this);
940 // TODO: this was dit.forwardPosNoDescend before. Check that this is the same
941 dit.top().forwardPos();
942 fixMacroInstancesOptional(dit, name(), optionals_);
949 void MathMacroTemplate::doDispatch(Cursor & cur, FuncRequest & cmd)
951 string const arg = to_utf8(cmd.argument());
952 switch (cmd.action) {
954 case LFUN_MATH_MACRO_ADD_PARAM:
956 commitEditChanges(cur);
957 cur.recordUndoFullDocument();
958 size_t pos = numargs_;
960 pos = (size_t)convert<int>(arg) - 1; // it is checked for >=0 in getStatus
961 insertParameter(cur, pos);
966 case LFUN_MATH_MACRO_REMOVE_PARAM:
968 commitEditChanges(cur);
969 cur.recordUndoFullDocument();
970 size_t pos = numargs_ - 1;
972 pos = (size_t)convert<int>(arg) - 1; // it is checked for >=0 in getStatus
973 removeParameter(cur, pos);
977 case LFUN_MATH_MACRO_APPEND_GREEDY_PARAM:
979 commitEditChanges(cur);
980 cur.recordUndoFullDocument();
981 insertParameter(cur, numargs_, true);
985 case LFUN_MATH_MACRO_REMOVE_GREEDY_PARAM:
987 commitEditChanges(cur);
988 cur.recordUndoFullDocument();
989 removeParameter(cur, numargs_ - 1, true);
993 case LFUN_MATH_MACRO_MAKE_OPTIONAL:
994 commitEditChanges(cur);
995 cur.recordUndoFullDocument();
999 case LFUN_MATH_MACRO_MAKE_NONOPTIONAL:
1000 commitEditChanges(cur);
1001 cur.recordUndoFullDocument();
1002 makeNonOptional(cur);
1005 case LFUN_MATH_MACRO_ADD_OPTIONAL_PARAM:
1007 commitEditChanges(cur);
1008 cur.recordUndoFullDocument();
1009 insertParameter(cur, optionals_);
1014 case LFUN_MATH_MACRO_REMOVE_OPTIONAL_PARAM:
1015 if (optionals_ > 0) {
1016 commitEditChanges(cur);
1017 cur.recordUndoFullDocument();
1018 removeParameter(cur, optionals_ - 1);
1021 case LFUN_MATH_MACRO_ADD_GREEDY_OPTIONAL_PARAM:
1022 if (numargs_ == optionals_) {
1023 commitEditChanges(cur);
1024 cur.recordUndoFullDocument();
1025 insertParameter(cur, 0, true);
1031 InsetMathNest::doDispatch(cur, cmd);
1037 bool MathMacroTemplate::getStatus(Cursor & /*cur*/, FuncRequest const & cmd,
1038 FuncStatus & flag) const
1041 string const arg = to_utf8(cmd.argument());
1042 switch (cmd.action) {
1043 case LFUN_MATH_MACRO_ADD_PARAM: {
1044 int num = numargs_ + 1;
1045 if (arg.size() != 0)
1046 num = convert<int>(arg);
1047 bool on = (num >= optionals_
1048 && numargs_ < 9 && num <= numargs_ + 1);
1053 case LFUN_MATH_MACRO_APPEND_GREEDY_PARAM:
1054 flag.enabled(numargs_ < 9);
1057 case LFUN_MATH_MACRO_REMOVE_PARAM: {
1059 if (arg.size() != 0)
1060 num = convert<int>(arg);
1061 flag.enabled(num >= 1 && num <= numargs_);
1065 case LFUN_MATH_MACRO_MAKE_OPTIONAL:
1066 flag.enabled(numargs_ > 0
1067 && optionals_ < numargs_
1068 && type_ != MacroTypeDef);
1071 case LFUN_MATH_MACRO_MAKE_NONOPTIONAL:
1072 flag.enabled(optionals_ > 0
1073 && type_ != MacroTypeDef);
1076 case LFUN_MATH_MACRO_ADD_OPTIONAL_PARAM:
1077 flag.enabled(numargs_ < 9);
1080 case LFUN_MATH_MACRO_REMOVE_OPTIONAL_PARAM:
1081 flag.enabled(optionals_ > 0);
1084 case LFUN_MATH_MACRO_ADD_GREEDY_OPTIONAL_PARAM:
1085 flag.enabled(numargs_ == 0
1086 && type_ != MacroTypeDef);
1089 case LFUN_IN_MATHMACROTEMPLATE:
1101 void MathMacroTemplate::read(Lexer & lex)
1104 mathed_parse_cell(ar, lex.getStream());
1105 if (ar.size() != 1 || !ar[0]->asMacroTemplate()) {
1106 lyxerr << "Cannot read macro from '" << ar << "'" << endl;
1107 lyxerr << "Read: " << to_utf8(asString(ar)) << endl;
1110 operator=( *(ar[0]->asMacroTemplate()) );
1116 void MathMacroTemplate::write(ostream & os) const
1118 odocstringstream oss;
1119 WriteStream wi(oss, false, false);
1120 oss << "FormulaMacro\n";
1122 os << to_utf8(oss.str());
1126 void MathMacroTemplate::write(WriteStream & os) const
1132 void MathMacroTemplate::write(WriteStream & os, bool overwriteRedefinition) const
1135 if (optionals_ > 0) {
1136 // macros with optionals use the xargs package, e.g.:
1137 // \newcommandx{\foo}[2][usedefault, addprefix=\global,1=default]{#1,#2}
1138 if (redefinition_ && !overwriteRedefinition)
1139 os << "\\renewcommandx";
1141 os << "\\newcommandx";
1143 os << "\\" << name().c_str()
1144 << "[" << numargs_ << "]"
1145 << "[usedefault, addprefix=\\global";
1146 for (int i = 0; i < optionals_; ++i) {
1147 docstring optValue = asString(cell(optIdx(i)));
1148 if (optValue.find(']') != docstring::npos
1149 || optValue.find(',') != docstring::npos)
1150 os << ", " << i + 1 << "="
1151 << "{" << cell(optIdx(i)) << "}";
1153 os << ", " << i + 1 << "="
1158 // macros without optionals use standard _global_ \def macros:
1159 // \global\def\foo#1#2{#1,#2}
1160 os << "\\global\\def\\" << name().c_str();
1161 docstring param = from_ascii("#0");
1162 for (int i = 1; i <= numargs_; ++i) {
1168 // in LyX output we use some pseudo syntax which is implementation
1169 // independent, e.g.
1170 // \newcommand{\foo}[2][default}{#1,#2}
1171 if (redefinition_ && !overwriteRedefinition)
1172 os << "\\renewcommand";
1174 os << "\\newcommand";
1175 os << "{\\" << name().c_str() << '}';
1177 os << '[' << numargs_ << ']';
1179 for (int i = 0; i < optionals_; ++i) {
1180 docstring optValue = asString(cell(optIdx(i)));
1181 if (optValue.find(']') != docstring::npos)
1182 os << "[{" << cell(optIdx(i)) << "}]";
1184 os << "[" << cell(optIdx(i)) << "]";
1188 os << "{" << cell(defIdx()) << "}";
1191 // writing .tex. done.
1194 // writing .lyx, write special .tex export only if necessary
1195 if (!cell(displayIdx()).empty())
1196 os << "\n{" << cell(displayIdx()) << '}';
1201 int MathMacroTemplate::plaintext(odocstream & os,
1202 OutputParams const &) const
1204 static docstring const str = '[' + buffer().B_("math macro") + ']';
1211 bool MathMacroTemplate::validName() const
1213 docstring n = name();
1219 // converting back and force doesn't swallow anything?
1222 if (asString(ma) != n)
1225 // valid characters?
1226 for (size_t i = 0; i < n.size(); ++i) {
1227 if (!(n[i] >= 'a' && n[i] <= 'z')
1228 && !(n[i] >= 'A' && n[i] <= 'Z')
1237 bool MathMacroTemplate::validMacro() const
1243 bool MathMacroTemplate::fixNameAndCheckIfValid()
1245 // check all the characters/insets in the name cell
1247 MathData & data = cell(0);
1248 while (i < data.size()) {
1249 InsetMathChar const * cinset = data[i]->asCharInset();
1251 // valid character in [a-zA-Z]?
1252 char_type c = cinset->getChar();
1253 if ((c >= 'a' && c <= 'z')
1254 || (c >= 'A' && c <= 'Z')) {
1264 // now it should be valid if anything in the name survived
1265 return data.size() > 0;
1269 void MathMacroTemplate::validate(LaTeXFeatures & features) const
1271 // we need global optional macro arguments. They are not available
1272 // with \def, and \newcommand does not support global macros. So we
1273 // are bound to xargs also for the single-optional-parameter case.
1275 features.require("xargs");
1278 void MathMacroTemplate::getDefaults(vector<docstring> & defaults) const
1280 defaults.resize(numargs_);
1281 for (int i = 0; i < optionals_; ++i)
1282 defaults[i] = asString(cell(optIdx(i)));
1286 docstring MathMacroTemplate::definition() const
1288 return asString(cell(defIdx()));
1292 docstring MathMacroTemplate::displayDefinition() const
1294 return asString(cell(displayIdx()));
1298 size_t MathMacroTemplate::numArgs() const
1304 size_t MathMacroTemplate::numOptionals() const
1310 void MathMacroTemplate::infoize(odocstream & os) const
1312 os << "Math Macro: \\" << name();
1316 docstring MathMacroTemplate::contextMenu(BufferView const &, int, int) const
1318 return from_ascii("context-math-macro-definition");