LaTeX: optional arguments with square brackets



No wonder there's a $ missing! I'd miss it, too. With a macro \monkeyBean defined as \newcommand{\monkeyBean}[1][]{\parbox{4in}{#1}}  and used with \monkeyBean[$[a, b]$]yo monkey  It's even clearer what happens, as TeX complies twice about an missing $ because that line expands to

\parbox{4in}{$[a, b}$]yo monkey


and “]yo monkey” is typeset in math mode, too.

Solution: Enclose optional arguments with a ] in braces, so that they get grouped:

\monkeyBean[{$[a, b]$}]
\monkeyBeans[{$[a, b]$}]{yo monkey}

-
Qrrbrbirlbel: Thank you, this was extremely informative and clear. You even got around my copy-paste error in the original question! It makes some sense, that LaTeX wouldn't notice the entering/exiting of math mode inside the square brackets. I was a bit surprised that: \monkeyBeans[([a, b])]{yo monkey} also causes the error. –  Kyle Nov 28 '12 at 14:06

Qrrbrbirlbel's solution is the standard LaTeX2e approach, and is certainly what you have to do for an arbitrary command. The LaTeX3 package xparse deals with the nesting in a cleaner way:

\documentclass[letter,12pt]{article}
\usepackage{xparse}

\NewDocumentCommand{\monkeyBeans}{O{}m}{%
\parbox{4in}{#1}%
}

\begin{document}

\parbox{4in}{$[a, b]$}

\monkeyBeans[$[a, b]$]{yo monkey}

\end{document}


which works of course only if you are defining the command where [] nesting is required.

-