[Tex/LaTex] Suppressing whitespace at end of environment

environmentsspacing

This must have been answered before, but I'm afraid I can't find it. I'm defining an environment and I want the end block to be formatted immediately after the end of the contents, without intervening horizontal space. Here's a MWE:

\documentclass{article}
\newenvironment{example}{[\textit{Example} --- }{]}
\begin{document}
\begin{example}
This is an example.
\end{example}
\end{document}

Obviously I can achieve this by putting a % on the end of the contents line, e.g.

\begin{example}
This is an example.%
\end{example}

… but that's not practical as I only have control of the environment definition, not the use of it. Is there anything I can add to the definition of the environment to kill the horizontal space that otherwise gets inserted?

Best Answer

Use \unskip before the ] in the closing part of the environment definition. This will eat up any space characters prior to the ].

EDIT to heed Barbara's comment to remove stray space following em-dash. And as she notes, one cannot have a blank line before \end{example} without automatically introducing a paragraph break.

\documentclass{article}
\newenvironment{example}{[\textit{Example} ---}{\unskip]}
\begin{document}
\begin{example}
This is an example.
\end{example}
\end{document}

enter image description here

Furthermore, if you wish not to have the blank space after the closing ], you need \ignorespacesafterend, as in

\documentclass{article}
\newenvironment{example}{[\textit{Example} ---}{\unskip]\ignorespacesafterend}
\begin{document}
\begin{example}
This is an example.
\end{example}
xxx
\end{document}

enter image description here

Related Question