1

The following MWE does not compile (unfortunately). The objective is to create a dynamically created macro, for example, \Newton with an optional argument.

If \Newton is invoked, $F=ma$ will be rendered. If \Newton[$F=GMm/r^2$] is invoked then $F=GMm/r^2$ rather than $F=ma$ will be rendered.

How to implement this?

MWE

\documentclass{book}
\usepackage{etoolbox}
\newcommand\CreateMacro[2]{%
    \expandafter\newrobustcmd\csname#1\endcsname[1][]{%
        % if ##1 is given 
        % then use ##1
        % else use #2
    }%
}

\begin{document}
\CreateMacro{Newton}{$F=ma$}

\Newton should produce $F=ma$.

\Newton[$F=GMm/r^2$] replaces $F=ma$.

\end{document}
  • @ChristianHupfer: I think I don't need key-value interface because it will make my input file complicated. – Money Oriented Programmer Dec 3 '15 at 16:03
2

Quite simple:

\newcommand{\CreateMacro}[2]{%
  % #1 is the macro name, #2 the default expansion
  \expandafter\newcommand\csname #1\endcsname[1][#2]{##1}%
}

Let's see why: \CreateMacro{Newton}{$F=ma$} would do

\expandafter\newcommand\csname Newton\endcsname[1][$F=ma$]{#1}

and the calls

\Newton
\Newton[$F=GMm/r^2$]

would produce the expected output.

2

Here's a etoolbox and a xparse version, the xparse version is more failsafe regarding empty optional arguments.

The etoolbox version uses \ifblank{...}{true}{false} to check the optional argument. There's an alternative (but not shorter) with \notblank, however.

\documentclass{book}
\usepackage{etoolbox}
\usepackage{xparse}
\newcommand\CreateMacro[2]{%
  \expandafter\newrobustcmd\csname#1\endcsname[1][]{%
    \ifblank{##1}{%
      #2%
    }{%
      ##1%
    }%
  }%
}

\NewDocumentCommand{\CreateOtherMacro}{mm}{%
\expandafter\NewDocumentCommand\csname #1\endcsname{o}{%
    \IfValueTF{##1}{%
      ##1%
    }{%
      #2%
    }%
  }%
}
\begin{document}
\CreateMacro{Newton}{$F=ma$}%
\CreateOtherMacro{Einstein}{$E=mc^2$}%

\Newton\ should produce $F=ma$.

\Newton[$F=GMm/r^2$] replaces $F=ma$.

\Einstein\ should produce $E=mc^2$.

\Einstein[$8\pi G$] will show something different

\end{document}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.