# New command with optional argument being first argument [duplicate]

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?

-

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

– Peter Grill Nov 3 '12 at 15:53
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

## LaTeX kernel solution

\makeatletter
\newcommand{\mycommand}{\@dblarg\@mycommand}
\def\@mycommand[#1]#2{\textbf{#1} #2}
\makeatother


See this answer for a description of \@dblarg.

## xparse solution

\usepackage{xparse}
\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.

-

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

\documentclass{article}
\makeatletter
\newcommand{\mycommand}[2][\@empty]{%
\textbf{\ifx\@empty#1\relax#2\else#1\fi} #2}
\makeatother
\begin{document}
\mycommand{Second} \par
\mycommand[First]{Second}
\end{document}


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.

-
Thanks, your solutions works as well. – Haatschii Jun 22 '12 at 21:50