# New Environment with spacing issues for equations

Preety often i write equations with evenly spaced objects to be centered, like

\begin{equation*}
\hphantom{ \hspace{1cm} {(x\in X)} }
f(x) = Ax + B
\hspace{1cm} {(x\in X)}
\end{equation*}


which works fine. However, i tried defining a \newenvironment for this setup in a natural way and got some errors (when compiling or not). The closest solution i came up is

\newenvironment{eqspaced}[1]{
\begin{center}
$\hphantom{\hspace{1.5cm} {#1}} \displaystyle }{ \hspace{1.5cm} {#1}$
\end{center}
}


but without succes. When applying the macro above, i get

What is wrong with this macro? I was dreaming about putting a second argument for the spacing, but it seems to get pdflatex even angrier.

• you can't use #1 in the end code, the arguments are only available in the begin code, also your first form is a display equation from equation* (presumably from amsmath although you do not mention that) but your definition is making an inline math in \$ why the difference? You provided no test document but you presuably got ! Illegal parameter number in definition of \endeqspaced. after any error it is best not to even look at the generated pdf. Nov 27 '21 at 15:39
• I've tried with equation* but it crash the whole thing. Using center was the only one which got closer (at least it compiles something). Maybe i cant see for beeing dumb, but the build log doesn't show me anything. Nov 27 '21 at 15:48
• you should always provide a small test document not a fragment, but it is hard to imagine you do not get the error shown from your definition. Nov 27 '21 at 16:05

You get errors, don't you? When errors are raised, TeX tries to exit from them as best as it can, but the output will likely be wrong.

The problem is that you cannot use #1 in the end part of \newenvironment.

Solution: use \NewDocumentEnvironment (you may need to do \usepackage{xparse} if running an older version of LaTeX, released earlier than 2020-10-01).

With the optional argument you can set a spacing; the default value, if not specified with the optional argument, is 1cm.

\documentclass{article}
\usepackage{amsmath}

\NewDocumentEnvironment{eqspaced}{O{1cm}m}
{\begin{equation*}\hphantom{\hspace{#1}#2}}
{\hspace{#1}#2\end{equation*}\ignorespacesafterend}

\begin{document}

\begin{eqspaced}{(x\in X)}
f(x)=Ax+B
\end{eqspaced}
Let's verify the centering
\begin{equation*}
f(x)=Ax+B
\end{equation*}
With the optional argument
\begin{eqspaced}[3cm]{(x\in X)}
f(x)=Ax+B
\end{eqspaced}

\end{document}


Note: the code presented earlier (see answer history) worked around a bug in the LaTeX kernel that's now solved with LaTeX2e <2021-11-15> patch level 1 (be sure to have an up-to-date distribution).

• @daleif Oh, yes! Thanks! Dec 7 '21 at 18:03