Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LaTeX: how to use a required arg as the default for an optional one?

I'm trying to create a LaTeX command with two arguments, one of them optional. Normally I'd do this as

\newcommand{\whatever}[2][default]{first #1 second #2}

where default is the default value for the first argument. But for this command I want the value of the second argument to be used as the default value for the first argument - that is, I want

\whatever{blah}
\whatever{foo}
\whatever[lol]{rofl}

to be equivalent to

\whatever[blah]{blah}
\whatever[foo]{foo}
\whatever[lol]{rofl}

Does anyone know how to do this? I can drop down to plain TeX if necessary.

like image 633
David Z Avatar asked Feb 28 '23 21:02

David Z


2 Answers

The LaTeX kernel has an inbuilt method of doing this, although it's not widely used. Here's an example:

\makeatletter
\newcommand\@foo[2][]{[1: #1, 2: #2.] }
\newcommand\foo{\@dblarg\@foo}
\makeatother

\foo{same}
\foo[hello]{world}

Obviously, the \makeatletter commands can be dropped if you're doing this inside a .sty or .cls file.

like image 144
Will Robertson Avatar answered Apr 28 '23 11:04

Will Robertson


An ugly hack:

\usepackage{ifthen}

...

\newcommand{\whatever}[2][uniquenonesense]{
   ... 
   \ifthenelse{\equal{#2}{uniquenonesense}}{#1}{#2}
   ...
}

Presumably you wanted something cleaner, but that's what I've got.

Depending on your semantics, uniquenonesense might be empty.

like image 37
dmckee --- ex-moderator kitten Avatar answered Apr 28 '23 11:04

dmckee --- ex-moderator kitten