7

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?

2 Answers 2

11

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

1
  • 1
    two comments: the space following the dash is wider than the space before it, so add \ignorespaces at the end of the first argument. second, there can't be a blank line before \end{example}; if input it's most likely unintended, so this is just a warning. Apr 20, 2016 at 18:19
3

I'm not sure you really want an environment for this. However, you can (ab)use environ.

\documentclass{article}
\usepackage{environ}

\NewEnviron{example}{%
  [\textit{Example} --- \BODY]%
}

\begin{document}

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

\end{document}

enter image description here

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .