1

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?

1
  • It depends. You can have macros that has two or more optional args in []. Fx in the memoir class \sectrion[a][b]{c} works. In the standard class \section has one optional arg, here it found one and stops looking for more and then it take the next [ as the value for the mandatory arg. Nowadays using xparse one can define al sorts of argument even optional {} arguments (which can be useful in some circumstances event if it is discouraged)
    – daleif
    Commented May 17, 2022 at 9:47

1 Answer 1

3

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}
1
  • 2
    Good answer. Just so people remembers it, on modern LaTeX installations the line \usepackage{xparse} is not necessary. The functionality is now build into the kernel. But it does not hurt to have it there for users on old systems, or if one want to use the features from xparse what wasn't added to the kernel, eg the optional {} argument.
    – daleif
    Commented May 17, 2022 at 10:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .