Optional argument with \newcommand in LaTeX

  |   Source

In LaTeX, it seems like you can't define a command with a really optional argument, using \newcommand. You can make commands with arguments having a default value though.

Now, I found myself in need of having such a functionality. I had to google a while, but finally found it, so I'm posting it here, both to share knowledge and to remember it in future :)

Suppose you want to do something like \mycmd{foo} and \mycmd{foo}{bla}, doing different things (in my case, I needed to add the second argument enclosed by parenthesis in the TOC and other places, but only if it was present)

Here's the code:

\def\mycmd#1{\def\tempa{#1}\futurelet\next\mycmd@i}% Save first argument
\def\mycmd@i{\ifx\next\bgroup\expandafter\mycmd@ii\else\expandafter\mycmd@end\fi}%Check brace
\def\mycmd@ii#1{...}%Two args
\def\mycmd@end{...}%Single args

In the last two lines of the code, use \tempa for your first argument, and #1 for your second optional argument. If you need spaces there (maybe as part of some text), be sure to escape them with a backslash \.

I think it's expandable for additional arguments, but I haven't tried, and I don't feel like getting my hands dirty with TeX yet ;)

Comments powered by Disqus
Contents © 2013 David Paleino - Powered by Nikola