Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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].

share|improve this question
    
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

1 Answer 1

up vote 12 down vote accepted

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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