]> git.lyx.org Git - lyx.git/blobdiff - src/mathed/MathMacroTemplate.cpp
Fix bug 5802 (http://bugzilla.lyx.org/show_bug.cgi?id=5802)
[lyx.git] / src / mathed / MathMacroTemplate.cpp
index b7ecb9bbc535511fec76a8662dddf88af316d60b..6765f01a99783b8980d014da7c4de850785ee52d 100644 (file)
@@ -3,7 +3,8 @@
  * This file is part of LyX, the document processor.
  * Licence details can be found in the file COPYING.
  *
- * \author André Pönitz
+ * \author André Pönitz
+ * \author Stefan Schimanski
  *
  * Full author contact details are available in file CREDITS.
  */
 #include "BufferView.h"
 #include "Color.h"
 #include "Cursor.h"
-#include "support/debug.h"
 #include "DispatchResult.h"
 #include "FuncRequest.h"
 #include "FuncStatus.h"
-#include "support/gettext.h"
 #include "Lexer.h"
 #include "Undo.h"
 
-#include "frontends/FontMetrics.h"
 #include "frontends/Painter.h"
 
+#include "support/lassert.h"
 #include "support/convert.h"
+#include "support/debug.h"
+#include "support/gettext.h"
 #include "support/docstream.h"
 #include "support/lstrings.h"
 
-#include "support/debug.h"
-
 #include <sstream>
 
 using namespace std;
@@ -80,8 +79,8 @@ protected:
 
 
 InsetLabelBox::InsetLabelBox(MathAtom const & atom, docstring label,
-                            MathMacroTemplate const & parent, bool frame)
-:      InsetMathNest(1), parent_(parent), label_(label), frame_(frame)
+       MathMacroTemplate const & parent, bool frame)
+       : InsetMathNest(1), parent_(parent), label_(label), frame_(frame)
 {
        cell(0).insert(0, atom);
 }
@@ -89,7 +88,7 @@ InsetLabelBox::InsetLabelBox(MathAtom const & atom, docstring label,
 
 InsetLabelBox::InsetLabelBox(docstring label,
                             MathMacroTemplate const & parent, bool frame)
-:      InsetMathNest(1), parent_(parent), label_(label), frame_(frame)
+       : InsetMathNest(1), parent_(parent), label_(label), frame_(frame)
 {
 }
 
@@ -276,6 +275,61 @@ void InsetMathWrapper::draw(PainterInfo & pi, int x, int y) const
 }
 
 
