# Capture a macro's subscripts/superscripts by the macro

Is it possible to capture sub-/superscripts added to a macro by the macro itself? Consider the following example:

\newcommand{\fx}[1]{f(x)}
\fx{x}   % -> f(x)
\fx{x}^2 % -> f(x)²


Now the question, is it possible to do something like

\newcommand{\fx}[1]{f<superscript-here>(x)}
\fx{x}^2 % -> f²(x)


of course not in this way, but in principle using some hacky TeX stuff?

-

I find a notation such as "f²(x)" ambiguous; I know that it's traditional for the trigonometric functions, but I believe that

f(x)²

is far less ambiguous, when we agree that "f(x)" has precedence over other algebraic expressions.

However, here it is.

\documentclass{article}
\makeatletter
\newcommand{\fx}[1]{\def\buergi@arg{#1}\@ifnextchar^\buergi@fexp{f(#1)}}
\def\buergi@fexp^#1{f^{#1}(\buergi@arg)}
\makeatother

\begin{document}
$\fx{x}\quad\fx{x}^2$
\end{document}


You carry over the argument and test whether the argument is followed by ^; in this case you typeset f^{<exponent>}(<argument of \fx>), otherwise you do the simple thing.

A more general macro might be

\documentclass{article}
\makeatletter
\newcommand{\fx}[2][f]{%
\def\buergi@arg{#2}%
\@ifnextchar^{\buergi@fexp{#1}}{#1(#2)}}
\def\buergi@fexp#1^#2{#1^{#2}(\buergi@arg)}
\makeatother

\begin{document}
$\fx{x}\quad\fx{x}^2$

$\fx[g]{x}\quad\fx[g]{x}^2$
\end{document}


which gives

-
Thanks again egreg, I have to admit the example was stupid. I agree that this notion is ambiguous an I don't like it either (except for sin and cos) but that is actually not what I need it for, I thought more of something like f^*(x) or \Psi^\dagger(x) etc. – buergi Nov 20 '12 at 18:30