[texhax] Defining a command which runs differently based ion input argument

Heiko Oberdiek heiko.oberdiek at googlemail.com
Tue Dec 28 13:37:27 CET 2010

On Tue, Dec 28, 2010 at 01:28:00AM -0800, Mike B. wrote:

> How can I define a command which runs differently based on if an input
> argument was provided or not?. For example:
> \mycommand
> would introduce a vsapce of 1cm
> whereas 
> \mycommand{xyz}
> would print xyz

Why do you want to have the same macro name for different purposes?

> So it's conceptually something likel:
> if input argument is missing then
>    run this code
> else 
>    run this code
> endif

There are already many solutions in the thread:
* A classical optional argument:
* An optional argument using braces.

However optional arguments at the end have the risk of

{\bfseries Hello World} % group braces are taken as argument braces

\mycommand\xyz % missing argument braces

Another concept/idea:
In the example above the first use of \mycommand is in
vertical mode, the second in horizontal mode.
This can be used to make the macro behaving differently
dependend on the mode:

    \expandafter\mycommand at hmode
      \mycommand at vmode
      \errmessage{Invalid mode}%
\newcommand*{\mycommand at hmode}[1]{#1}
\newcommand*{\mycommand at vmode}{\vspace{1cm}}

Yours sincerely
  Heiko Oberdiek

More information about the texhax mailing list