More than one optional argument for newcommand

Try the LaTeX 3 package xparse. Example:

\documentclass{article}
\usepackage{xparse}
\NewDocumentCommand{\foocmd}{ O{default1} O{default2} m }{#1~#2~#3}
                                %     ⤷ #1        ⤷ #2    ⤷ #3

\begin{document}
  \foocmd{foo} \par
  \foocmd[nondefault1]{foo} \par
  \foocmd[nondefault2][notfoo2]{foo} \par
\end{document}

Result of above's LaTeX code

You may read the documents for more information.


You've got answers for other approaches, so here is the basics using the kernel only. You'll need to define your macros by hand, something like

\makeatletter
\def\mycommand{%
   \@ifnextchar[%
     {\mycommand@i}
     {\mycommand@i[<default-for-1>]}%
}
\def\mycommand@i[#1]{%
   \@ifnextchar[%
     {\mycommand@ii{#1}}
     {\mycommand@ii{#1}[<default-for-2>]}%
}
\def\mycommand@ii#1[#2]#3{%
  % Do stuff
}
\makeatother

This can of course be extended to more complex cases. (Here, I'm leaving it up to you whether to make your function \long or not. If you want part of it to be long, then all of the internal macros should be long. The xparse approach allows this to vary between arguments, based on some internal shuffling.)


\usepackage{twoopt}
\newcommandtwoopt{\xyz}[3][Def1][Def2]{Something with #1, #2 and #3}

There are also \renewcommandtwoopt and \providecommandtwoopt.

However the xparse package (part of the LaTeX3 package tree, but works also with LaTeX2e) provides \DeclareDocumentCommand that gives great flexibility in defining commands with optional arguments in every position and also *-versions.

Historical note

In TeX Live there is a newcommand.py Python script accompanied by documentation accessible by texdoc newcommand. For example, to obtain code for defining a command with two optional arguments and a mandatory one, one launches

python /usr/local/texlive/2011/texmf-dist/doc/latex/newcommand/newcommand.py

and at the prompt % Prototype: answers with

MACRO twoopt OPT[#1={Def1}] OPT[#2={Def2}] #3

where \twoopt is the macro we want to define. The script will build a skeleton for defining the macro:

\makeatletter
\newcommand{\twoopt}[1][Def1]{%
  \@ifnextchar[{\twoopt@i[{#1}]}{\twoopt@i[{#1}][{Def2}]}%
}

\def\twoopt@i[#1][#2]#3{%
  % Put your code here.
  % You can refer to the arguments as #1 through #3.
}
\makeatother

The commented lines should be replaced by the actual code.

With the specification

MACRO finalopt #1 OPT[#2={default}]

one defines a macro with a mandatory argument followed by an optional one:

\makeatletter
\newcommand{\finalopt}[1]{%
  \@ifnextchar[{\finalopt@i{#1}}{\finalopt@i{#1}[{default}]}%
}

\def\finalopt@i#1[#2]{%
  % Put your code here.
  % You can refer to the arguments as #1 and #2.
}
\makeatother