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_(0),
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(bool editing) 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 for (; i < optionals_; ++i) {
490 MathData * optData = &look_[look_.size() - 1].nucleus()->cell(0);
492 // color it red, if it is to be remove when the cursor leaves
493 if (optionals_ > argsInLook_) {
494 optData->push_back(MathAtom(
495 new InsetColoredCell(Color_mathbg, Color_mathmacrooldarg)));
496 optData = &(*optData)[0].nucleus()->cell(0);
499 optData->push_back(MathAtom(new InsetMathChar('[')));
500 optData->push_back(MathAtom(new InsetMathWrapper(&cell(1 + i))));
501 optData->push_back(MathAtom(new InsetMathChar(']')));
506 for (; i < numargs_; ++i) {
508 arg.push_back(MathAtom(new MathMacroArgument(i + 1)));
509 if (i >= argsInLook_) {
510 look_.push_back(MathAtom(new InsetColoredCell(
511 Color_mathbg, Color_mathmacrooldarg,
512 MathAtom(new InsetMathBrace(arg)))));
514 look_.push_back(MathAtom(new InsetMathBrace(arg)));
516 for (; i < argsInLook_; ++i) {
518 arg.push_back(MathAtom(new MathMacroArgument(i + 1)));
519 look_.push_back(MathAtom(new InsetColoredCell(
520 Color_mathbg, Color_mathmacronewarg,
521 MathAtom(new InsetMathBrace(arg)))));
525 look_.push_back(MathAtom(new InsetMathChar(':')));
526 look_.push_back(MathAtom(new InsetMathChar('=')));
529 look_.push_back(MathAtom(
530 new InsetLabelBox(MathAtom(
531 new InsetMathWrapper(&cell(defIdx()))), _("TeX"), *this, true)));
534 look_.push_back(MathAtom(
535 new DisplayLabelBox(MathAtom(
536 new InsetMathWrapper(&cell(displayIdx()))), _("LyX"), *this)));
540 void MathMacroTemplate::metrics(MetricsInfo & mi, Dimension & dim) const
542 FontSetChanger dummy1(mi.base, from_ascii("mathnormal"));
543 StyleChanger dummy2(mi.base, LM_ST_TEXT);
546 MacroData const * macro = 0;
548 macro = mi.macrocontext.get(name());
550 // updateToContext() - avoids another lookup
551 redefinition_ = macro != 0;
555 int argsInDef = maxArgumentInDefinition();
556 if (lookOutdated_ || argsInDef != argsInLook_) {
557 lookOutdated_ = false;
558 createLook(argsInDef);
561 /// metrics for inset contents
565 // first phase, premetric:
567 look_.metrics(mi, dim);
568 labelBoxAscent_ = dim.asc;
569 labelBoxDescent_ = dim.des;
571 // second phase, main metric:
573 look_.metrics(mi, dim);
582 setDimCache(mi, dim);
586 void MathMacroTemplate::draw(PainterInfo & pi, int x, int y) const
588 FontSetChanger dummy1(pi.base, from_ascii("mathnormal"));
589 StyleChanger dummy2(pi.base, LM_ST_TEXT);
591 setPosCache(pi, x, y);
592 Dimension const dim = dimension(*pi.base.bv);
595 int const a = y - dim.asc + 1;
596 int const w = dim.wid - 2;
597 int const h = dim.height() - 2;
598 pi.pain.rectangle(x, a, w, h, Color_mathframe);
600 // just to be sure: set some dummy values for coord cache
601 for (idx_type i = 0; i < nargs(); ++i) {
602 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::Force);
614 InsetMathNest::edit(cur, front, entry_from);
618 bool MathMacroTemplate::notifyCursorLeaves(Cursor const & old, Cursor & cur)
620 commitEditChanges(cur);
622 cur.updateFlags(Update::Force);
623 return InsetMathNest::notifyCursorLeaves(old, cur);
627 void MathMacroTemplate::removeArguments(Cursor & cur, int from, int to) {
628 for (DocIterator it = doc_iterator_begin(*this); it; it.forwardChar()) {
631 if (it.nextInset()->lyxCode() != MATHMACROARG_CODE)
633 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
634 int n = arg->number() - 1;
635 if (from <= n && n <= to) {
636 int cellSlice = cur.find(it.cell());
637 if (cellSlice != -1 && cur[cellSlice].pos() > it.pos())
638 --cur[cellSlice].pos();
640 it.cell().erase(it.pos());
648 void MathMacroTemplate::shiftArguments(size_t from, int by) {
649 for (DocIterator it = doc_iterator_begin(*this); it; it.forwardChar()) {
652 if (it.nextInset()->lyxCode() != MATHMACROARG_CODE)
654 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
655 if (arg->number() >= from + 1)
656 arg->setNumber(arg->number() + by);
663 int MathMacroTemplate::maxArgumentInDefinition() const
666 MathMacroTemplate * nonConst = const_cast<MathMacroTemplate *>(this);
667 DocIterator it = doc_iterator_begin(*nonConst);
669 for (; it; it.forwardChar()) {
672 if (it.nextInset()->lyxCode() != MATHMACROARG_CODE)
674 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
675 maxArg = std::max(int(arg->number()), maxArg);
681 void MathMacroTemplate::insertMissingArguments(int maxArg)
683 bool found[9] = { false, false, false, false, false, false, false, false, false };
684 idx_type idx = cell(displayIdx()).empty() ? defIdx() : displayIdx();
686 // search for #n macros arguments
687 DocIterator it = doc_iterator_begin(*this);
689 for (; it && it[0].idx() == idx; it.forwardChar()) {
692 if (it.nextInset()->lyxCode() != MATHMACROARG_CODE)
694 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
695 found[arg->number() - 1] = true;
699 for (int i = 0; i < maxArg; ++i) {
703 cell(idx).push_back(MathAtom(new MathMacroArgument(i + 1)));
708 void MathMacroTemplate::changeArity(Cursor & cur, int newNumArg)
710 // remove parameter which do not appear anymore in the definition
711 for (int i = numargs_; i > newNumArg; --i)
712 removeParameter(cur, numargs_ - 1, false);
714 // add missing parameter
715 for (int i = numargs_; i < newNumArg; ++i)
716 insertParameter(cur, numargs_, false, false);
720 void MathMacroTemplate::commitEditChanges(Cursor & cur)
722 int argsInDef = maxArgumentInDefinition();
723 if (argsInDef != numargs_) {
724 cur.recordUndoFullDocument();
725 changeArity(cur, argsInDef);
727 insertMissingArguments(argsInDef);
731 // FIXME: factorize those functions here with a functional style, maybe using Boost's function
734 void fixMacroInstancesAddRemove(Cursor const & from, docstring const & name, int n, bool insert) {
737 for (; dit; dit.forwardPos()) {
738 // only until a macro is redefined
739 if (dit.inset().lyxCode() == MATHMACRO_CODE) {
740 MathMacroTemplate const & macroTemplate
741 = static_cast<MathMacroTemplate const &>(dit.inset());
742 if (macroTemplate.name() == name)
746 // in front of macro instance?
747 Inset * inset = dit.nextInset();
750 InsetMath * insetMath = inset->asInsetMath();
754 MathMacro * macro = insetMath->asMacro();
755 if (macro && macro->name() == name && macro->folded()) {
756 // found macro instance
758 macro->insertArgument(n);
760 macro->removeArgument(n);
766 void fixMacroInstancesOptional(Cursor const & from, docstring const & name, int optionals) {
769 for (; dit; dit.forwardPos()) {
770 // only until a macro is redefined
771 if (dit.inset().lyxCode() == MATHMACRO_CODE) {
772 MathMacroTemplate const & macroTemplate
773 = static_cast<MathMacroTemplate const &>(dit.inset());
774 if (macroTemplate.name() == name)
778 // in front of macro instance?
779 Inset * inset = dit.nextInset();
782 InsetMath * insetMath = inset->asInsetMath();
785 MathMacro * macro = insetMath->asMacro();
786 if (macro && macro->name() == name && macro->folded()) {
787 // found macro instance
788 macro->setOptionals(optionals);
795 void fixMacroInstancesFunctional(Cursor const & from,
796 docstring const & name, F & fix) {
799 for (; dit; dit.forwardPos()) {
800 // only until a macro is redefined
801 if (dit.inset().lyxCode() == MATHMACRO_CODE) {
802 MathMacroTemplate const & macroTemplate
803 = static_cast<MathMacroTemplate const &>(dit.inset());
804 if (macroTemplate.name() == name)
808 // in front of macro instance?
809 Inset * inset = dit.nextInset();
812 InsetMath * insetMath = inset->asInsetMath();
815 MathMacro * macro = insetMath->asMacro();
816 if (macro && macro->name() == name && macro->folded())
822 void MathMacroTemplate::insertParameter(Cursor & cur, int pos, bool greedy, bool addarg)
824 if (pos <= numargs_ && pos >= optionals_ && numargs_ < 9) {
829 shiftArguments(pos, 1);
831 cell(defIdx()).push_back(MathAtom(new MathMacroArgument(pos + 1)));
832 if (!cell(displayIdx()).empty())
833 cell(displayIdx()).push_back(MathAtom(new MathMacroArgument(pos + 1)));
838 dit.leaveInset(*this);
839 // TODO: this was dit.forwardPosNoDescend before. Check that this is the same
840 dit.top().forwardPos();
842 // fix macro instances
843 fixMacroInstancesAddRemove(dit, name(), pos, true);
851 void MathMacroTemplate::removeParameter(Cursor & cur, int pos, bool greedy)
853 if (pos < numargs_ && pos >= 0) {
855 removeArguments(cur, pos, pos);
856 shiftArguments(pos + 1, -1);
858 // removed optional parameter?
859 if (pos < optionals_) {
861 optionalValues_[pos] = cell(optIdx(pos));
862 cells_.erase(cells_.begin() + optIdx(pos));
865 int macroSlice = cur.find(this);
866 if (macroSlice != -1) {
867 if (cur[macroSlice].idx() == optIdx(pos)) {
868 cur.cutOff(macroSlice);
869 cur[macroSlice].idx() = 1;
870 cur[macroSlice].pos() = 0;
871 } else if (cur[macroSlice].idx() > optIdx(pos))
872 --cur[macroSlice].idx();
877 // fix macro instances
878 //boost::function<void(MathMacro *)> fix = _1->insertArgument(n);
879 //fixMacroInstancesFunctional(dit, name(), fix);
881 dit.leaveInset(*this);
882 // TODO: this was dit.forwardPosNoDescend before. Check that this is the same
883 dit.top().forwardPos();
884 fixMacroInstancesAddRemove(dit, name(), pos, false);
892 void MathMacroTemplate::makeOptional(Cursor & cur) {
893 if (numargs_ > 0 && optionals_ < numargs_) {
895 cells_.insert(cells_.begin() + optIdx(optionals_ - 1), optionalValues_[optionals_ - 1]);
897 int macroSlice = cur.find(this);
898 if (macroSlice != -1 && cur[macroSlice].idx() >= optIdx(optionals_ - 1))
899 ++cur[macroSlice].idx();
901 // fix macro instances
903 dit.leaveInset(*this);
904 // TODO: this was dit.forwardPosNoDescend before. Check that this is the same
905 dit.top().forwardPos();
906 fixMacroInstancesOptional(dit, name(), optionals_);
913 void MathMacroTemplate::makeNonOptional(Cursor & cur) {
914 if (numargs_ > 0 && optionals_ > 0) {
917 // store default value for later if the user changes his mind
918 optionalValues_[optionals_] = cell(optIdx(optionals_));
919 cells_.erase(cells_.begin() + optIdx(optionals_));
922 int macroSlice = cur.find(this);
923 if (macroSlice != -1) {
924 if (cur[macroSlice].idx() > optIdx(optionals_))
925 --cur[macroSlice].idx();
926 else if (cur[macroSlice].idx() == optIdx(optionals_)) {
927 cur.cutOff(macroSlice);
928 cur[macroSlice].idx() = optIdx(optionals_);
929 cur[macroSlice].pos() = 0;
933 // fix macro instances
935 dit.leaveInset(*this);
936 // TODO: this was dit.forwardPosNoDescend before. Check that this is the same
937 dit.top().forwardPos();
938 fixMacroInstancesOptional(dit, name(), optionals_);
945 void MathMacroTemplate::doDispatch(Cursor & cur, FuncRequest & cmd)
947 string const arg = to_utf8(cmd.argument());
948 switch (cmd.action) {
950 case LFUN_MATH_MACRO_ADD_PARAM:
952 commitEditChanges(cur);
953 cur.recordUndoFullDocument();
954 size_t pos = numargs_;
956 pos = (size_t)convert<int>(arg) - 1; // it is checked for >=0 in getStatus
957 insertParameter(cur, pos);
962 case LFUN_MATH_MACRO_REMOVE_PARAM:
964 commitEditChanges(cur);
965 cur.recordUndoFullDocument();
966 size_t pos = numargs_ - 1;
968 pos = (size_t)convert<int>(arg) - 1; // it is checked for >=0 in getStatus
969 removeParameter(cur, pos);
973 case LFUN_MATH_MACRO_APPEND_GREEDY_PARAM:
975 commitEditChanges(cur);
976 cur.recordUndoFullDocument();
977 insertParameter(cur, numargs_, true);
981 case LFUN_MATH_MACRO_REMOVE_GREEDY_PARAM:
983 commitEditChanges(cur);
984 cur.recordUndoFullDocument();
985 removeParameter(cur, numargs_ - 1, true);
989 case LFUN_MATH_MACRO_MAKE_OPTIONAL:
990 commitEditChanges(cur);
991 cur.recordUndoFullDocument();
995 case LFUN_MATH_MACRO_MAKE_NONOPTIONAL:
996 commitEditChanges(cur);
997 cur.recordUndoFullDocument();
998 makeNonOptional(cur);
1001 case LFUN_MATH_MACRO_ADD_OPTIONAL_PARAM:
1003 commitEditChanges(cur);
1004 cur.recordUndoFullDocument();
1005 insertParameter(cur, optionals_);
1010 case LFUN_MATH_MACRO_REMOVE_OPTIONAL_PARAM:
1011 if (optionals_ > 0) {
1012 commitEditChanges(cur);
1013 cur.recordUndoFullDocument();
1014 removeParameter(cur, optionals_ - 1);
1017 case LFUN_MATH_MACRO_ADD_GREEDY_OPTIONAL_PARAM:
1018 if (numargs_ == optionals_) {
1019 commitEditChanges(cur);
1020 cur.recordUndoFullDocument();
1021 insertParameter(cur, 0, true);
1027 InsetMathNest::doDispatch(cur, cmd);
1033 bool MathMacroTemplate::getStatus(Cursor & /*cur*/, FuncRequest const & cmd,
1034 FuncStatus & flag) const
1037 string const arg = to_utf8(cmd.argument());
1038 switch (cmd.action) {
1039 case LFUN_MATH_MACRO_ADD_PARAM: {
1040 int num = numargs_ + 1;
1041 if (arg.size() != 0)
1042 num = convert<int>(arg);
1043 bool on = (num >= optionals_
1044 && numargs_ < 9 && num <= numargs_ + 1);
1049 case LFUN_MATH_MACRO_APPEND_GREEDY_PARAM:
1050 flag.enabled(numargs_ < 9);
1053 case LFUN_MATH_MACRO_REMOVE_PARAM: {
1055 if (arg.size() != 0)
1056 num = convert<int>(arg);
1057 flag.enabled(num >= 1 && num <= numargs_);
1061 case LFUN_MATH_MACRO_MAKE_OPTIONAL:
1062 flag.enabled(numargs_ > 0
1063 && optionals_ < numargs_
1064 && type_ != MacroTypeDef);
1067 case LFUN_MATH_MACRO_MAKE_NONOPTIONAL:
1068 flag.enabled(optionals_ > 0
1069 && type_ != MacroTypeDef);
1072 case LFUN_MATH_MACRO_ADD_OPTIONAL_PARAM:
1073 flag.enabled(numargs_ < 9);
1076 case LFUN_MATH_MACRO_REMOVE_OPTIONAL_PARAM:
1077 flag.enabled(optionals_ > 0);
1080 case LFUN_MATH_MACRO_ADD_GREEDY_OPTIONAL_PARAM:
1081 flag.enabled(numargs_ == 0
1082 && type_ != MacroTypeDef);
1085 case LFUN_IN_MATHMACROTEMPLATE:
1097 void MathMacroTemplate::read(Lexer & lex)
1100 mathed_parse_cell(ar, lex.getStream());
1101 if (ar.size() != 1 || !ar[0]->asMacroTemplate()) {
1102 lyxerr << "Cannot read macro from '" << ar << "'" << endl;
1103 lyxerr << "Read: " << to_utf8(asString(ar)) << endl;
1106 operator=( *(ar[0]->asMacroTemplate()) );
1112 void MathMacroTemplate::write(ostream & os) const
1114 odocstringstream oss;
1115 WriteStream wi(oss, false, false);
1116 oss << "FormulaMacro\n";
1118 os << to_utf8(oss.str());
1122 void MathMacroTemplate::write(WriteStream & os) const
1128 void MathMacroTemplate::write(WriteStream & os, bool overwriteRedefinition) const
1130 // newcommand or renewcommand
1131 if (os.latex() && optionals_ > 1)
1132 os << "\\newlyxcommand";
1134 if (redefinition_ && !overwriteRedefinition)
1135 os << "\\renewcommand";
1137 os << "\\newcommand";
1139 os << "{\\" << name().c_str() << '}';
1141 os << '[' << numargs_ << ']';
1144 for (int i = 0; i < optionals_; ++i) {
1145 docstring optValue = asString(cell(optIdx(i)));
1146 if (optValue.find(']') != docstring::npos)
1147 os << "[{" << cell(optIdx(i)) << "}]";
1149 os << "[" << cell(optIdx(i)) << "]";
1152 os << "{" << cell(defIdx()) << "}";
1155 // writing .tex. done.
1158 // writing .lyx, write special .tex export only if necessary
1159 if (!cell(displayIdx()).empty())
1160 os << "\n{" << cell(displayIdx()) << '}';
1165 int MathMacroTemplate::plaintext(odocstream & os,
1166 OutputParams const &) const
1168 static docstring const str = '[' + buffer().B_("math macro") + ']';
1175 bool MathMacroTemplate::validName() const
1177 docstring n = name();
1183 // converting back and force doesn't swallow anything?
1186 if (asString(ma) != n)
1189 // valid characters?
1190 for (size_t i = 0; i < n.size(); ++i) {
1191 if (!(n[i] >= 'a' && n[i] <= 'z')
1192 && !(n[i] >= 'A' && n[i] <= 'Z')
1201 bool MathMacroTemplate::validMacro() const
1207 bool MathMacroTemplate::fixNameAndCheckIfValid()
1209 // check all the characters/insets in the name cell
1211 MathData & data = cell(0);
1212 while (i < data.size()) {
1213 InsetMathChar const * cinset = data[i]->asCharInset();
1215 // valid character in [a-zA-Z]?
1216 char_type c = cinset->getChar();
1217 if ((c >= 'a' && c <= 'z')
1218 || (c >= 'A' && c <= 'Z')) {
1228 // now it should be valid if anything in the name survived
1229 return data.size() > 0;
1233 void MathMacroTemplate::validate(LaTeXFeatures & features) const
1235 if (optionals_ > 1) {
1236 features.require("newlyxcommand");
1240 void MathMacroTemplate::getDefaults(vector<docstring> & defaults) const
1242 defaults.resize(numargs_);
1243 for (int i = 0; i < optionals_; ++i)
1244 defaults[i] = asString(cell(optIdx(i)));
1248 docstring MathMacroTemplate::definition() const
1250 return asString(cell(defIdx()));
1254 docstring MathMacroTemplate::displayDefinition() const
1256 return asString(cell(displayIdx()));
1260 size_t MathMacroTemplate::numArgs() const
1266 size_t MathMacroTemplate::numOptionals() const
1272 void MathMacroTemplate::infoize(odocstream & os) const
1274 os << "Math Macro: \\" << name();