5

I like to define a macro with an optional parameter. As an example, consider a macro for the differential:

\documentclass[11pt]{article}
\usepackage{amsmath}
\usepackage{bm}

\newcommand\drm{\mathop{}\!\mathrm{d}}
\newcommand\Drm[1]{\mathop{}\!\mathrm{d^#1}}

\begin{document}

\begin{equation}
\int\limits_0^\infty \drm t \, f(t)
\end{equation}

\begin{equation}
\int\limits_0^\infty \Drm{3} r \, g(\bm{r})
\end{equation}

\end{document}

The macros for the differentials are taken from an earlier post. Apart from my own question, why is there a \mathop{} in the definition of the differentials? But second, how can I achieve a macro that puts both of them together? Like it is with \sqrt, where you can do \sqrt{x} or \sqrt[3]{x}. I like to do \drm or \drm[3].

  • It's best not to ask two questions at once. Nevertheless, are you aware of the package physics? – Johannes_B Dec 13 '13 at 9:39
  • No I am not. Looking into it. – DaPhil Dec 13 '13 at 9:41
  • What's the advantage from writing \Drm{3} instead of \drm^{3}? I see none. – egreg Dec 13 '13 at 13:27
12

Are you sure you want

\newcommand\Drm[1]{\mathop{}\!\mathrm{d^#1}}

rather than

\newcommand\Drm[1]{\mathop{}\!\mathrm{d}^{#1}}

which would be rather more usual I think (It makes no difference if the superscript is a digit but try n) and you certainly need the {} around #1 if there might be two digits.

To make the argument optional you could use

 \newcommand\Drm[1][]{\mathop{}\!\mathrm{d}^{#1}}

But that makes ^{} in the empty case which can affect spacing so better is

 \newcommand\Drm[1][\relax]{%
   \mathop{}\!\mathrm{d}\ifx\relax#1\relax\else^{#1}\fi}

where you omit the superscript in the default case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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