Stupid error caused by doing stupid things
A quick attempt with xparse
:
\documentclass{article}
\usepackage{xparse,mathrsfs}
\NewDocumentCommand\optional{mO{}mm}
{%
\NewDocumentCommand{#1}{o#2}
{\IfNoValueTF{##1}{#4}{#3}}%
}
\NewDocumentCommand\starredcommand{O{s}mmm}
{%
\NewDocumentCommand{#2}{#1}
{\IfBooleanTF{##1}{#4}{#3}}%
}
\optional{\foo}{F(#1)}{F}
\optional{\baz}[m]{Baz with opt #1 and #2}{Baz without opt and #2}
\starredcommand{\barr}{\mathcal{B}}{\mathscr{B}}
\starredcommand[t{+}]{\carr}{\mathcal{C}}{\mathscr{C}}
\begin{document}
$\foo$
$\foo[x]$
$\foo[\barr*]$
$\foo[\barr]$
$\foo[\carr+]$
$\foo[\carr]$
\baz{x}
\baz[Y]{x}
\end{document}
However you have to change the way arguments are specified. You see in the example how to use a +
instead of the *
; for \optional
and how to define \baz
with a mandatory argument (the optional one is always present).
Here is how you can have your \starredcommand
with arguments
\documentclass{article}
\usepackage{amsmath}
\usepackage{mathrsfs}
\makeatletter
% Following 3 lines thanks to Prof. Enrico Gregorio, from:
% http://tex.stackexchange.com/questions/42318/
% removing-a-backslash-from-a-character-sequence
\begingroup\lccode`\|=`\\
\lowercase{\endgroup\def\removebs#1{\if#1|\else#1\fi}}
\newcommand{\@macro@name}[1]{\expandafter\removebs\string#1}
%
\newcommand\starredcommand[5]{%
\gdef\mname{\@macro@name{#1}}%
\newcommand#1{\@ifstar{\csname @\mname star\endcsname}
{\csname @\mname\endcsname}}
\expandafter\newcommand\csname @\mname\endcsname[#2]{#3}
\expandafter\newcommand\csname @\mname star\endcsname[#4]{#5}
}
\makeatother
\begin{document}
\starredcommand{\barr}{1}{\mathcal #1}{1}{\mathscr #1}
\begin{align}
\barr{C} &\neq \barr*{F}
\end{align}
\end{document}
FOLLOW UP: Here is a version of your \optional
command:
\usepackage{ifthen}
% ...
\def\optional#1[#2]#3#4{%
\newcommand#1[#2][]{\ifthenelse{\equal{##1}{}}{#4}{#3}}%
}
though it is not ideal. It does allow, per the user's desire, for \barr
to be an argument of foo
, except that the \barr
must be protected, as in
\optional{\foo}[1]{F(#1)}{F}
\( \foo = \foo[\protect\barr{Q}] \neq \foo[\protect\barr*{R}]\)