[Tex/LaTex] Problem with wrapfigure and line breaks in the text

wrapfigure

How can I fix this problem? The text of the second paragraph overwrites the figure and doesn't contain line breaks.

\documentclass[parskip=half]{scrbook}
\usepackage[english]{babel}
\usepackage{graphicx,lipsum,wrapfig}

\begin{document}
\begingroup
\setlength{\columnsep}{30pt}%
\begin{wrapfigure}{r}{0.5\textwidth}
  \centering\includegraphics[width=\linewidth]{example-image-a}
  \caption{A very very very very very very very very long long long caption}
\end{wrapfigure}
foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo 

foo foo foo foo foo foo foofoo foo foo foo foo foo foofoo foo foo foo foo foo foo
\endgroup
\end{document}

Best Answer

As cited in the comment by Harish Kumar, the manual says that the text wrapping should end before the group does. So we need to add another line of text. But we can do this without actually displaying this added text (using, e.g., phantom) like this:

\documentclass[parskip=half]{scrbook}
\usepackage[english]{babel}
\usepackage{graphicx,lipsum,wrapfig}

\begin{document}
\begingroup
\setlength{\columnsep}{30pt}%
\begin{wrapfigure}{r}{0.5\textwidth}
  \centering\includegraphics[width=\linewidth]{example-image-a}
  \caption{A very very very very very very very very long long long caption}
\end{wrapfigure}
foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo

foo foo foo foo foo foo foofoo foo foo foo foo foo foofoo foo foo foo foo foo foo

\phantom{foo}
\endgroup
\end{document}

If this adds too much vertical space, another workaround for this would be to add negative vspace (although bad style, great for quick and dirty workarounds).

Related Question