# 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?

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