8

If I have a command in the form

\newcommand{\TM}[1]{\color{red} $\boldsymbol{#1}$}

how can I call it with an optional parameter for color? What I want is that if it's called like

\TM{\alpha}

it should return a red alpha but if it's called as

\TM[green]{\alpha}

the alpha's color should be green.

3
  • Well, this is very well-known: \newcommand{\TM}[2][red]{{\color{#1}$#2$}} (or, better, \newcommand*{\TM}[2][red]{{\color{#1}$#2$}}). Note the additional pair of braces (this is unrelated to your question, though)!
    – GuM
    Commented Mar 11, 2017 at 2:26
  • @Gustavo Could you explian what is "unrelated" to the question? It is unclear to me, as Latex remains often unclear doing the job well.
    – pzorba75
    Commented Mar 11, 2017 at 3:35
  • The extra pair of curly brackets will stop the rest of your document turning red. But this is unrelated to your question.
    – cfr
    Commented Mar 11, 2017 at 4:36

1 Answer 1

13

An optional parameter is defined by adding a [<opt>] after defining the number of arguments:

enter image description here

\documentclass{article}

\usepackage{xcolor,amsmath}

\newcommand{\TM}[2][red]{\textcolor{#1}{$\boldsymbol{#2}$}}

\begin{document}

\TM{\alpha}

\TM[green!50!black]{\beta}

\end{document}

Note that it's not always a good idea to include math formatting within a command, since it will cause errors if used inside math. For this, LaTeX provides \ensuremath.

To circumvent this, I've used \textcolor{<colour>}{<stuff>} which necessarily puts <stuff> in text mode. As such, a switch to math mode would be okay.

1
  • 1
    \textcolor doesn't actually force text mode (blame the author of the color package;-) Commented Mar 11, 2017 at 12:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .