Typing \spec[{\commu[2]{C}}]{x}
would solve the problem, but I think you can enjoy a different solution with xparse
, which allows to take care of some other small issues.
I've made two adjustments: first remove \left
and \right
whose only effect is to add unwanted horizontal space before and after the parentheses; second, add the subscript only if present.
There is a difference between no subscript and an empty one; in the latter case TeX adds a horizontal space of size \scriptspace
(default value is 0.5pt); in the example I make it very large to show what happens. The length 0.5pt is small, but noticeable when present.
The syntax for the definition of \spec
is that it has an optional argument o
and a mandatory one. If the optional argument is present in the later input, the condition \IfValueT
is true and the relative tokens are used (it's a shorthand for \IfValueTF{_{#1}}{}
, here in the false case we do nothing).
In the definition of \commu
, the optional argument receives a default value of 1, so it's denoted as O{1}
.
With expl3
(on which xparse
is based) the loop can be greatly simplified.
\documentclass{article}
\usepackage{xparse}
\NewDocumentCommand{\spec}{om}{%
\sigma
\IfValueT{#1}{_{#1}}%
(#2)%
}
\ExplSyntaxOn % we need to access lower level functions; here spaces are ignored
\NewDocumentCommand{\commu}{O{1}m}
{
#2\prg_replicate:nn { #1 } { ' }
}
\ExplSyntaxOff
\begin{document}
$\spec[\commu[2]{C}]{x}$ % no braces required
\bigskip
% let's show why \IfValueT is necessary
\setlength{\scriptspace}{20pt}
$\spec{x}$
$\sigma_{}(x)$ % what you'd get without the trick
\end{document}
Note that no additional braces are necessary here.
\commu[2]{C}
rather thanC''
?C''
which is shorter than\commu[2]{C}
. It was just to note that may be you did not need the macro ;)