# [Tex/LaTex] 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}[1]{\mathop{}\!\mathrm{d}#1\mathop{}}


be a good solution? It certainly looks better.

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

\newcommand\ipdif[1]{\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)$