When I was writing my thesis I wrote the following two commands which I found useful (and still do). They are both ways of defining other commands.
\usepackage{ifthen}
\makeatletter
\def\optional #1[#2]#3#4{\newcommand{#1}[#2][@rGUmentmiSSing]{\ifthenelse{\equal{##1}{@rGUmentmiSSing}}{#4}{#3}}}
\newcommand{\starredcommand}[4][*]{\newcommand{#2}{\@ifnextchar#1{\expandafter #4\@gobble}{#3}}}
\makeatother
They aren't easy to read. The first one allows me to define a command with an optional argument, where the behaviour of the command is very different if the optional argument is there or not.
The second allows me to define a command with a modifier which I usually use if I have two versions of the same object but one defined on a larger space. For example I have
\optional{\foo}[1]{F(#1)}{F}
\starredcommand{\barr}{\mathcal B}{\mathscr B}
So I can write
\begin{align}
\foo &= \foo[x] \\
\barr &\neq \barr*
\end{align}
Which would give me the same effect as
\begin{align}
F &= F(x) \\
\mathcal B &\neq \mathscr B
\end{align}
I like these commands but they don't play nicely together.
For example if I write \foo[\bar] or \foo[\bar*] I get over 100 errors, which is bad. It's not to do with the \@gobble command eating the bracket.
\foo[\bar* 123456789] Gives me the same thing. And it's not to do with the square brackets. If I define
\newcommand{\fine}[1][y]{X^{#1}}
then \fine[\bar] works exactly as it's supposed to.
I have no idea what's going wrong. It would be great if someone could help.
Here's a follow up question if that one's too easy. At the moment there's no way of including arguments in my \starredcommand If I wanted to give \barr an argument I'd normally do something like
\makeatletter
\newcommand{\@barr}[1]{\mathcal B^{#1}}
\newcommand{\@barrstar}{\mathscr B^{#1}}
\starredcommand{\barr}{\@barr}{\@barrstar}
\makeatother
Which works fine (even with optional arguments or my \optional command) but it sort of defeats the point of defining the \starredcommand in the first place.
I'd love a version of starred command that could work with arguments but I can't think of a way of doing it.



xparsepackage, can do very sophisticated argument parsing very easy. – daleif May 14 '13 at 11:02