Why does this forest tree in wrapfig go out of the textwidth area?

\begin{wrapfigure}{r}{0.4\textwidth}\centering

If you want it not by trial and error, write the contents first in a box:

\documentclass{article}
\usepackage{forest}
\usepackage{wrapfig}
\usepackage{blindtext}
\usepackage{graphicx}
\newsavebox\ForestBox
\begin{document}

\savebox\ForestBox{%
    \begin{forest}%
        for tree={circle,draw,calign=center,edge=->,grow'=north}
        [A  [B [C] [D] ]    [E [F] [G] [H] ]    ]
    \end{forest}}

\begin{wrapfigure}{r}{\dimexpr\wd\ForestBox+2em}
\centering
\usebox\ForestBox
\caption{A tree}\label{fig:simple_tree}
\end{wrapfigure}
\blindtext
\end{document}

enter image description here


The answer depends on what matters most to you: The amount of space your tree is taking up on the page or the size of the tree as produced by the forest package:

In the first case (where you would want the space the tree uses on the page to be limited to 0.25\textwidth) you could make the tree smaller with the use of the graphicx package with resizebox:

\documentclass{article}
\usepackage{forest}
\usepackage{wrapfig}
\usepackage{blindtext}
\usepackage{graphicx}
\begin{document}
\begin{wrapfigure}{r}{0.25\textwidth}
    \centering
     \resizebox{\linewidth}{!}{\begin{forest}
        for tree={circle,draw,calign=center,edge=->,grow'=north}
        [A  [B [C] [D] ]    [E [F] [G] [H] ]    ]
    \end{forest}}
    \caption{A tree}
    \label{fig:simple_tree}
\end{wrapfigure}
\blindtext
\end{document}

Here is the output:

enter image description here

In the second case (where you would want the tree to keep it's default size), you can give the tree more space on the page and thereby preventing your tree from leaving the margin:

\begin{wrapfigure}{r}{0.4\textwidth}\centering

Herbert described in his answer, how to do this and also gave an account on doing this without the need for try-and-error. Donald Arseneau described in his answer below another very convenient solution: As long as the figure and the caption are not "special" (e.g. complicated expansions) you can simply use 0pt as the width and let warpfigure do the measuring:

\begin{wrapfigure}{r}{0pt}\centering

Picture: enter image description here