# How to define d in integral expression for \int \dif x f(x) notation

There seems to be some consensus about defining \dif like this:

\newcommand{\dif}{\mathop{}\!\mathrm{d}}


This looks fine in

\int f(x) \dif x


but not so much in

\int \dif x f(x)


What is the best alternative (or extension) when using the latter notation?

Here's an MWE which nicely shows the difference -- the second line is even shorter than the first:

\documentclass{article}
\newcommand{\dif}{\mathop{}\!\mathrm{d}}
\begin{document}
$\int f(x) \dif x$

$\int \dif x f(x)$
\end{document} Would

\newcommand{\dif}{\mathop{}\!\mathrm{d}#1\mathop{}}


be a good solution? It certainly looks better.

• #1 is usually a ordinary math atom (variable), then there will always a thin space between #1 and \mathop{}. In may situations this space is wrong, e.g. when a closing bracket follows. At the end of a centered equation the centering is then off by a half thin space. Therefore I would at least remove that space: #1\!\mathop{}. A thin space remains, if another ordinary atom (f) or another operator \int follows. – Heiko Oberdiek May 22 '15 at 16:47

You should use a different command for “improperly placed differential”:

\newcommand\ipdif{\mathrm{d}#1\,}


and use it only if followed by other symbols (choose another name, if you want).

With \mathop{}\!\mathrm{d} you'd get an unwanted thin space between the integral symbol and the “d”. If you add a trailing \mathop{} you get two thin spaces between the variable and the following letter or one if a parenthesis follows. You could do

\mathrm{d}#1\mathop{}\!


but this would be the same as just adding \,.

I see no chance of defining a command that can go either at the beginning or at the end of the integrand. Making the decision by looking at the next token would require big tables and several exceptions.

You may define a *-variant, if you prefer:

\usepackage{xparse}

\NewDocumentCommand{\dif}{sm}{%
\IfBooleanTF{#1}
{% * variant, we are at the beginning
\mathrm{d}#2\,%
}
{% normal variant
\mathop{}\!\mathrm{d}#2%
}%
}


and use

$\int f(x)\dif{x} = \int \dif*{x} f(x)$

• Thanks for this. I think it should be #2 instead of #1 in the normal and star variants. – imj Mar 3 '18 at 17:56
• @imj Sure! Sorry for the mistake. – egreg Mar 3 '18 at 18:04