[Tex/LaTex] Conditionally remove the space before a one-letter operator

math-modemath-operatorsspacing

I'm pursuing the Math Expectation operator (\mathbb{E}).

As \DeclareMathOperator is not very good for one-letter operators (since it adds some spacing after itself), I use a plain \newcommand. But here comes the problem that there's no space before it, so writing something like X \MyExpct X turns into something without spaces, while I would like to see a space between the first X and \MyExpct.

But adding a spacing into \newcommand before \mathbb{E}, like

\newcommand{\MyExpct}{\,\mathbb{E}}

fails when my operator stand in the beginning of an expression! So what I want is a space which would be added before the operator if something (but not a binary operation or a opening bracket!) stands before it, and which would be removed otherwise.

I tried to play with \unskip, \ignorespaces, and even looked into how \DeclareMathOperator deals with it (via \kern) but failed to find the solution.

Best Answer

The rule for a math operator is that in case it's preceded/followed by an ordinary symbol, then a thin space is inserted. This is what's wanted in cases such as

$a\log b$

where we do want a thin space before and after “log”. In a case such as

$a\log(bc)$

the space is inserted only before “log”.

I don't know why you don't want your operator to behave differently; perhaps you don't want to add parentheses and trust on the different shape of the letter for visual distinction. So here's the way:

\newcommand{\MExp}{\mathop{}\!\mathbb{E}}

If \MExp is preceded by an ordinary operator, the thin space will be inserted. However, since the empty \mathop is followed by an ordinary symbol, it would always insert a thin space, that we remove with \!.

\documentclass{article}
\usepackage{amsmath,amssymb}
\newcommand{\MExp}{\mathop{}\!\mathbb{E}}

\begin{document}
X$\MExp$ has no space

$X \MExp X$ shows space and no space
\end{document}

enter image description here

Related Question