# The wrapfigure environment breaks when put inside another environment

I've tried using the wrapfigure environment (from the wrapfig) package, but it acts in such a way that I can't use it.

Consider the following MWE:

\documentclass{article}
\usepackage{wrapfig,mwe}

\newenvironment{testenv}{%
\begin{wrapfigure}{r}{.5\linewidth}%
\vspace{.5\baselineskip}%
}{%
\end{wrapfigure}}

\begin{document}
\begin{wrapfigure}{r}{.5\textwidth}\vspace{.5\baselineskip}
This is some dummy text.  This is some dummy text.
This is some dummy text.  This is some dummy text.
\end{wrapfigure}
\lipsum[1]

\begin{testenv}
This is some dummy text.  This is some dummy text.
This is some dummy text.  This is some dummy text.
\end{testenv}
\lipsum[2]
\end{document}


This produces the output below. What causes this error, and is there any way to fix it?

While a fix for wrapfigure would be cool, if a simpler fix exists for my specific use case, I'd be grateful to have a peek at it :).

Use the command-form of the wrapfigure environment:

\documentclass{article}
\usepackage{wrapfig,lipsum}% http://ctan.org/pkg/{wrapfig,lipsum}

\newenvironment{testenv}{%
\wrapfigure{r}{.5\linewidth}%
\vspace{.5\baselineskip}%
}{%
\endwrapfigure}

\begin{document}
\begin{wrapfigure}{r}{.5\textwidth}\vspace{.5\baselineskip}
This is some dummy text.  This is some dummy text.
This is some dummy text.  This is some dummy text.
\end{wrapfigure}
\lipsum[1]

\begin{testenv}
This is some dummy text.  This is some dummy text.
This is some dummy text.  This is some dummy text.
\end{testenv}
\lipsum[2]
\end{document}

• Does the original issue then revolve around grouping? I don't know terribly much about \begin and \end, but I do know they they begin and end groups as well. – Sean Allred Aug 2 '13 at 11:32
• @SeanAllred: This is related to grouping, yes, and using the command-form circumvents that. From the wrapfig documentation (p 1): "Some idiosyncrasies:... If you put a wrapfigure in a \parbox or a minipage, or any other type of grouping, the text wrapping should end before the group does." In this case, it does not (\end{testenv} occurs before the text wrapping). – Werner Aug 2 '13 at 16:26
• I read that part of the documentation, but I thought it had meant something along the lines of 'you must end the content the wrapfigure wraps before you end the group'. What exactly then does it mean by 'text wrapping'? – Sean Allred Aug 2 '13 at 17:12
• @SeanAllred: I read it that "text wrapping" refers to the text being wrapped. So your group testenv ended even before the text-to-be-wrapped was found. I think there is some \aftergroup usages in wrapfig.sty that could imply this requirement. – Werner Aug 2 '13 at 17:50