# Defining optional parameters in \newcommand

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.

• @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 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 Mar 11 '17 at 4:36

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

\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.

• \textcolor doesn't actually force text mode (blame the author of the color package;-) – David Carlisle Mar 11 '17 at 12:04