LaTeX: optional arguments with square brackets
Note: Without a MWE I will remove \end{tabular}
from the definition of your macro and ignore the fact that you declare two argments (one optional, one mandatory) but use only #1
.
An optional argument behaves quite different from normal arguments and groups as it is catched by TeX with the help of the [
/]
delimiters.
With a macro is defined with
\newcommand{\monkeyBeans}[2][]{\parbox{4in}{#1}}
and called with
\monkeyBeans[$[a, b]$]{yo monkey}
#1
will be $[a, b
. #2
will be $
and in this case discarded as #2
is not used in your macro definition. Therefore, \monkeyBeans[$[a, b]$]{yo monkey}
is expanded to
\parbox{4in}{$[a, b}]{yo monkey}
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'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.