[Tex/LaTex] Conditionally Remove Brackets

conditionalsmacros

I'm trying to create a command with an optional argument using

\newcommand{\Af}[1]{{\mathbf{A}_{(#1)}}

where the argument is a number.

However, I'd like that if no argument is given the bracket were dropped.

Question

How could I define a command which decides whether or not write the brackets?

Best Answer

Another solution using xparse.

\documentclass{article}

\usepackage{xparse}

\NewDocumentCommand{ \Af }{ o }{%
    A\IfValueT{#1}{_{(#1)}}%
}
\NewDocumentCommand{ \Bf }{ d() }{%
    A\IfValueT{#1}{_{(#1)}}%
}

\begin{document}
no argument: $\Af$

with argument: $\Af[x]$

no argument: $\Bf$

with argument: $\Bf(x)$
\end{document}

result

xparse uses a different (an in my eyes easier and more flexible) syntax to define a command. The second argument of \NewDocumentCommand takes a list defining the arguments, e.g. o for an optional an m for a mandatory argument. With \If(No)Value(TF) you can test whether the argument has a value. (TF) can be T or F to test only one case or TF to differentiate between both the latter case has there arguments, e.g. {#1}{true code}{false code}. With d as argument specifier (see \Bf definition) you can even define the delimiting symbols, () in this case, so the code equals the output even more.

As daleif said you can add a \smash to the subscript to prevent it form affecting the line spacing.

\NewDocumentCommand{ \Afs }{ o }{%
    A\IfValueT{#1}{_{\smash{(#1)}}}%
}

without \smash (exaggerating example using \sum and \left…\right to get flexible parens).
without smash

with \smash
with smash

Related Question