[Tex/LaTex] How to use one argument as the default value for another

macrosoptional arguments

I'd like to define a command that takes 1, 2 or 3 arguments, and where the 2nd gets the same value as the 1st if it is not defined. I tried

\newcommand\codefrom[3][#1][Matlab]{ ... }

but I get an error saying

! Illegal parameter number in definition of \codefrom.
<to be read again>
                   1
l.57 \newcommand{\codefrom}[3][#1][
                                                              Matlab]

Is there any way to accomplish what I want to do?

Best Answer

You can't accomplish this with one \newcommand. There you can define one optional parameter, and it has to be the first one. There is the twoopt package that defines \newcommandtwoopt for two optional parameters, but I don't think it can handle what you want to achieve. I first thought you would need to use TeX's \def, but here's a solution that's completely free of any \defs and @s:

\documentclass[12pt]{report}
\newcommand\storefirst{}
\newcommand\storesecond{}
\newcommand\codefrom[1]{\renewcommand\storefirst{#1}\codefromi}
\newcommand\codefromi[1][\storefirst]{\renewcommand\storesecond{#1}\codefromii}
\newcommand\codefromii[1][Matlab]{\storefirst, \storesecond, #1}
\begin{document}
\codefrom{first}\par
\codefrom{first}[second]\par
\codefrom{first}[second][third]
\end{document}
Related Question