+///////////////////////////////////////////////////////////////////////
+class InsetColoredCell : public InsetMathNest {
+public:
+       ///
+       InsetColoredCell(ColorCode min, ColorCode max);
+       ///
+       InsetColoredCell(ColorCode min, ColorCode max, MathAtom const & atom);
+       ///
+       void draw(PainterInfo &, int x, int y) const;
+       ///
+       void metrics(MetricsInfo & mi, Dimension & dim) const;
+
+protected:
+       ///
+       Inset * clone() const;
+       ///
+       ColorCode min_;
+       ///
+       ColorCode max_;
+};
+
+
+InsetColoredCell::InsetColoredCell(ColorCode min, ColorCode max)
+       : InsetMathNest(1), min_(min), max_(max)
+{
+}
+
+
+InsetColoredCell::InsetColoredCell(ColorCode min, ColorCode max, MathAtom const & atom)
+       : InsetMathNest(1), min_(min), max_(max)
+{
+       cell(0).insert(0, atom);
+}
+
+
+Inset * InsetColoredCell::clone() const
+{
+       return new InsetColoredCell(*this);
+}
+
+
+void InsetColoredCell::metrics(MetricsInfo & mi, Dimension & dim) const
+{
+       cell(0).metrics(mi, dim);
+}
+
+
+void InsetColoredCell::draw(PainterInfo & pi, int x, int y) const
+{
+       pi.pain.enterMonochromeMode(min_, max_);
+       cell(0).draw(pi, x, y);
+       pi.pain.leaveMonochromeMode();
+}
+
+
 ///////////////////////////////////////////////////////////////////////
 
 class InsetNameWrapper : public InsetMathWrapper {
@@ -337,7 +391,7 @@ void InsetNameWrapper::draw(PainterInfo & pi, int x, int y) const
 
 
 MathMacroTemplate::MathMacroTemplate()
-       : InsetMathNest(3), numargs_(0), optionals_(0),
+       : InsetMathNest(3), numargs_(0), argsInLook_(0), optionals_(0),
          type_(MacroTypeNewcommand), lookOutdated_(true)
 {
        initMath();
@@ -348,7 +402,7 @@ MathMacroTemplate::MathMacroTemplate(docstring const & name, int numargs,
        int optionals, MacroType type,
        vector<MathData> const & optionalValues,
        MathData const & def, MathData const & display)
-       : InsetMathNest(optionals + 3), numargs_(numargs),
+       : InsetMathNest(optionals + 3), numargs_(numargs), argsInLook_(numargs),
          optionals_(optionals), optionalValues_(optionalValues),
          type_(type), lookOutdated_(true)
 {
@@ -419,9 +473,10 @@ void MathMacroTemplate::updateLook() const
 }
 
 
-void MathMacroTemplate::createLook() const
+void MathMacroTemplate::createLook(int args) const
 {
        look_.clear();
+       argsInLook_ = args;
 
        // \foo
        look_.push_back(MathAtom(new InsetLabelBox(_("Name"), *this, false)));
@@ -432,12 +487,19 @@ void MathMacroTemplate::createLook() const
        int i = 0;
        if (optionals_ > 0) {
                look_.push_back(MathAtom(new InsetLabelBox(_("optional"), *this, false)));
-               MathData & optData = look_[look_.size() - 1].nucleus()->cell(0);
-
+               
+               MathData * optData = &look_[look_.size() - 1].nucleus()->cell(0);
                for (; i < optionals_; ++i) {
-                       optData.push_back(MathAtom(new InsetMathChar('[')));
-                       optData.push_back(MathAtom(new InsetMathWrapper(&cell(1 + i))));
-                       optData.push_back(MathAtom(new InsetMathChar(']')));
+                       // color it light grey, if it is to be removed when the cursor leaves
+                       if (i == argsInLook_) {
+                               optData->push_back(MathAtom(
+                                       new InsetColoredCell(Color_mathbg, Color_mathmacrooldarg)));
+                               optData = &(*optData)[optData->size() - 1].nucleus()->cell(0);
+                       }
+
+                       optData->push_back(MathAtom(new InsetMathChar('[')));
+                       optData->push_back(MathAtom(new InsetMathWrapper(&cell(1 + i))));
+                       optData->push_back(MathAtom(new InsetMathChar(']')));
                }
        }
 
@@ -445,9 +507,21 @@ void MathMacroTemplate::createLook() const
        for (; i < numargs_; ++i) {
                MathData arg;
                arg.push_back(MathAtom(new MathMacroArgument(i + 1)));
-               look_.push_back(MathAtom(new InsetMathBrace(arg)));
+               if (i >= argsInLook_) {
+                       look_.push_back(MathAtom(new InsetColoredCell(
+                               Color_mathbg, Color_mathmacrooldarg,
+                               MathAtom(new InsetMathBrace(arg)))));
+               } else
+                       look_.push_back(MathAtom(new InsetMathBrace(arg)));
        }
-
+       for (; i < argsInLook_; ++i) {
+               MathData arg;
+               arg.push_back(MathAtom(new MathMacroArgument(i + 1)));
+               look_.push_back(MathAtom(new InsetColoredCell(
+                       Color_mathbg, Color_mathmacronewarg,
+                       MathAtom(new InsetMathBrace(arg)))));
+       }
+       
        // :=
        look_.push_back(MathAtom(new InsetMathChar(':')));
        look_.push_back(MathAtom(new InsetMathChar('=')));
@@ -479,9 +553,10 @@ void MathMacroTemplate::metrics(MetricsInfo & mi, Dimension & dim) const
        }
 
        // update look?
-       if (lookOutdated_) {
+       int argsInDef = maxArgumentInDefinition();
+       if (lookOutdated_ || argsInDef != argsInLook_) {
                lookOutdated_ = false;
-               createLook();
+               createLook(argsInDef);
        }
 
        /// metrics for inset contents
@@ -524,33 +599,40 @@ void MathMacroTemplate::draw(PainterInfo & pi, int x, int y) const
        pi.pain.rectangle(x, a, w, h, Color_mathframe);
 
        // just to be sure: set some dummy values for coord cache
-       for (idx_type i = 0; i < nargs(); ++i) {
+       for (idx_type i = 0; i < nargs(); ++i)
                cell(i).setXY(*pi.base.bv, x, y);
-       }
 
        // draw contents
        look_.draw(pi, x + 3, y);
 }
 
 
-void MathMacroTemplate::edit(Cursor & cur, bool left)
+void MathMacroTemplate::edit(Cursor & cur, bool front, EntryDirection entry_from)
 {
        updateLook();
-       cur.updateFlags(Update::Force);
-       InsetMathNest::edit(cur, left);
+       cur.updateFlags(Update::SinglePar);
+       InsetMathNest::edit(cur, front, entry_from);
 }
 
 
-bool MathMacroTemplate::notifyCursorLeaves(Cursor & cur)
+bool MathMacroTemplate::notifyCursorLeaves(Cursor const & old, Cursor & cur)
 {
+       // find this in cursor old
+       Cursor insetCur = old;
+       int scriptSlice = insetCur.find(this);
+       LASSERT(scriptSlice != -1, /**/);
+       insetCur.cutOff(scriptSlice);
+       
+       commitEditChanges(insetCur);
        updateLook();
        cur.updateFlags(Update::Force);
-       return InsetMathNest::notifyCursorLeaves(cur);
+       return InsetMathNest::notifyCursorLeaves(old, cur);
 }
 
 
-void MathMacroTemplate::removeArguments(Cursor & cur, int from, int to) {
-       for (DocIterator it = doc_iterator_begin(*this); it; it.forwardChar()) {
+void MathMacroTemplate::removeArguments(Cursor & cur, int from, int to)
+{
+       for (DocIterator it = doc_iterator_begin(&buffer(), this); it; it.forwardChar()) {
                if (!it.nextInset())
                        continue;
                if (it.nextInset()->lyxCode() != MATHMACROARG_CODE)
@@ -570,14 +652,15 @@ void MathMacroTemplate::removeArguments(Cursor & cur, int from, int to) {
 }
 
 
-void MathMacroTemplate::shiftArguments(size_t from, int by) {
-       for (DocIterator it = doc_iterator_begin(*this); it; it.forwardChar()) {
+void MathMacroTemplate::shiftArguments(size_t from, int by)
+{
+       for (DocIterator it = doc_iterator_begin(&buffer(), this); it; it.forwardChar()) {
                if (!it.nextInset())
                        continue;
                if (it.nextInset()->lyxCode() != MATHMACROARG_CODE)
                        continue;
                MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
-               if (arg->number() >= from + 1)
+               if (arg->number() >= int(from) + 1)
                        arg->setNumber(arg->number() + by);
        }
 
@@ -585,6 +668,73 @@ void MathMacroTemplate::shiftArguments(size_t from, int by) {
 }
 
 
+int MathMacroTemplate::maxArgumentInDefinition() const
+{
+       int maxArg = 0;
+       DocIterator it = doc_iterator_begin(&buffer(), this);
+       it.idx() = defIdx();
+       for (; it; it.forwardChar()) {
+               if (!it.nextInset())
+                       continue;
+               if (it.nextInset()->lyxCode() != MATHMACROARG_CODE)
+                       continue;
+               MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
+               maxArg = std::max(int(arg->number()), maxArg);
+       }
+       return maxArg;
+}
+
+
+void MathMacroTemplate::insertMissingArguments(int maxArg)
+{
+       bool found[9] = { false, false, false, false, false, false, false, false, false };
+       idx_type idx = cell(displayIdx()).empty() ? defIdx() : displayIdx();
+
+       // search for #n macros arguments
+       DocIterator it = doc_iterator_begin(&buffer(), this);
+       it.idx() = idx;
+       for (; it && it[0].idx() == idx; it.forwardChar()) {
+               if (!it.nextInset())
+                       continue;
+               if (it.nextInset()->lyxCode() != MATHMACROARG_CODE)
+                       continue;
+               MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
+               found[arg->number() - 1] = true;
+       }
+
+       // add missing ones
+       for (int i = 0; i < maxArg; ++i) {
+               if (found[i])
+                       continue;
+
+               cell(idx).push_back(MathAtom(new MathMacroArgument(i + 1)));
+       }
+}
+
+
+void MathMacroTemplate::changeArity(Cursor & cur, int newNumArg)
+{
+       // remove parameter which do not appear anymore in the definition
+       for (int i = numargs_; i > newNumArg; --i)
+               removeParameter(cur, numargs_ - 1, false);
+       
+       // add missing parameter
+       for (int i = numargs_; i < newNumArg; ++i)
+               insertParameter(cur, numargs_, false, false);
+}
+
+
+void MathMacroTemplate::commitEditChanges(Cursor & cur)
+{
+       int argsInDef = maxArgumentInDefinition();
+       if (argsInDef != numargs_) {
+               cur.recordUndoFullDocument();
+               changeArity(cur, argsInDef);
+       }
+       insertMissingArguments(argsInDef);
+}
+
+
 // FIXME: factorize those functions here with a functional style, maybe using Boost's function
 // objects?
 
@@ -676,16 +826,19 @@ void fixMacroInstancesFunctional(Cursor const & from,
 }
 
 
-void MathMacroTemplate::insertParameter(Cursor & cur, int pos, bool greedy)
+void MathMacroTemplate::insertParameter(Cursor & cur, int pos, bool greedy, bool addarg)
 {
        if (pos <= numargs_ && pos >= optionals_ && numargs_ < 9) {
                ++numargs_;
-               shiftArguments(pos, 1);
-
+               
                // append example #n
-               cell(defIdx()).push_back(MathAtom(new MathMacroArgument(pos + 1)));
-               if (!cell(displayIdx()).empty())
-                       cell(displayIdx()).push_back(MathAtom(new MathMacroArgument(pos + 1)));
+               if (addarg) {
+                       shiftArguments(pos, 1);
+
+                       cell(defIdx()).push_back(MathAtom(new MathMacroArgument(pos + 1)));
+                       if (!cell(displayIdx()).empty())
+                               cell(displayIdx()).push_back(MathAtom(new MathMacroArgument(pos + 1)));
+               }
 
                if (!greedy) {
                        Cursor dit = cur;
@@ -768,7 +921,7 @@ void MathMacroTemplate::makeNonOptional(Cursor & cur) {
        if (numargs_ > 0 && optionals_ > 0) {
                --optionals_;
 
-               // store default value for later if the use changes his mind
+               // store default value for later if the user changes his mind
                optionalValues_[optionals_] = cell(optIdx(optionals_));
                cells_.erase(cells_.begin() + optIdx(optionals_));
 
@@ -803,6 +956,7 @@ void MathMacroTemplate::doDispatch(Cursor & cur, FuncRequest & cmd)
 
        case LFUN_MATH_MACRO_ADD_PARAM:
                if (numargs_ < 9) {
+                       commitEditChanges(cur);
                        cur.recordUndoFullDocument();
                        size_t pos = numargs_;
                        if (arg.size() != 0)
@@ -814,6 +968,7 @@ void MathMacroTemplate::doDispatch(Cursor & cur, FuncRequest & cmd)
 
        case LFUN_MATH_MACRO_REMOVE_PARAM:
                if (numargs_ > 0) {
+                       commitEditChanges(cur);
                        cur.recordUndoFullDocument();
                        size_t pos = numargs_ - 1;
                        if (arg.size() != 0)
@@ -824,6 +979,7 @@ void MathMacroTemplate::doDispatch(Cursor & cur, FuncRequest & cmd)
 
        case LFUN_MATH_MACRO_APPEND_GREEDY_PARAM:
                if (numargs_ < 9) {
+                       commitEditChanges(cur);
                        cur.recordUndoFullDocument();
                        insertParameter(cur, numargs_, true);
                }
@@ -831,23 +987,27 @@ void MathMacroTemplate::doDispatch(Cursor & cur, FuncRequest & cmd)
 
        case LFUN_MATH_MACRO_REMOVE_GREEDY_PARAM:
                if (numargs_ > 0) {
+                       commitEditChanges(cur);
                        cur.recordUndoFullDocument();
                        removeParameter(cur, numargs_ - 1, true);
                }
                break;
 
        case LFUN_MATH_MACRO_MAKE_OPTIONAL:
+               commitEditChanges(cur);
                cur.recordUndoFullDocument();
                makeOptional(cur);
                break;
 
        case LFUN_MATH_MACRO_MAKE_NONOPTIONAL:
+               commitEditChanges(cur);
                cur.recordUndoFullDocument();
                makeNonOptional(cur);
                break;
 
        case LFUN_MATH_MACRO_ADD_OPTIONAL_PARAM:
                if (numargs_ < 9) {
+                       commitEditChanges(cur);
                        cur.recordUndoFullDocument();
                        insertParameter(cur, optionals_);
                        makeOptional(cur);
@@ -856,12 +1016,14 @@ void MathMacroTemplate::doDispatch(Cursor & cur, FuncRequest & cmd)
 
        case LFUN_MATH_MACRO_REMOVE_OPTIONAL_PARAM:
                if (optionals_ > 0) {
+                       commitEditChanges(cur);
                        cur.recordUndoFullDocument();
                        removeParameter(cur, optionals_ - 1);
                } break;
 
        case LFUN_MATH_MACRO_ADD_GREEDY_OPTIONAL_PARAM:
                if (numargs_ == optionals_) {
+                       commitEditChanges(cur);
                        cur.recordUndoFullDocument();
                        insertParameter(cur, 0, true);
                        makeOptional(cur);
@@ -887,48 +1049,48 @@ bool MathMacroTemplate::getStatus(Cursor & /*cur*/, FuncRequest const & cmd,
                                num = convert<int>(arg);
                        bool on = (num >= optionals_
                                   && numargs_ < 9 && num <= numargs_ + 1);
-                       flag.enabled(on);
+                       flag.setEnabled(on);
                        break;
                }
 
                case LFUN_MATH_MACRO_APPEND_GREEDY_PARAM:
-                       flag.enabled(numargs_ < 9);
+                       flag.setEnabled(numargs_ < 9);
                        break;
 
                case LFUN_MATH_MACRO_REMOVE_PARAM: {
                        int num = numargs_;
                        if (arg.size() != 0)
                                num = convert<int>(arg);
-                       flag.enabled(num >= 1 && num <= numargs_);
+                       flag.setEnabled(num >= 1 && num <= numargs_);
                        break;
                }
 
                case LFUN_MATH_MACRO_MAKE_OPTIONAL:
-                       flag.enabled(numargs_ > 0
+                       flag.setEnabled(numargs_ > 0
                                     && optionals_ < numargs_
                                     && type_ != MacroTypeDef);
                        break;
 
                case LFUN_MATH_MACRO_MAKE_NONOPTIONAL:
-                       flag.enabled(optionals_ > 0
+                       flag.setEnabled(optionals_ > 0
                                     && type_ != MacroTypeDef);
                        break;
 
                case LFUN_MATH_MACRO_ADD_OPTIONAL_PARAM:
-                       flag.enabled(numargs_ < 9);
+                       flag.setEnabled(numargs_ < 9);
                        break;
 
                case LFUN_MATH_MACRO_REMOVE_OPTIONAL_PARAM:
-                       flag.enabled(optionals_ > 0);
+                       flag.setEnabled(optionals_ > 0);
                        break;
 
                case LFUN_MATH_MACRO_ADD_GREEDY_OPTIONAL_PARAM:
-                       flag.enabled(numargs_ == 0
+                       flag.setEnabled(numargs_ == 0
                                     && type_ != MacroTypeDef);
                        break;
 
                case LFUN_IN_MATHMACROTEMPLATE:
-                       flag.enabled();
+                       flag.setEnabled(true);
                        break;
 
                default:
@@ -939,7 +1101,7 @@ bool MathMacroTemplate::getStatus(Cursor & /*cur*/, FuncRequest const & cmd,
 }
 
 
-void MathMacroTemplate::read(Buffer const &, Lexer & lex)
+void MathMacroTemplate::read(Lexer & lex)
 {
        MathData ar;
        mathed_parse_cell(ar, lex.getStream());
@@ -954,10 +1116,10 @@ void MathMacroTemplate::read(Buffer const &, Lexer & lex)
 }
 
 
-void MathMacroTemplate::write(Buffer const &, ostream & os) const
+void MathMacroTemplate::write(ostream & os) const
 {
        odocstringstream oss;
-       WriteStream wi(oss, false, false);
+       WriteStream wi(oss, false, false, false);
        oss << "FormulaMacro\n";
        write(wi);
        os << to_utf8(oss.str());
@@ -972,26 +1134,61 @@ void MathMacroTemplate::write(WriteStream & os) const
 
 void MathMacroTemplate::write(WriteStream & os, bool overwriteRedefinition) const
 {
-       // newcommand or renewcommand
-       if (os.latex() && optionals_ > 1)
-               os << "\\newlyxcommand";
-       else {
+       if (os.latex()) {
+               if (optionals_ > 0) {
+                       // macros with optionals use the xargs package, e.g.:
+                       // \newcommandx{\foo}[2][usedefault, addprefix=\global,1=default]{#1,#2}
+                       // \long is implicit by xargs
+                       if (redefinition_ && !overwriteRedefinition)
+                               os << "\\renewcommandx";
+                       else
+                               os << "\\newcommandx";
+
+                       os << "\\" << name()
+                          << "[" << numargs_ << "]"
+                          << "[usedefault, addprefix=\\global";
+                       for (int i = 0; i < optionals_; ++i) {
+                               docstring optValue = asString(cell(optIdx(i)));
+                               if (optValue.find(']') != docstring::npos
+                                   || optValue.find(',') != docstring::npos)
+                                       os << ", " << i + 1 << "="
+                                       << "{" << cell(optIdx(i)) << "}";
+                               else
+                                       os << ", " << i + 1 << "="
+                                       << cell(optIdx(i));
+                       }
+                       os << "]";
+               } else {
+                       // Macros without optionals use standard _global_ \def macros:
+                       //   \global\def\long\foo#1#2{#1,#2}
+                       // We use the \long prefix as this is the equivalent to \newcommand.
+                       // We cannot use \newcommand directly because \global does not work with it.
+                       os << "\\global\\long\\def\\" << name();
+                       docstring param = from_ascii("#0");
+                       for (int i = 1; i <= numargs_; ++i) { 
+                               param[1] = '0' + i;
+                               os << param;
+                       }
+               }
+       } else {
+               // in LyX output we use some pseudo syntax which is implementation
+               // independent, e.g.
+               // \newcommand{\foo}[2][default]{#1,#2}
                if (redefinition_ && !overwriteRedefinition)
                        os << "\\renewcommand";
                else
                        os << "\\newcommand";
-       }
-       os << "{\\" << name().c_str() << '}';
-       if (numargs_ > 0)
-               os << '[' << numargs_ << ']';
-
-       // optional values
-       for (int i = 0; i < optionals_; ++i) {
-               docstring optValue = asString(cell(optIdx(i)));
-               if (optValue.find(']') != docstring::npos)
-                       os << "[{" << cell(optIdx(i)) << "}]";
-               else
-                       os << "[" << cell(optIdx(i)) << "]";
+               os << "{\\" << name() << '}';
+               if (numargs_ > 0)
+                       os << '[' << numargs_ << ']';
+
+               for (int i = 0; i < optionals_; ++i) {
+                       docstring optValue = asString(cell(optIdx(i)));
+                       if (optValue.find(']') != docstring::npos)
+                               os << "[{" << cell(optIdx(i)) << "}]";
+                       else
+                               os << "[" << cell(optIdx(i)) << "]";
+               }
        }
 
        os << "{" << cell(defIdx()) << "}";
@@ -1007,10 +1204,10 @@ void MathMacroTemplate::write(WriteStream & os, bool overwriteRedefinition) cons
 }
 
 
-int MathMacroTemplate::plaintext(Buffer const & buf, odocstream & os,
+int MathMacroTemplate::plaintext(odocstream & os,
                                 OutputParams const &) const
 {
-       static docstring const str = '[' + buf.B_("math macro") + ']';
+       static docstring const str = '[' + buffer().B_("math macro") + ']';
 
        os << str;
        return str.size();
@@ -1033,8 +1230,9 @@ bool MathMacroTemplate::validName() const
 
        // valid characters?
        for (size_t i = 0; i < n.size(); ++i) {
-               if (!(n[i] >= 'a' && n[i] <= 'z') &&
-                               !(n[i] >= 'A' && n[i] <= 'Z'))
+               if (!(n[i] >= 'a' && n[i] <= 'z')
+                   && !(n[i] >= 'A' && n[i] <= 'Z')
+                   && n[i] != '*')
                        return false;
        }
 
@@ -1076,9 +1274,11 @@ bool MathMacroTemplate::fixNameAndCheckIfValid()
        
 void MathMacroTemplate::validate(LaTeXFeatures & features) const
 {
-       if (optionals_ > 1) {
-               features.require("newlyxcommand");
-       }
+       // we need global optional macro arguments. They are not available 
+       // with \def, and \newcommand does not support global macros. So we
+       // are bound to xargs also for the single-optional-parameter case.
+       if (optionals_ > 0)
+               features.require("xargs");
 }
 
 void MathMacroTemplate::getDefaults(vector<docstring> & defaults) const
@@ -1118,4 +1318,10 @@ void MathMacroTemplate::infoize(odocstream & os) const
        os << "Math Macro: \\" << name();
 }
 
+
+docstring MathMacroTemplate::contextMenu(BufferView const &, int, int) const
+{
+       return from_ascii("context-math-macro-definition");
+}
+
 } // namespace lyx