TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

This question already has an answer here:

I know I can create a new command with an optional parameter with

\newcommand{\mycommand}[2][Hello]{\textbf{#1} #2}

I would like to have the command such that there is an optional parameter which takes the value of the non optional if not specified. Something like this

\newcommand{\mycommand}[2][#2]{\textbf{#1} #2}

Any ideas?

share|improve this question

marked as duplicate by Ryan Reich, Xavier, Stefan Kottwitz May 9 '13 at 6:44

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

I don't know why this popped up just now, being almost a year old, but it is an exact duplicate of tex.stackexchange.com/q/5211/575 – Ryan Reich May 9 '13 at 3:40
Also, that one has a much better accepted answer than the ones here. – Ryan Reich May 9 '13 at 3:41
up vote 15 down vote accepted

LaTeX kernel solution

\def\@mycommand[#1]#2{\textbf{#1} #2}

See this answer for a description of \@dblarg.

xparse solution

\NewDocumentCommand{\mycommand}{o m}
 {\textbf{\IfValueTF{#1}{#1}{#2}} #2}

\IfValueTF{#1}{A}{B} looks whether the optional argument was specified; if it was, it delivers A, otherwise B. In the previous definition, A is #1 and B is #2 as you wished.

The xparse solution is more robust.

share|improve this answer

Using a very elementary approach, you can make the optional argument default to some macro that you can test against:

enter image description here

  \textbf{\ifx\@empty#1\relax#2\else#1\fi} #2}
\mycommand{Second} \par

In the above example, the optional argument to \mycommand is set to \@empty by default (if it's not specified). Using \ifx\@empty#1\relax, you can test whether the default argument is supplied (and therefore, #1 is actually missing). Then, print #2, otherwise, print #1.

share|improve this answer
Thanks, your solutions works as well. – Haatschii Jun 22 '12 at 21:50

Not the answer you're looking for? Browse other questions tagged or ask your own question.