12

How do you go about redefining a command such as \underbrace, which uses an "uncommon" delimiter, i.e. _, between its two arguments, so that the redefined command be usable in exactly the same way as the original one?

As an example, consider the command \redub ("red underbrace") defined below on the basis of \underbrace:

\documentclass{article}
\usepackage{amsmath}
\usepackage{xcolor}

\newcommand\redub[2]{%
    \colorlet{currentcolor}{.}%
    \color{red}%
    \underbrace{\color{currentcolor}#1}_{\color{red}#2}%
    \color{currentcolor}%
}
\begin{document}
\[
  \redub{e^{-x^2}}{\text{foo}} + \redub{e^{-2x^2}}{\text{bar}}
\]
\end{document}

enter image description here

For someone who commonly uses \underbrace, it would be much easier to be able to use the command just like \underbrace, i.e. like this:

\redub{}_{};

not like that:

\redub{}{}.

19

The simplest way is

\newcommand{\redub}{} % make sure it's definable
\def\redub#1_#2{%
    \colorlet{currentcolor}{.}%
    \color{red}%
    \underbrace{\color{currentcolor}#1}_{\color{red}#2}%
    \color{currentcolor}%
}

using lower level features.

You might want to add a check for a missing _:

\makeatletter
\newcommand{\redub}{} % make sure it's definable
\def\redub#1{%
  \@ifnextchar_%
    {\@redub{#1}}
    {\@latex@warning{Missing argument for \string\redub}\@redub{#1}_{}}%
}
\def\@redub#1_#2{%
    \colorlet{currentcolor}{.}%
    \color{red}%
    \underbrace{\color{currentcolor}#1}_{\color{red}#2}%
    \color{currentcolor}%
}
\makeatother

Minimal example:

\documentclass{article}
\usepackage{amsmath}
\usepackage{xcolor}

\makeatletter
\newcommand{\redub}{} % make sure it's definable
\def\redub#1{%
  \@ifnextchar_%
    {\@redub{#1}}
    {\@latex@warning{Missing argument for \string\redub}\@redub{#1}_{}}%
}
\def\@redub#1_#2{%
    \colorlet{currentcolor}{.}%
    \color{red}%
    \underbrace{\color{currentcolor}#1}_{\color{red}#2}%
    \color{currentcolor}%
}
\makeatother

\begin{document}
\[
  \redub{e^{-x^2}}_{\text{foo}} + \redub{e^{-2x^2}}_{\text{bar}}
\]

$\redub{A}X$
\end{document}

enter image description here

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.