Conditionally Remove Brackets
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}
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).
with \smash
Since you want an optional argument I think you should use the presence of the argument (rather than it being empty) as the test so
\makeatletter
\newcommand\Af{\@ifnextchar[\@Af\@@Af}
\def\@@Af{\mathbf{A}}
\def\@Af[#1]{\@@Af_{(#1)}}
\makeatother
...
\Af ... \Af[x] ...
I usually use etoolbox
Something like (note your example does not use an optional argument)
\newcommand\Af[1][]{\mathbf{A}\ifblank{#1}{}{_{(#1))}}}
ought to do the trick (untested)
Usage:
$\Af$ will just give $\mathbf{A}$
and
$\Af[n]$ will give $\mathbf{A}_{(n)}$
BTW: One can do even cooler things with the xparse
package such as instead of $\Af[n]$
we can use $\Af_{n}$
to get the same result (see the argument type e
in the xparse
manual), aka we pick up the n
from the subscript and wrap ()
around it.