LaTeX is trying to add a missing $ that I don't want to the following code. Minimal working example:




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

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


If I try any of the following lines in my document instead of the call to monkeyBeans, there is no error:

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

What is the deal with square brackets in optional arguments?

  • 4
    Where is the rest of the tabular that is ended in \monkeyBeans? A minimal working example (MWE) would really help here. It should start with \documentclass{...} and end with \end{document}.
    – Werner
    Nov 28 '12 at 3:15
  • 5
    You will need to enclose an optional argument with square brackets in braces (i.e. \monkeyBeans[{$[a, b]$}]{yo monkey} or [${[a, b]}$], …) otherwise the inner/first ] is used as the end of your optional argument, and then all hell breaks loose. Nov 28 '12 at 5:04
  • 5
    Does this answer your question? Bug? LaTeX misparses nested optional arguments
    – user202729
    Nov 7 at 15:19

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


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


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:




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

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


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

Not the answer you're looking for? Browse other questions tagged or ask your own question.