[Tex/LaTex] Special behavior if optional argument is not passed

macrosoptional arguments

I am looking to define a command (actually, an environment, but that shouldn't matter for the purposes of this question) that does some default behavior, and if an optional argument is passed, does something else.

For example,

\newcommand{mycommand}[1]{%
if (#1 != NULL){%
The argument #1 was passed}
else {%
No argument was passed.}}

Obviously this is not valid LaTeX, but hopefully this makes it clear what I am trying to do. Is there a way to do this with ordinary LaTeX? Is it worth switching to LuaLaTeX to accomplish behavior like this?

Best Answer

You can do it easily with xparse:

\documentclass{article}

\usepackage{xparse}

\NewDocumentCommand{\mycommand}{o}{%
  % <code>
  \IfNoValueTF{#1}
    {code when no optional argument is passed}
    {code when the optional argument #1 is present}%
  % <code>
}

\begin{document}

\mycommand

\mycommand[HERE]

\end{document}

This will print

code when no optional argument is passed
code when the optional argument HERE is present

For an environment it's similar

\NewDocumentEnvironment{myenv}{o}
  {\IfNoValueTF{#1}{start code no opt arg}{start code with #1}}
  {\IfNoValueTF{#1}{end code no opt arg}{end code with #1}}

Other code common to the two cases can be added at will. As you see, xparse also allows (but it's not mandatory) to use the argument specifiers also in the end part.

Related Question