Q:

How can I test if a command is followed by an argument?

Imagine I have two commands defined as
\def\witharg#1{something with #1}
\def\without{something without arg}

and I want to define a new command \mycmd that behaves as \witharg if it's followed by an argument (not necessarily enclosed in braces), and behaves like \without if it is not followed by an argument. In fact, the later case can only be true if \mycmd is followed by the token }. To make things slightly more clear, I want
{\mycmd\token\mycmd}

to expand to something similar to the expansion of
{\witharg{\token}\without}

How can I achieve this?
Note that, in fact, trying to evaluate something like {\witharg} fails with TeX complaining that there is an extra }, i.e. the argument to \witharg is missing.

A:

Whenever you need to check what comes next after a macro, the primitive to use is generally \futurelet (see TeX by Topic for a good reference). In this case, you'd write something like
\def\mycmd{%
  \futurelet\mytoken\myargparse
}

which will \let the following token to \mytoken and then expand \myargparse. Define \myargparse to be conditional on what \mytoken is, and that's it:
\def\myargparse{%
  \ifx\mytoken\closingbracetoken
    \expandafter\without
  \else
    \expandafter\witharg
  \fi
}
\let\closingbracetoken=}

Finally, check that it works:
\def\witharg#1{something with #1}
\def\without{something without arg}
\def\token{TOK}
{\mycmd\token\mycmd}

A:

xparse can test for explicit brace-delimited arguments (or other delimiters, see documentation):
\documentclass{article}
\usepackage{xparse}% http://www.ctan.org/pkg/xparse

\NewDocumentCommand\mycmd{g}{%
\IfValueTF{#1}{(something with #1)}{(something without arg)}%
}

\def\token{TOK}
\begin{document}

\mycmd{Hello}

\mycmd

{\mycmd\token\mycmd}

Blah, \mycmd{Hello}, blah, \mycmd, blah

\end{document}

