[Tex/LaTex] How to renewcommand in newcommand

macros

I have a macro that I use to write units (so that I can write exponents easily), in math or in text mode.

I would like to change the definition of \mu in \upmu (from the upgreek package) only in this macro (not for standard math). This is what I wrote:

\newcommand{\U}[1]{%
    \renewcommand{\mu}{\upmu}
    \ensuremath{\mathrm{~#1}}%
}

It works, but I get an error at compilation:

ERROR: Argument of \@caption has an extra }.

--- TeX said ---
<inserted text> 
                \par 
l.117 ... bla 30\U{\mu K} bla bla}

--- HELP ---
From the .log file...

I've run across a `}' that doesn't seem to match anything.
For example, `\def\a#1{...}' and `\a}' would produce
this error. If you simply proceed now, the `\par' that
I've just inserted will cause me to report a runaway
argument that might be the root of the problem. But if
your `}' was spurious, just type `2' and it will go away.

for the incriminated code:

\caption{bla bla 30\U{\mu K} bla bla}

Best Answer

Fragile commands like \renewcommand have to be \protected when used in moving arguments like the one of \caption (see What is the difference between Fragile and Robust commands? for more info).

Moreover, you have to add a trailing % whenever you don't want to insert extra space (see What is the use of percent signs (%) at the end of lines?).

So you should change your definition to

\newcommand{\U}[1]{%
    \protect\renewcommand{\mu}{\upmu}%
    \ensuremath{\mathrm{~#1}}%
}
Related Question