Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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
    
    
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
add comment

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.

2 Answers

up vote 13 down vote accepted

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.

share|improve this answer
add comment

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

enter image description here

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

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

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