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.

Werner
  • 603,163
Gabu
  • 995
  • 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 Mar 11 '17 at 02: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 Mar 11 '17 at 03:35
  • The extra pair of curly brackets will stop the rest of your document turning red. But this is unrelated to your question. – cfr Mar 11 '17 at 04:36

1 Answers1

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.

Werner
  • 603,163