1

I want to implement a macro, that uses the command passed in the first argument as the command itself, not as the content passed by evaluating it. Something like:

\newcommand{\foo}{bar}
% definition
\newcommand{\mycmd}[1]{
    \dosomethingwith{???}% I want \foo here, not 'bar'
}
\mycmd{\foo}
  • 6
    I don't follow: if you do \mycmd{\foo} then #1 in \mycomd is '\foo'. – Joseph Wright Sep 11 '13 at 9:38
  • 5
    As Joseph says, #1 will be \foo and not bar: TeX won't do macro expansion when absorbing arguments. So you should be clearer about your aims. – egreg Sep 11 '13 at 9:45
  • Thanks on that hint. I didn't know the macro expansion works in that way. I wanted to do something like: \newcommand{\mycmd}[1]{\expandafter\renewcommand{#1}{BAR}} and I got it now with \expandafter. – delbertooo Sep 11 '13 at 9:53
  • Welcome to TeX.SX! You might have a look on our our starter page if you wish to familiarize yourself further with our format. – Claudio Fiandrino Sep 11 '13 at 10:11
  • 1
    \expandafter\renewcommand{#1 expands { which is not expandable, you want \expandafter\renewcommand\expandafter{#1 or just \expandafter\renewcommand#1 – David Carlisle Sep 11 '13 at 11:00
2

With the following preliminary code

\newcommand{\foo}{bar}
% definition
\newcommand{\mycmd}[1]{%
    \dosomethingwith{#1}%
}

the call

\mycmd{\foo}

will make TeX replace \mycmd and its argument \foo with

\dosomethingwith{\foo}

and no expansion of \foo will be attempted yet. What TeX will do is expand \dosomethingwith, which might mean looking for an argument, but again \foo will still not be expanded.

So, the test case you outline in the comments is

\newcommand{\foo}{bar}
% definition
\newcommand{\mycmd}[1]{%
    \renewcommand{#1}{BAR}%
}

and attempting

\mycmd{\foo}

will do exactly what's espected, that is, changing the meaning of \foo.

Example document

\documentclass{article}

\begin{document} % we want to use `\meaning` for showing the meaning of commands

\newcommand{\foo}{bar}

\texttt{\meaning\foo}

\newcommand{\mycmd}[1]{%
    \renewcommand{#1}{BAR}%
}
\mycmd{\foo}
\texttt{\meaning\foo}

\end{document}

enter image description here

1
\expandafter\renewcommand{#1 

expands { which is not expandable, you want

\expandafter\renewcommand\expandafter{#1

or just

\expandafter\renewcommand#1
  • Of course, \newcommand{\mycmd}[1]{\expandafter\renewcommand\expandafter{#1}{BAR}} with \mycmd{\foo} will result in a disaster if \foo expands to bar as in the example. – egreg Sep 11 '13 at 13:05
  • @egreg yes answering the implied question in the comments rather than the question as written, maybe the OP could clarify the original question... – David Carlisle Sep 11 '13 at 13:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.