Better automatic spacing of differential d?

\operatorname turns d into an operator. If an ordinary math atom follows (x), then TeX sets a thin space that is negated by \!. However, TeX does not set a space after an operator if the following math atom belongs to categories "open", "close", "punct", or "inner" (\scriptstyle/\scriptscriptstyle). A fix would be to add an empty math ord atom (\mathord{} or an empty sub formula {}), then TeX always sets a thin space, canceled by \!. Macro \der behaves on the left-hand side as an operator and on its right-hand side as an ordinary math atom. Now both cases work as expected:

\documentclass{article}
\usepackage{amsmath}
\newcommand{\der}{\operatorname{d\!}{}}
\begin{document}
\[
  \der(x^7) \quad \der x
\]
\end{document}

Result

Variation

The d can be put both in the operator atom or the ordinary atom, as suggested in the comment of Manuel and the comment of egreg (without \mathrm):

\mathop{}\!\mathrm{d}

Fonts for d

  • \lim, \sin and friends are using the font \operator@font. Package amsmath then provides macro \operatorname. But the former can also be used without an additional package:

    \makeatletter
    \newcommand*{\der}{%
      \mathop{\kern\z@\operator@font d}\!{}%
    }
    \makeatother
    

    \kern\z@ prevents that \mathop centers the symbol.

    Or with d in the ordinary atom:

    \makeatletter
    \newcommand*{\der}{%
      \mathop{}\!{\operator@font d}%
    }
    \makeatother
    
  • Font \mathrm is easier to use (no @ in the name):

    \newcommand*{\der}{%
      \mathop{}\!\mathrm{d}%
    }
    

    or a little more complex, again the \kern prevents vertical centering:

    \newcommand*{\der}{%
      \mathop{\kern0pt\mathrm{d}}\!{}%
    }
    
  • The italics variant:

    \newcommand*{\der}{%
      \mathop{}\!d%
    }%
    

    or

    \newcommand*{\der}{%
      \mathop{\kern0pt d}\!{}%
    }
    

    italics


Packages are written by good and nice people keeping lazy and ignorant people like me in mind. Instead of re-inventing things, it is better start finding a suitable package and use it. In this case, physics package (as noted by Johannes) offers \dd macro. A screen shot of the relevant part of the physics documentation:

enter image description here

And a sample code:

\documentclass{article}
\usepackage{physics}
\begin{document}
  \[
  \dd(x^7) \quad \dd x
  \]
\end{document}

enter image description here