Meaning of square brackets, optional arguments

macrosoptional arguments

I'm a bit confused as to how LaTeX parses square brackets/optional macro arguments.

I'll try to explain what I understood by means of the macro \section which has one optional and one mandatory argument. Please correct me if you think I got anything wrong.

This

\documentclass{article}

\begin{document}
\section ab
\end{document}

finds no optional argument, and a mandatory argument a. b is just text then. With {}, one can group things, so

\section {ab}

takes ab as mandatory argument. The space doesn't matter.

Square brackets [] usually get rendered as square brackets. Unless, it seems, if it could potentially contain optional arguments. This

\section[a]{b}

takes a as optional, b as mandatory argument. Are optional arguments always indicated by square brackets?

This

\section[a][b]{c}

takes a as optional argument, [ as mandatory argument, and b]{c} is just text.

enter image description here

This, too, seems to indicate that square brackets are square brackets if and only if they aren't in their function of optional argument. Is this correct?

Best Answer

Depends on the command. The way arguments are parsed is command specific, not TeX/LaTeX imposed.

Some commands expect optional arguments and then parse the square brackets as the start of optional arguments. Other commands expect no optional arguments and then a square bracket is just an argument.

See these examples:

\documentclass{article}
\usepackage{xparse}


\NewDocumentCommand{\mycmd}{o o m}{\IfValueTF{#1}{first #1}{nothing on one},
  \IfValueTF{#2}{second #2}{nothing on two},
  mandatory #3}
\newcommand\anothercmd[1]{My argument is /#1/}

\begin{document}
\mycmd{Hello}

\mycmd[1]{Hello}

\mycmd[1][2]{Hello}

\anothercmd{test}

\anothercmd[2]{Test}
\end{document}