Second optional argument for newcommand to be the same of the first in case it is not specified
The standard \newcommand
doesn't support it. The kernel provides \@dblarg
:
\makeatletter
\newcommand{\mypar}{\@dblarg\@mypar}
\def\@mypar[#1]#2{#2\paren{#1}}
\makeatletter
However, you can do it more robustly and easily with xparse
:
\usepackage{xparse}
\NewDocumentCommand{\mypar}{O{#2}m}{#2\paren{#1}}
Full example:
\documentclass{article}
\usepackage{xparse}
\newcommand{\paren}[1]{\left(#1\right)} %this is just an example command
\NewDocumentCommand{\mypar}{O{#2}m}{#2\paren{#1}}
\begin{document}
$\mypar{a}$
$\mypar[b]{a}$
\end{document}
Not that I endorse that definition of \paren
, of course. ;-)
The latex format has a standard command for doubling an optional argument in this way (as used for \section[zz]{zz}
)
\documentclass{article}
\newcommand{\xmypar}[2][]{#2\left(#1\right)} %this is just an example command
\makeatletter
\newcommand\mypar{\@dblarg\xmypar}
\makeatother
\begin{document}
$\mypar{a}$
$\mypar[b]{a}$
\end{document}
You can check for an empty argument in #1
and use it to condition on displaying either #1
or #2
:
\documentclass{article}
\usepackage{mleftright}
\newcommand{\paren}[1]{\mleft(#1\mright)} %this is just an example command
\newcommand{\mypar}[2][]{%
\if\relax\detokenize{#1}\relax #2\else #1\fi\paren{#2}}
\begin{document}
$A = \mypar{a} = \mypar[a]{a} \neq \mypar[b]{a}$
\end{document}
The following definition is a little simpler, but also works:
\newcommand{\mypar}[2][\relax]{%
\ifx\relax#1\relax #2\else #1\fi\paren{#2}}