4

Why this not work. I suspect an expansion problem ...

\documentclass{standalone}

\newcommand{\foo}[1][foo]{#1}
\newcommand{\Fbox}[1][bla]{\fbox{#1}}

\begin{document}

\Fbox[\foo[bla]]

\end{document}
Tarass
  • 16,912

1 Answers1

5

The problem is that your square brackets are ambiguous.

When your write \Fbox[\foo[bla]] the \Fbox macro thinks that its' (optional) argument is \foo[bla. Then \foo tries to execute with argument [bla so it complains because its' argument does not conform to the expected syntax.

As egreg says, to fix the problem you need to write \Fbox[{\foo[bla]}].

As Symbols says in the comments, if you use the \NewDocumentCommand from the xparse package then your syntax becomes legal because xparse is slightly smarter in how it matches brackets/delimiters. In full detail, this works:

\documentclass{standalone}
\usepackage{xparse}
\NewDocumentCommand\foo{O{foo}}{#1}
\NewDocumentCommand\Fbox{O{bla}}{\fbox{#1}}

\begin{document}
    \Fbox[\foo[bla]]
\end{document}

The xparse package is really cool. You can use it define macros with many optional arguments, in any order you like, with or without defaults, with different delimiters, with stars, with bells, ... OK, not with bells but it is one of my favourite packages:) As another silly example,

\NewDocumentCommand\fock{D|>\lambda}{|#1\rangle}% optional argument between |...>

defines a macro that, by default, produces the same as |\lambda\rangle and where the optional arguments are given as \fock|\mu>, which expands to |\mu\rangle. (Of course, this should always be used in math-mode.

  • 3
    Would you like to say something about xparse? It is not well-explained in egreg's comment and this is a good chance. – Symbol 1 Aug 11 '15 at 14:05
  • @Symbol1 Good point. You are obviously more adept at reading egreg's comments than I am as I see no mention of xparse there:) –  Aug 11 '15 at 22:55
  • For about 20 seconds I was (also) wondering where the comment goes. Turns out it becomes This question already has an answer here – Symbol 1 Aug 12 '15 at 01:47