Newcommand with Optional Argument – How to Define Shortcuts in Derivative Package

macrosoptional arguments

The recent release (June 2021) of the derivative package includes the command \odif which can be used to typeset differentials.

For instance, \odif[order={3}]{x} yields something like d^3x.

Because I am replacing the physics package, I would like to add a \newcommand which replaces \dd[3]{x} with \odif[order={3}]{x}.

I know that \newcommand{\dd}[1]{\odif{#1}} would replace \dd{x} with \odif{x} but I don't know how to handle the optional argument.

Best Answer

You can supply a marker when the optional argument is empty to decide if there is an optional argument.

\newcommand*\dd[2][\relax]{\ifx\relax#1\odif{#2}\else \odif[order={#1}]{#2}\fi}

xparse has a mechanism for this:

\NewDocumentCommand\dd{ o m }{\IfNoValueTF{#1}{\odif{#2}}{\odif[order={#1}]{#2}}}