% \iffalse
% !TEX encoding = UTF-8 Unicode
% Remember to use \StopEventually{}, otherwise no Check Sum
%<*internal>
\begingroup
\input docstrip.tex
\keepsilent
\preamble

Copyright (C) 1991-2003 by Donald Arseneau  (asnd@triumf.ca)
Copyright (C) 2021 by Claudio Beccari (claudio.beccari@gmail.com)
License information appended
  
\endpreamble

\postamble

Distributable under the LaTeX Project Public License,
version 1.3c or higher (your choice). The latest version of
this license is at: http://www.latex-project.org/lppl.txt

This work is "maintained"

This work  consists of file  wrapfig2.dtx, and the derived  files 
wrapfig2.sty and wrapfig2.pdf, plus the auxiliary file README.txt.

\endpostamble
\askforoverwritefalse

\generate{\file{wrapfig2.sty}{\from{wrapfig2.dtx}{package}}}

\def\tmpa{plain}
\ifx\tmpa\fmtname\endgroup\expandafter\bye\fi
\endgroup
%</internal>
% \fi
%
% \iffalse
%<*package>
%<package>\NeedsTeXFormat{LaTeX2e}[2019/01/01]
%</package>
%<*driver>
\ProvidesFile{wrapfig2.dtx}%
%</driver>
%<+package>\ProvidesPackage{wrapfig2}%
%^^A<+readme>File README.txt for package wrapfig2
%<*package|readme>
        [2021-12-21 v.4.0 Wrapfig extended]
%</package|readme>
%<*driver>
%
\documentclass{ltxdoc}\errorcontextlines=100
\hfuzz 10pt
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage{mflogo}
\usepackage{multicol,amsmath,fancyvrb,graphicx,verbatim,pict2e,trace}
\usepackage{xfp,xcolor,wrapfig2,tcolorbox,kantlipsum,xspace}
\GetFileInfo{wrapfig2.dtx}
\title{The \textsf{wrapfig2} package}
\author{Claudio Beccari\thanks{E-mail: \texttt{claudio dot beccari at gmail dot com}}}
\date{Version \fileversion~--~Last revised \filedate.}
\providecommand*\diff{\mathop{}\!\mathrm{d}}
\renewcommand\meta[1]{{\normalfont\textlangle\textit{#1}\textrangle}}
\renewcommand\marg[1]{\texttt{\{\meta{#1}\}}}
\providecommand\opz{}
\renewcommand\opz[1]{{\normalfont\texttt{\itshape#1}}}
\providecommand\Marg{}
\renewcommand\Marg[1]{\texttt{\{#1\}}}
\providecommand\oarg{}
\renewcommand\oarg[1]{\texttt{[\meta{#1}]}}
\providecommand\Oarg{}
\renewcommand\Oarg[1]{\texttt{[#1]}}
\providecommand\aarg{}
\renewcommand*\aarg[1]{\texttt{<\meta{#1}>}}
\providecommand\Aarg{}
\renewcommand\Aarg[1]{\texttt{<#1>}}
\providecommand\barg{}
\renewcommand\barg[1]{\texttt{\string|\meta{#1}\string|}}
\providecommand\Barg{}
\renewcommand\Barg[1]{\texttt{\string|#1\string|}}
\providecommand\parg{}
\renewcommand\parg[1]{\texttt{(\meta{#1})}}
\providecommand\Parg{}
\renewcommand\Parg[1]{\texttt{(#1)}}
\providecommand\eTeX{}
\renewcommand\eTeX{\lower0.5ex\hbox{$\varepsilon\!$}\TeX}
\providecommand\pack{}
\renewcommand\pack[1]{{\normalfont\texttt{#1}}}
\providecommand\class{}
\renewcommand\class[1]{{\normalfont\texttt{#1}}}
\providecommand\env{}
\renewcommand\env[1]{\meta{\textsf{\slshape#1}}}\let\amb\env
\providecommand\Env{}
\renewcommand\Env[1]{\textsf{\slshape#1}}\let\Amb\Env
\providecommand*\Bambiente[1]{\texttt{\char92begin\{#1\}}}
\providecommand*\Eambiente[1]{\texttt{\char92end\{#1\}}}
\let\Bamb\Bambiente \let\Benv\Bamb
\let\Eamb\Eambiente \let\Eenv\Eamb

\makeatletter

\AfterEndPreamble{%
\apptocmd{\TeX}{{}\xspace}{}{}
\apptocmd{\LaTeX}{{}\xspace}{}{}}

\DeclareRobustCommand\LaTeXe{%
  \LaTeX\@killglue\kern0.15em2$_{\textstyle \varepsilon}${}\xspace}
\DeclareRobustCommand\LaTeXccix{%
  \LaTeX\@killglue\nobreakspace2.09{}\xspace}
\DeclareRobustCommand\LaTeXiii{\LaTeX\@killglue\kern0.15em3{}\xspace}
\DeclareRobustCommand*\pdfLaTeX{pdf\/\LaTeX}
\DeclareRobustCommand*\LuaLaTeX{Lua\LaTeX}
\DeclareRobustCommand*\XeLaTeX{%
X\ifdim\fontdimen1\font=0pt\kern-0.15em\fi
\lower.5ex\hbox{\rotatebox[origin=c]{180}{E}}%
\ifdim\fontdimen1\font=0pt\kern-0.15em\else\kern-0.275em\fi
\LaTeX}

\providecommand\setfontsize{}
\RenewDocumentCommand\setfontsize{O{1.2} m}{%
  \fontsize{#2}{\fpeval{#1*#2}}\selectfont}


\newwrite\example@out
\ProvideDocumentEnvironment{Esempio}{ O{\footnotesize} D(){0.50}}
% All definitions and assignments are local
% #1 := LaTeX font size command or  \setfontsize{<size>}
% %2 := \textwidth percentage for the code box; the complement, less the
%       column gap, for the resulting compiled code
% Syntax: \begin{Esempio}[<size command>](<code-box percentage-width>)
%
{\par\addvspace{3.0ex plus 0.8ex minus 0.5ex}\vskip -\parskip
\dimendef\Wboxu=2570 \dimendef\Wboxd=2572
\Wboxu=#2\textwidth\relax
\Wboxd=\dimexpr\linewidth-\columnsep-\Wboxu\relax
\begingroup
\@bsphack
\immediate\openout\example@out\jobname-temp.tex
\let\do\@makeother\dospecials\catcode`\^^M\active
\def\verbatim@processline{%
  \immediate\write\example@out{\the\verbatim@line}}%
\verbatim@start\relax}%
{\immediate\closeout\example@out\@esphack\endgroup
\begin{lrbox}{0}%
\begin{minipage}{\textwidth}%
\begin{minipage}{\Wboxu}%
#1\relax
\verbatiminput{\jobname-temp.tex}
\end{minipage}%
\hfill
\begin{minipage}{\Wboxd}\raggedleft
\input{\jobname-temp}%
\end{minipage}
\end{minipage}%
\end{lrbox}%

\medskip
\noindent\makebox[\textwidth]{\box0}%
\par
}

\providecommand\hz{\hskip0pt}

\newenvironment{ttsintassi}{\begin{lrbox}{0}
  \minipage{\dimexpr\linewidth-2\fboxrule-2\fboxsep}\ttfamily\obeylines}%
{\endminipage\end{lrbox}\center\fbox{\box0}\endcenter}
    

%
\begin{document}\errorcontextlines=100
\maketitle
\columnseprule=0.4pt
\begin{multicols}{2}
 \tableofcontents
 \end{multicols}
 \DocInput{wrapfig2.dtx}
 
\end{document}
%</driver>
% \fi
%
% \begin{abstract}
% This new package \pack{wrapfig2} is a fork that upgrades Donald
% Arseneau's package \pack{wrapfig} (version 2.6, dated 2003) by
% adding some \LaTeXiii definitions that accept a final optional star;
% its presence changes the meaning of the first optional
% argument so that it becomes a correction to the number of lines
% that must be indented in order to receive the wrapped object.
% A new environment is added to the traditional \Env{wrapfigure}
% and \Env{wraptable}, namely \Env{wraptext}; it may be used
% to wrap a small framed text block on a grey background; the
% philosophy of this new environment is similar to that of the
% other two environments, but the syntax is different.
% \end{abstract}
%
%^^A%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \paragraph{Caution} This package requires a fairly recent
% \LaTeX kernel, otherwise it won't work; any \LaTeX kernel dated
% at least 2020 is~OK.
%^^A%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%^^A%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \section{Introduction}
%^^A%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% The purpose of this package is twofold. On one side it tries
% to modernise the original software by Donald Arseneau by
% upgrading it to the \LaTeXiii modern language. On the other it
% creates a new environment, with the same philosophy
% of the original Arseneau's ones, such that a document author
% can emphasise short blocks of text by framing them while
% typesetting the text on a coloured background by means of
% the \pack{tcolorbox} functionalities, and wrapping this
% inserted text with the surrounding main text.
%
% The original software had some idiosyncrasies; Donald Arseneau
% described them in the documentation of his package; I am sorry
% to say that such idiosyncrasies have not been reduced; but in any case
% the solution is to wrap the inserted object with a sufficient
% number of lines, i.e. by a sufficiently long paragraph.
%
% The above implies that no wrapped object code should be inserted
% by the end of a paragraph; again no object code should be inserted
% within any list; not even close to the end or to the
% beginning of section. Arseneau's code is capable of
% specifying the wrapping number of lines such that two or more
% paragraphs can be indented so as to wrap a longish insertion,
% but it is wise to avoid such risky situations. Moreover, if the
% inserted figure or table has a numbered caption, the number might
% not result in the correct order with the normal corresponding
% floating objects.
%
% Therefore the usefulness of the wrapping procedure depends very
% much from the document author ability to move around his/her code
% until a suitable position is found. Certainly a good place is
% within a longish first section at the beginning of a new chapter.
%
% The code of this package does not do anything to correct such
% idiosyncrasies. They are caused by the limitations of the
% \cs{ShipOut} native \TeX/\LaTeXe macro, and very little can be done in
% addition to what Arseneau already did.
%
% Another purpose of this package is to add an option so that the
% \meta{number of indented lines} argument does not mean the total
% number, but the correction number to add-to or subtract-from to the
% value computed by the default mechanism devised by Arseneau. We assume
% that any user first uses the software to insert an object to be wrapped
% by the surrounding text without specifying any value with the
% specific optional argument; then evaluates the result, and if the
% space below the wrapped object is too large, or if such space is
% too small s/he counts the necessary number of lines and specifies
% it to be processed during another document compilation. When the
% object to be wrapped is tall, it is very easy to miscount the
% necessary number of lines, while is is very easy to evaluate the
% necessary small correction to the default computed value.
%
% A third purpose of this package is to define a new environment,
% \Env{wraptext}, to wrap a framed text block typeset on a grey
% background as if it were a figure. On \texttt{texstackexchange}
% a solution was suggested to a user who was asking for such an
% arrangement; the solution resorted to a specific use of the
% \Env{wrapfigure} environment. We thought that an \emph{ad hoc}
% solution would be a better one, since the parameters to be used for a
% figure have nothing or little to do with a text, therefore most
% of them would be useless with a wrapped text. Nevertheless the
% \meta{location} of the wrapped text and the optional correction
% of the indented lines number would still be necessary. We added also
% the possibility of optionally specifying the measure of the
% wrapped text, even if this measure should not be too different
% from a half of the wrapping text measure: with a value too different
% from \texttt{0.5\cs{linewidth}} either the wrapped text has problems
% with inter word spaces and hyphenation because of the small measure,
% or, on the opposite, the indented lines of the wrapping text have
% similar problems.
%
%^^A%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \section{Environment syntax}
%^^A%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% The new syntax for \Env{wrapfigure} and \Env{wraptable} is backwards
% compatible with the original one: just a final optional star is
% added to the original list of arguments. 
% As the list of arguments shows, the \Env{wraptext} environment has
% similar features, but all its arguments are optional, so that they
% may be specified independently from one another, provided that, when
% they are more than one, they are specified in the order
% shown in the syntax table.
%
% The optional star is available only for the standard \Env{wrapfigure}
% and \Env{wraptable} environments because the backwards compatibility
% requires the first four optional and mandatory arguments. When the
% optional star is specified, the \meta{indented lines number} is
% interpreted as the correction to the computed number.
%
% \begin{ttsintassi}\setfontsize{8.10}
%\Bambiente{wrapfigure}\oarg{indented lines number}\marg{location}\oarg{overhang}\oarg{width}\meta{$\star$}
%\qquad\meta{figure}
%\Eambiente{wrapfigure}
%~
%\Bambiente{wraptable}\oarg{indented lines number}\marg{location}\oarg{overhang}\oarg{width}\meta{$\star$}
%\qquad\meta{table}
%\Eambiente{wraptable}
%~
%\Bambiente{wraptext}\oarg{location}\barg{width}\aarg{indented line number correction}\parg{caption label}
%\qquad\meta{wrapped framed text}
%\Eambiente{wraptext}
% \end{ttsintassi}
%
%^^A%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%\section{Examples}
%^^A%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% We display some examples by using fake objects such that suitably
% long paragraphs are available; some fake language long paragraphs are
% obtained by means of the \pack{kantlipsum} package functionalities.
% They contain paragraphs that look as Kant's sentences, but we
% doubt that Immanuel Kant ever wrote such texts\dots
%
%^^A%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \subsection{A wrapped figure}
%^^A%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
%\begin{wrapfigure}{r}{50mm}*
%\centering\unitlength=1mm
%\begin{picture}(40,30)
%\polygon(0,0)(40,0)(40,30)(0,30)
%\Line(0,0)(40,30)\Line(0,30)(40,0)
%\end{picture}
%\caption{A rectangle}
%\end{wrapfigure}
%
% \kant[1]
%
%
% The code used to type the above figure is the following:
%
%\begin{flushleft}\obeylines%
%\noindent\Bambiente{wrapfigure}\Marg{r}\Marg{50mm}
%\cs{centering}\cs{unitlength}=1mm
%\Bambiente{picture}\texttt{(40,30)}
%\cs{polygon}\texttt{(0,0)(40,0)(40,30)(0,30)}
%\cs{Line}\texttt{(0,0)(40,30)}\cs{Line}\texttt{(0,30)(40,0)}
%\Eambiente{picture}
%\cs{caption}\Marg{A rectangle with its diagonals}
%\Eambiente{wrapfigure}
%~
%\cs{kant}\Oarg{1}
%\end{flushleft}
%
% No asterisk was used because the package succeeded to correctly
% compute the necessary number of indented lines.
%
%^^A%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \subsection{A wrapped table}
%^^A%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Wrapping a small table is a little more difficult than wrapping
% a figure, because the width of the inserted object is not known
% exactly in advance and is difficult to estimate; therefore it is
% possible that several trial compilations are necessary. In any
% case a \cs{centering} command might help to center the table
% within the indention of the wrapping text. Nevertheless the
% software can compute the object width if a zero value is specified
% or if the mandatory \meta{width} parameter is completely omitted;
% this second possibility is a feature of this package, that uses a
% \LaTeXiii property by which even a braced argument can be treated
% as an optional argument with a predefined default value; see below
% more details about this feature.
%
%\begin{wraptable}{l}
%\centering 
%  \begin{tabular}{cc}
%  \hline
%  First & Second\\
%  Third & Fourth\\
%  \hline
%\end{tabular}
%\caption{A small table}
%\end{wraptable}
%
%\kant[2]
%
% The above wrapped small table has been typeset by means of the
% following code.
%\begin{flushleft}\ttfamily\obeylines
%\Bambiente{wraptable}\Marg{l} 
%\quad\cs{centering} 
%\quad\Bambiente{tabular}\Marg{cc}
%\qquad\cs{hline}
%\qquad First \& Second\string \\
%\qquad Third \& Fourth\string \\
%\qquad\cs{hline}
%\quad\Eambiente{tabular}
%\quad\cs{caption}\Marg{A small table}
%\Eambiente{wraptable}
%\cs{kant}\Oarg{2}
%\end{flushleft}
%
% You notice the absence of the braced width value; as said above,
% this braced value is optional, and the software autonomously
% computes the width of the wrapped object. This feature may be
% useful in many instances, although we think that a smart use of
% this width parameter might yield better looking results.
% 
% On the opposite if the user estimates that the table with its
% caption might use 5 lines, and specified such a value as the
% first (optional) argument to the environment, the result would
% be this poor one, with the last caption line overlapping the
% wrapping text.
%
%\begin{wraptable}[5]{l}
%\centering 
%  \begin{tabular}{cc}
%  \hline
%  First & Second\\
%  Third & Fourth\\
%  \hline
%\end{tabular}
%\caption{A small table}
%\end{wraptable}
%\kant[2]
%
% If 
%
%^^A%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \subsection{A wrapped text}
%^^A%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% \begin{wraptext}
% Text, text, text, text, text, text, text, text, text, text, text.
% \end{wraptext}
% \kant[3]
%\enlargethispage{-2\baselineskip}
% 
% The above example was typeset with this simple code:
%\begin{flushleft}\obeylines
% \Bamb{wraptext}
% \ttfamily Text, text, text, text, text, text, text, text, text, text, text.
% \Eamb{wraptext}
% \cs{kant}[3]
%\end{flushleft}
%
% As it was previously shown, the syntax for the \Env{wraptext}
% environment is a little different from that of the other two
% environments. The logic behind it is substantially the same;
% the \meta{width} parameter is optional; its preset value is
% half the column width, that in one column typesetting mode
% coincides with the text width. The wrapped text is typeset
% in justified mode within a \Env{minipage} environment; the
% measure of this mini page should not be too small (unless
% the text is less than one line long) otherwise the inter
% word spacing might be too large; at the same time the measure
% of the mini page cannot be too large, otherwise the indented
% wrapping lines, generally justified, might get a bad word
% spacing. Therefore it is suggested to avoid specifying the
% optional \meta{widh} outside the range of 40\% to 60\% the
% column width. Actually specifying \texttt{0.2\cs{textwidth}}
% or \texttt{0.4\cs{columnwidth}} when typesetting in two column
% mode produces approximately the same result, because
% \cs{columnwidth} is a little less than half the \cs{textwidth}.
%
% A warning is necessary: if a caption is entered
% within the environment, such caption gets typeset within the
% background coloured frame. We think that a framed text does not
% require any caption; if such caption were necessary, then the
% user should resort to other means, for example, to a standalone
% small PDF file containing the framed shaded text to be imported
% as a figure with the \amb{wrapfigure} environment.
%
%^^A%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \section{Remarks}
%^^A%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% The syntax of the original environments \amb{wrapfigure} and
% \amb{wraptable} has not been changed, except for a last optional
% star. The fact that the last braced argument is optional does not
% change the backward compatibility with the original environments.
%
% Therefore the optional \meta{line number} argument maintains its
% meaning, unless the optional star is specified; in such a case that
% number assumes the meaning of a correction to the computed number
% of the indented lines.
%
% The mandatory \meta{placement} maintains its meaning and the legal
% values are \texttt{l} (left), \texttt{r} (right), \texttt{L}
% (floating left), \texttt{R} (floating right), \texttt{i}
% (inner margin), \texttt{o} (outer margin), \texttt{I}
% (floating inner margin), \texttt{O} (floating outer margin).
% 
% We tested all of them, but as a personal choice we prefer to
% place the wrapped object at the left of the text, without
% floating it and irrespective of the page number parity.
%
% As in the previous examples, we prefer to specify the wrapping
% environment before a sufficiently long paragraph. Should the
% paragraph be too short to completely wrap the object, all
% the environments are capable of counting the number of indented
% lines and to apply the \cs{overhang} command with the remaining
% line number to the following paragraph(s); in these circumstances
% it might be necessary to recourse to the optional star in order
% to correct the indention, since the mechanism does not consider
% the inter paragraph spacing that \TeX introduces only at ship~out
% time.
%
% We avoid also to enter the wrapping environment before paragraphs
% that are close to a page break; this action would tickle the
% idiosyncrasies of the software, and requires moving the wrapping
% environment some paragraphs before or after the preferred one; but
% this can be done only while reviewing the document, because any
% change in the previous source text might change the situation
% if this adjustment is done while still editing the document.
%
% With the standard environments the optional parameter \meta{overhang} 
% does exactly what its name implies: the wrapped object protrudes
% into the adjacent margin exactly by the specified amount. This
% parameter is not available for the \Env{wraptext} environment;
% we believe that a wrapped text logically pairs the wrapping text;
% of course this opinion might be wrong and in future upgrades we
% might add this functionality.
%
% The \meta{width} parameter has been already sufficiently described;
% we just remember that for \Env{wraptext} this parameter is optional
% and its default value amounts to half the current measure; it can
% be specified but it should not be too different from 50\% the
% current measure. For the standard environments this parameter value
% is mandatory, but, we recall, for the redefined environments
% \env{wrapfigure} and \env{wraptable}, this braced argument is optional.
%
%^^A%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \section{Other floating objects}
%^^A%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Pictures and textual arrays may be floated by means of the standard
% \amb{figure} and \amb{table} environments. But other floating
% objects may be defined by means of the \pack{float} package,
% just to name one, or classes. Besides floating, the main difference
% is the name of the caption “label”: Figure, Table, Algorithm,
% Example, and so on.
%
% If floating is not necessary, this package (as well as the original
% one) allows to use the underlying  environment \Env{wrapfloat}
% that uses the same syntax as \Env{wrapfigure} plus the mandatory
% name of the new object: even a figure  might be introduced without
% using \amb{wrapfigure}, by using instead:
%\begin{flushleft}\ttfamily\obeylines
%\Benv{wrapfloat}\Marg{figure}\oarg{line number}\marg{placement}\%
%\quad \oarg{overhang}\marg{width}\meta{$\star$}
%\qquad\qquad\meta{image}
%\Eenv{wrapfloat}
%\end{flushleft}
% Another \meta{object} may be wrapped by using:
%\begin{flushleft}\ttfamily\obeylines
%\Benv{wrapfloat}\marg{object name}\oarg{line number}\marg{placement}\%
%\quad \oarg{overhang}\marg{width}\meta{$\star$}
%\qquad\qquad\meta{object}
%\Eenv{wrapfloat}
%\end{flushleft}
%
% If the floating \meta{placement} codes have to be used, another
% floating object with the desired \meta{object name} has to be
% previously  defined by means of the functionalities of other
% packages or classes.
%
%^^A%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \CheckSum{1061}
% \StopEventually{}
%^^A%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%^^A%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \section{The code}
%^^A%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Here we describe and comment the code of this package; essentially 
% only the initial parts need some comments; because the final ones
% are almost identical to the original Arseneau's code.
%
% We start with the usual specification of the format name and date,
% and the identification of this specific package. We possibly load
% the \pack{etoolbox} package, because we immediately need a
% test on the existence of an @-protected macro; should this macro
% already been defined by the class or other packages (including a
% previous loading of this package or the previous Arseneau's one)
% the loading is immediately aborted. If is was not previously loaded,
% we load the \pack{xfp} package, that allows us to perform precise
% calculations. Loading the \pack{xparse} package is necessary in
% order to use one of its rare features that did not migrate
% to the \LaTeX kernel. From the \LaTeX News Letter dated October 2020:
%\begin{quote}
% Most, but not all, of the argument types defined by \pack{xparse}
% are now supported at the kernel level. In particular, the types
% \texttt{g/G}, \texttt{l} and \texttt{u} are not provided by the
% kernel code; these are \emph{deprecated} but still available by
% explicitly loading \pack{xparse}. All other argument types are
% now available directly within the \LaTeXe kernel.
%\end{quote}
% For now their availability eases the treatment of the backwards
% compatibility of this software with the original \pack{wrapfig}
% functionality. It deals with the mandatory \meta{width} argument
% of the \pack{wrapfigure}, \pack{wraptable}, and \pack{wrapfloat}
% environments, where it was possible to specify a zero value.
% Now it is possible to omit it completely because it is a
% \emph{braced optional argument}.
%
%\iffalse
%<*package>
%\fi

%    \begin{macrocode}
\NeedsTeXFormat{LaTeX2e}[2020-01-01] 
\ProvidesPackage{wrapfig2}%
 [2021-11-30 v.4.0 Wrap text around figures, tables, framed text blocks]
\@ifpackageloaded{etoolbox}{}{\RequirePackage{etoolbox}}
\ifcsdef{c@WF@wrappedlines}{\endinput}{}
\ifcsdef{fpeval}{}{\RequirePackage{xfp}}
\RequirePackage{xparse}

%    \end{macrocode}
% 
% Next we define some dimensions, boxes, token registers, \TeX counters,
% and alias names. The \cs{WF@correctlines@switch} \TeX numeric register
% (not a \LaTeX counter) is going to be used a  boolean switch; if its
% value is zero, il means “false”, otherwise is “true”; in the other
% definitions below,  it will be set only to 0 or 1, depending on the
% presence of the optional star.
%    \begin{macrocode}
\newdimen\wrapoverhang \wrapoverhang\z@
\newdimen\WF@size
\newcounter{WF@wrappedlines} 
\newbox\WF@box 
\newbox\NWF@box
\newtoks\WF@everypar
\newif\ifWF@float
\newcount\WF@correctlines@switch
\newdimen\insertwidth
\let\@@parshape\parshape
\let\WF@@everypar\everypar

%    \end{macrocode}
%
% In what follows we are going to use very often the functionalities
% of the \pack{xparse} package that are mostly already included into
% the \LaTeX  kernel; but, since we use one of this functionalities that
% have not migrated to the \LaTeX kernel, we load it, as they remain
% available with that package; nevertheless we specified a
% \LaTeX format date insuring that the \LaTeXiii syntax is available.
%
% Should the format file be an older one, a multitude of errors would be
% produced, and the user should take care to load the \pack{xparse}
% and \pack{xfp} packages before loading \pack{wrapfig2}.
% Notice that most of the \pack{xparse} package functionalities
% at the date required for the format file are already included. The
% \pack{xparse} package has been available about in 2018; should the user
% have available a definitely  older \TeX system installation, s/he
% should upgrade it, or must avoid using this \pack{wrapfig2} package
% and use the original one; if s/he needs to wrap text, s/he should
% resort to some ingenious tricks to do it.
%
% The opening command of the \Env{wrapfloat} environment receives
% the mandatory and optional arguments plus the name of the particular
% object to be wrapped. It is used to define the prefix label of the
% caption number in case that the object is described with a caption. The
% optional star is not explicit, because it is going to be read by
% the \cs{WF@wr} macro.
%
% The closing command of \Env{wrapfloat} performs most of
% the work necessary to wrap the box that contains the object
% to be wrapped, but certain tasks are demanded to other service
% macros.
%
% It may set the width of the box if the \meta{width} parameter
% is specified; otherwise it closes the \cs{hbox} that was used;
% then it closes the main vertical box \cs{WF@box}. After executing
% \cs{WF@floatstyhook}, necessary when package \pack{float.sty}
% has been used, it saves the \meta{overhang} value to be used when
% wrapping is actually performed; then it verifies if the box height
% is too high to fit, or is too short; possibly re-boxes this box
% in the same box register with a negative initial vertical skip
% that raises the box contents.
%
% The definitions of the \Env{wrapfigure} and \Env{wraptable}
% environments are very simple by means of the underlaying
% \Env{wrapfloat} environments.
%    \begin{macrocode}
\NewDocumentEnvironment{wrapfigure}{o m o G{0pt}}%
  {\wrapfloat{figure}[#1]{#2}[#3]{#4}}%
  {\endwrapfloat}
  
\NewDocumentEnvironment{wraptable}{o m o G{0pt}}%
  {\wrapfloat{table}[#1]{#2}[#3]{#4}}%
  {\endwrapfloat}
  
%    \end{macrocode}
% 
% The definition of the \Env{wraptext} environment is more detailed,
% because most of the computations must be done on the actual text
% to be wrapped, that does not have a specific width; moreover the
% inserted text must not be too wide, nor too short in order to avoid
% problems for its justification or the justification of the wrapping
% text. The framed box width is preset to 50\% of the normal text measure,
% but it can be optionally specified to a different value (not too
% different from 50\%), while for the other environments the wrapped
% material width is an \emph{optional braced parameter}.
%
% For what concerns the \Env{wraptext} environment, see below,
% because the code is a little more complicated and requires some
% explanation.
% In facts the first statement argument description list does not
% contain any descriptor for an optional star. There is no need
% because the computation of the insertion block height is pretty
% precise and at most the user might desire one line more or less
% depending on the  measure of the whole text, and that of the
% inserted block and/or the measure of the indented wrapped lines.
%
% It is true that some of the input parameters specified to the opening
% command with \LaTeXiii are available also to the closing commands; see
% the last paragraph of section~2 in the \pack{xparse} documentation. 
% But the following definition, besides using special delimiters for
% optional parameters,  uses the separate opening and closing
% macros  of the \Env{wrapfloat} environment; such procedure
% apparently breaks this second availability of the input parameters,
% therefore it is necessary to save them into local macros or count
% registers (assignments of \TeX count registers are \emph{local},
% while assignment of the \LaTeX\ named counters, through the
% \cs{setcounter} macro and its siblings, are \emph{global}) so 
% that we can use their values within the closing commands.
%
% The \cs{NWF@box} has been assigned at the beginning; remember
% that \LaTeXiii registers of any kind are not limited in number
% as they were some years ago even with \LaTeXe. 
% The last opening commands are conceived to box the object to be
% wrapped, typeset within a \Env{minipage} with the default or
% specified width; such box, and the \Env{tcolorbox} and
% \Env{minipage} environments are closed at the beginning of the
% closing commands, so that what is necessary in order to place the
% wrapped boxed text is easy to be executed.
%
% The number of indented lines is computed by  means of the
% \cs{fpeval} \LaTeXiii function; among the operands of this
% function there is the value \texttt{2} used to take into
% account the vertical space used by \Env{tcolorbox} to
% separate the frame from its contents. It is possible that
% a value of \texttt{3} might reduce the probability of using the
% \meta{line number correction}. But it is not always true and we
% found that the chosen value is a better choice.
%
% Eventually the opening \Env{wrapfloat} statement is created by
% expanding the whole line complete of arguments, by means of the
% usual trick of defining a dummy macro within a group that contains
% among its expansion the group closing command, so that while
% it is being executed, it deletes itself from memory.
%    \begin{macrocode}
\NewDocumentEnvironment{wraptext}%
      {O{l}    D||{0.5\columnwidth} D<>{0}   D(){figure}}%
{%                                                        Open environment
  \insertwidth=#2\relax
  \def\textplacement{#1}%
  \def\textcorrection{#3}%
  \def\WF@caption@label{#4}%
  \begin{lrbox}\NWF@box%            This box is to contain the framed text
    \minipage{\insertwidth}%
   \tcolorbox
}{%                                                      Close environment
  \endtcolorbox\endminipage\end{lrbox}%
  \edef\NWF@wli%                        \NWF@wli is a macro, not a counter
    {%
      \fpeval{%
        round((\ht\NWF@box+\dp\NWF@box)/\baselineskip,0)+2+\textcorrection
             }%
    }%
  \ifhmode\unskip\else\leavevmode\noindent\fi
  \bgroup\edef\x{\egroup\noexpand\wrapfloat{\WF@caption@label}[\NWF@wli]%
      {\textplacement}{\the\insertwidth}}\x
    \box\NWF@box %                       Output framed box containing text
  \endwrapfloat
  \ignorespaces
}

%    \end{macrocode}
%
% Now comes the definition of the fundamental environment \Env{wrapfloat};
% compared to the original Arseneau's definition it is much longer,
% but it contains the code that Arseneau, who wrote the code in 
% \LaTeXe language, had to split in several macros in order to
% handle the multitude of interspersed mandatory and optional
% arguments.
%
% The main function of this environment is to handle the box that
% contains the figure, or the table, or the framed test, or what
% else, so that the inserted box is preceded and followed by the
% suitable vertical spaces, and it is possible to compute the
% number of lines to be indented; often this computed number is correct;
% but in certain cases, when the code is used too close or
% within prohibited wrapping text, such number might need to be
% corrected. As it can be seen the optional star is not among
% the argument descriptors of the opening commands; it will be
% the following macro \cs{WR@wr} to take care of examining
% the list of arguments and see if a star has been specified and
% not yet read by the preceding commands.
%
% In order to handle any kind of wrapped object, this environment
% first argument is the \meta{caption label}. It may remain blank;
% but for wrapping figures or tables their respective definitions
% specify the name of the floating object they belong to; it is not
% necessary that there exists a floating environment with the same
% name of the wrapped object, when its wrapping environment is not
% specified with a floating \meta{placement} argument.
%
%    \begin{macrocode}

\NewDocumentEnvironment{wrapfloat}{m o m o G{\z@}}%
  {\def\@captype{#1}\WF@wr[#2]{#3}[#4]{#5}}%
  {\ifdim\hsize>\z@ 
    \par\hrule\@width\hsize\@height\z@ %   force width with invisible rule
  \else 
    \unskip \egroup \box\z@  %                               or close hbox
  \fi 
 \egroup %                      close the vtop box; its width now is known 
  \WF@floatstyhook %                                 support for float.sty
  \def\width{\wd\WF@box}%
  \setlength\wrapoverhang{\WF@ovh}%
  \xdef\WF@ovh{\the\wrapoverhang}%                     save until wrapping
  \ifdim\ht\WF@box>\topskip \ht\WF@box\z@ \fi%          too high, set flag
  \ifdim\ht\WF@box<.5\p@ %                              too short, move up
    \global\setbox\WF@box\vtop{\vskip-1.4ex\unvbox\WF@box}%
  \fi
   \global\WF@size=%                  compute total box hight with \fpeval
     \fpeval{\ht\WF@box+\dp\WF@box+1.5\baselineskip+\tw@\intextsep}\p@
   \aftergroup\WF@startfloating %        use even when not really floating
  \unless\ifWF@float 
    \ifhmode
      {\unskip \parfillskip\z@skip \par \vskip-\parskip}%
      \aftergroup\noindent
    \fi
  \fi 
  \global\@ignoretrue
  }

%    \end{macrocode}
%
% The working macro \cs{WF@wr} is defined with the \LaTeXiii
% language; it grabs all the optional and mandatory arguments
% in a single step, contrary to \LaTeXe that requires to split
% the various steps in separate macros. In the definition code
% we use also some commands, such as \cs{unless}, originally
% defined by the \eTeX typesetting program extensions, that have
% been included in the \pdfLaTeX, \XeLaTeX and \LuaLaTeX kernels
% several years ago.
%
% Notice that the optional first (optional) argument, that represents
% the number of indented lines or their correction number, is saved
% into the macro \cs{WF@wli}, but if this argument is not specified,
% \cs{WF@wli} is assigned the value zero. The same happens for the
% \meta{overhang} optional argument.
%
% After these adjustments, it computes the box total height plus some
% fixed amounts needed mostly to set the wrapped material below the
% first wrapping text first line. Here is where the \LaTeXiii
% \cs{fpeval} computing macro comes into play so as to assign such
% height to \cs{WF@size}. Some unusual macros are executed; they
% were devised by Arseneau to deal with possibly floating wrapped
% objects. The optional star is not accepted by this macro; if the user
% specified it, it is still in the input flux; notice that the
% \Env{wraptext} environment does not accept the optional star; if
% the user specifies it for this environment, an asterisk appears
% at the beginning of the wrapped text.
%
% The mandatory \texttt{\#4} \meta{width} parameter (actually a
% \meta{optional braced parameter}) may be specified
% to be \texttt{0pt}; in any case \texttt{0pt} is the default parameter
% value; if so, the object is treated at its natural width, by
% boxing it into an hbox and using this hbox width as the working width
%    \begin{macrocode}
\NewDocumentCommand\WF@wr{o m o m s}{%
  \xdef\WF@wfname{wrap\@captype\space}%
  \unless\ifvoid\WF@box 
    \WFclear \WF@collision 
  \fi
  \xdef\WF@place{\string`\@car#2r\@nil}%
  \ifnum\lccode\WF@place=\WF@place 
      \global\WF@floatfalse
  \else 
      \global\WF@floattrue 
  \fi
  \ifx\parshape\WF@fudgeparshape 
    \unless\ifWF@float\\WF@collision\fi 
  \else
    \ifx\par\@@par 
      \ifnum\@@parshape>\z@\WF@conflict\fi 
    \else 
      \WF@conflict
    \fi
   \fi 
   \IfValueTF{#1}%                 save optional line number or correction
     {\gdef\WF@wli{#1}}%
     {\gdef\WF@wli{0}}%
% 
  \IfValueTF{#3}%                                   save optional overhang
      {\gdef\WF@ovh{#3}}%
      {\gdef\WF@ovh{\z@}}% 
%
   \global\setbox\WF@box\vtop\bgroup \setlength\hsize{#4}%       set width
   \ifdim\hsize>\z@
     \@parboxrestore
   \else
     \setbox\z@\hbox\bgroup
     \let\wf@@caption\caption
     \let\caption\wf@caption
     \ignorespaces
   \fi
  \IfBooleanTF{#5}%    if the asterisk is present set the numerical switch
              {\global\WF@correctlines@switch=\@ne}% 
              {\global\WF@correctlines@switch=\z@}%
  \global\@ignoretrue
}

%    \end{macrocode}
%
% At this point the main box \cs{WF@box} is opened in order to
% store the object to be wrapped; with this box height the software
% is going to compute the number of lines to be indented, unless
% such a number has been specified and no star was added to the
% input parameters.
%
% Also the \amb{wraptext} environment uses a box to collect the
% framed text; the name of this second box must be different from
% \cs{WF@box} otherwise interference of the various tasks produces
% unrecoverable errors. This is why at the beginning of this
% package we defined two different boxes: \cs{WF@box} and \cs{NWF@box}.
%
% The trick of creating an alias for the \cs{caption} macro is
% used by Arseneau to redefine one of the two macros according to
% certain conditions. Here \cs{wf@caption} is actually redefined
% if the \meta{width} parameter has been specified.
%    \begin{macrocode}
\def\wf@caption{\relax%        redefine \wf@caption in case \hsize is zero
  \ifdim\hsize>\z@ 
    \let\caption\wf@@caption 
  \else
    \unskip \egroup \hsize\wd\z@ \@parboxrestore \box\z@%      empty \box0
  \fi 
  \caption
}

%    \end{macrocode}
%
% One of these unusual macros was introduced by Arseneau
% to deal with paragraph parameters and possibly to float the
% object to be wrapped.
%    \begin{macrocode}
\def\WF@startfloating{%
 \WF@everypar\expandafter{\the\everypar}\let\everypar\WF@everypar
 \WF@@everypar{\ifvoid\WF@box\else\WF@floathand\fi \the\everypar
 \WF@wraphand
}}

%    \end{macrocode}
% The following macro is for floating wrapping environments.
%    \begin{macrocode}
\def\WF@floathand{%
  \ifx\parshape\WF@fudgeparshape 
    \WF@fltmes
  \else
    \ifx\par\@@par
      \ifnum\@@parshape=\z@
        \ifdim\hangindent=\z@
          \setbox\z@\lastbox \begingroup
          \@@par \WF@@everypar{}\WF@putfigmaybe
          \endgroup %                      after this group start wrapping
          \unless\ifvoid\z@ %                          replace indentation
              \box\z@
          \fi 
        \else
          \WF@fltmes
        \fi
      \else
        \WF@fltmes
      \fi
    \else
      \WF@fltmes
    \fi
  \fi}

%    \end{macrocode}
%
% On the contrary if there is enough space or if the wrapped object
% cannot float, it gets output here.
%    \begin{macrocode}
\def\WF@putfigmaybe{%
\ifinner
  \vskip-\parskip \global\WF@floatfalse
  \let\pagetotal\maxdimen %              kludge flag for "not top of page"
\else %                                                         outer page
  \@tempdima\pagedepth %                                   save page depth
  {\advance\parskip\@tempdima\vskip-\parskip}%        back up to base line
  \penalty\interlinepenalty %                       update page parameters
  \@tempdimb\pagegoal \advance\@tempdimb-\pagetotal %    room left on page 
  \ifdim \@tempdimb<\z@ %                                page already full
    \global\WF@floatfalse
    \unless\ifdim-\@tempdimb>\pageshrink 
      \pagebreak 
    \fi
  \else
    \ifdim\WF@size>\@tempdimb%     box too high does not fit in \@tempdimb
      \ifWF@float
        \dimen@.5\baselineskip 
      \else
        \dimen@ 2\baselineskip
      \fi
      \ifdim\pagestretch>\dimen@ \dimen@\pagestretch \fi
      \ifdim\pagefilstretch>\z@ \dimen@\@tempdimb \fi
      \ifdim\pagefillstretch>\z@ \dimen@\@tempdimb \fi
      \advance\dimen@.5\baselineskip
      \ifdim\dimen@>\@tempdimb %                     stretch page contents
        \global\WF@floatfalse \pagebreak
      \fi
    \else %                                         box fits in \@tempdimb
      \global\WF@floatfalse
    \fi
  \fi
  \vskip\@tempdima\relax %                        return erased page depth
\fi
\noindent
\ifWF@float
  \WF@fltmes
\else %                                               place insertion here
  \WF@info{Put \WF@wfname here:}%
  {\ifodd
     \if@twoside\c@page\else\@ne\fi %          assign l/r to i/o placement
     \lccode`i`l\lccode`o`r\else \lccode`i`r\lccode`o`l%
   \fi
   \xdef\WF@place{\the\lccode\lccode\WF@place}%
                 }%                               twice to get only l or r
  \hbox to\z@{%       llap o rlap depending on lor r; calc effective width
    \@tempdima\wd\WF@box \@tempdimb\WF@ovh
    \advance\@tempdima-\@tempdimb \advance\@tempdima\columnsep
    \@tempdimb\hsize \advance\@tempdimb-\@tempdima
    \xdef\WF@adjlw{\the\@tempdima}%
    \ifnum `l=\WF@place %                                   object on left
      \hss 
      \def\@tempa{\kern\columnsep}%             take right gap into action
    \else %                                                insert on light
      \@tempdima\z@ %                                  no left indentation
      \kern\@tempdimb \kern\columnsep
      \def\@tempa{\hss}%                object overlaps space to the right
    \fi
    \ifdim\@tempdimb<\hsize
      \xdef\WF@wrapil{\the\@tempdima \the\@tempdimb}%  indent.n and length
      \xdef\WF@adjtlm{\the\@tempdima}%
    \else
      \xdef\WF@wrapil{\z@ \the\hsize}%
      \xdef\WF@adjlw{\z@}\xdef\WF@adjtlm{\z@}%
    \fi
    \ifdim\pagetotal=\z@ %              put object at top of page \thepage
      \global\advance\WF@size-\intextsep
    \else %                               put object in middle of the page
      \setbox\WF@box\hbox{\lower\intextsep\box\WF@box}%
    \fi 
    \dp\WF@box\z@ 
    \box\WF@box 
    \@tempa
  }%                                                      end \hbox to 0pt
  \aftergroup\WF@startwrapping  
\fi
}

%    \end{macrocode}
%
% Here comes the very important macro that counts the wrapping indented
% lines, so that wrapping is correct; of course the limitations
% of the \TeX and \LaTeX processing (needed to ship out a complete
% page) forbid to take into account the spaces inserted between
% paragraphs and/or those inserted between entries of various
% listings. The idiosyncrasies of this package arise from the
% fact that this macro cannot preview actions that have not
% yet taken place when this macro is executed.
%
% This macro is the one that counts the lines to be indented by
% rounding the division of the box height by the current base
% line skip. Notice that \texttt{WF@wrappedlines} is the name
% of a \LaTeX named counter, not of a \TeX numeric register;
% therefore special LaTeX commands, such as \cs{setocounter} or
% \cs{value}, have to be used in order to  set or access the
% numerical value stored within the \TeX register associated
% to the \LaTeX counter name.
%    \begin{macrocode}
\def\WF@startwrapping{%
  \ifnum\WF@wli=\z@ %                              no number was specified
    \setcounter{WF@wrappedlines}%
      {\fpeval{round(\WF@size/\baselineskip,0)}}%
    \xdef\WF@wli{\value{WF@wrappedlines}}%
  \else
    \ifnum\WF@correctlines@switch>\z@ %             line number correction
      \setcounter{WF@wrappedlines}
        {\fpeval{round((\WF@size)/\baselineskip,0)+\WF@wli}}%
      \xdef\WF@wli{\value{WF@wrappedlines}}%
    \else
      \setcounter{WF@wrappedlines}{\WF@wli}%      absolute number of lines
      \global\advance\c@WF@wrappedlines\@ne
    \fi
  \fi
  \ifnum\c@WF@wrappedlines>\@ne %                              fine tuning
    \let\parshape\WF@fudgeparshape \let\WF@pspars\@empty \let\WF@@par\par
    \def\@setpar##1{\def\WF@@par{##1}}\def\par{\@par}\let\@par\WF@mypar
    \xdef\WF@restoretol{\tolerance\the\tolerance}\tolerance9999
    \advance\linewidth-\WF@adjlw \advance\@totalleftmargin\WF@adjtlm
 \fi}

%    \end{macrocode}
%
% The next macro is the one that actually indents the wrapping text lines
% and keeps track of the number of such processed lines. It can work
% on more than a single paragraph. It resorts to service macros that
% reiterate as long as the number of indented lines is lower than the
% computed number of lines. Possibly this process could be defined by
% means od the \texttt{dowhile} or \texttt{whiledo} \LaTeXiii functions.
% By now we did not afford this task, because first we would like to
% see if the overall software is reliable.
%    \begin{macrocode}
\def\WF@wraphand{%                    for indenting one or more paragraphs
  \ifnum\c@WF@wrappedlines<\tw@ 
    \WF@finale
  \else \begingroup %                            create a parshape command
    \@tempcnta\@ne \let\WF@wrapil\relax \gdef\WF@ps{}%
    \@whilenum 
      \@tempcnta<\c@WF@wrappedlines\do{%              repeated indentation
      \xdef\WF@ps{\WF@ps\WF@wrapil}\advance\@tempcnta\@ne
      }%
    \endgroup
    \ifx\WF@pspars\@empty
      \@@parshape\c@WF@wrappedlines \WF@ps \WF@noil
    \else %           use external `parshape' values to modify my parshape
      \WF@modps
    \fi
  \fi
}

%    \end{macrocode}
%
% This macro resets the paragraph properties and terminates the job.
%    \begin{macrocode}
\def\WF@mypar{\relax
  \WF@@par 
  \ifnum\@@parshape=\z@ 
    \let\WF@pspars\@empty %                                 reset parshape
  \fi
  \global\advance\c@WF@wrappedlines-\prevgraf \prevgraf\z@
  \ifnum\c@WF@wrappedlines<\tw@ 
    \WF@finale 
  \fi
}

%    \end{macrocode}
%
% These macros are to modify the paragraph settings.
%    \begin{macrocode}
\def\WF@modps{\begingroup
  \afterassignment\@tempdimb \@tempdima\WF@pspars % a=indent.num, b= width
  \advance\@tempdima-\WF@adjtlm \advance\@tempdimb\WF@adjlw
  \let\WF@wrapil\WF@pspars
  \edef\@tempb{\@@parshape\c@WF@wrappedlines 
                \WF@ps \the\@tempdima \the\@tempdimb}%
  \expandafter\endgroup\@tempb
}

\let\@@setpar\@setpar
\def\WF@noil{\z@ \hsize}
\let\WF@pspars\@empty

\def\WF@fudgeparshape{\relax 
  \ifnum\c@WF@wrappedlines<\tw@ 
    \WF@finale
  \else 
    \afterassignment\WF@fudgeparshapee \fam 
  \fi
}

\def\WF@fudgeparshapee{%
  \ifnum\fam=\@ne \expandafter 
    \WF@parshapeee 
  \else
    \WF@conflict \@@parshape\fam 
  \fi
}
  
\def\WF@parshapeee#1#2{%
  \begingroup\delimitershortfall#1%
  \nulldelimiterspace#2%         \advance \nulldelimiterspace by \WF@adjlw
  \edef\@tempa{\def\noexpand\WF@pspars{%
      \the\delimitershortfall \the\nulldelimiterspace}}%
  \expandafter\endgroup\@tempa \WF@wraphand
}

%    \end{macrocode}
%
% The following macro is the one that actually ends the single
% wrapping job.
%    \begin{macrocode}
\def\WF@finale{%
  \ifx\parshape\WF@fudgeparshape
    \WF@restoretol \let\@setpar\@@setpar \let\par\WF@@par
    \advance\linewidth\WF@adjlw \advance\@totalleftmargin-\WF@adjtlm
    \WF@info{Finish wrapping text}%
    \ifx\par\@@par 
      \def\@par{\let\par\@@par\par}%
    \else 
      \let\@par\WF@@par 
    \fi
    \let\parshape\@@parshape
    \parshape=\ifx\WF@pspars\@empty 
                \z@ 
              \else 
                \@ne \WF@pspars
              \fi 
  \fi
  \ifvoid\WF@box 
    \ifx\everypar\WF@everypar
      \let\everypar\WF@@everypar \everypar\expandafter{\the\WF@everypar}%
    \fi
  \fi
}

%    \end{macrocode}
%
% At the very end everything is restored, and the used boxes are emptied.
%    \begin{macrocode}
\newcommand{\WFclear}{\par 
  \unless\ifvoid\WF@box
    \vskip\bigskipamount \box\WF@box
    \let\everypar\WF@@everypar \everypar\expandafter{\the\WF@everypar}%
  \fi 
  \global\c@WF@wrappedlines\z@ \WF@finale
  \global\WF@correctlines@switch\z@
}

%    \end{macrocode}
%
% The following code is one of those “dirty tricks” by which a macro 
% defined within a group is executed with the help of an 
%\cs{expandafter} command that bypasses an \cs{endgroup}; by so doing
% nothing local to the group remains in memory.
%    \begin{macrocode}
\begingroup
 \toks0={\let\everypar\WF@@everypar
         \everypar\expandafter{\the\WF@everypar}%
         \let\parshape\@@parshape 
         \let\@setpar\@@setpar 
        }
 \toks1=\expandafter{\@arrayparboxrestore}%
 \toks2=\expandafter{\clearpage}%
 \edef\@tempa{%
      \def\noexpand\@arrayparboxrestore{\the\toks0 \the\toks1}%
      \def\noexpand\clearpage
      {\noexpand\protect\noexpand\WFclear \the\toks2}}%
 \expandafter
 \endgroup\@tempa

%    \end{macrocode}
%
% Donald Arseneau classifies the following macro as the one
% that “pampers the RevTeX's stupidity”.
%    \begin{macrocode}
\@ifundefined{@capwidth}{\let\@capwidth\hsize}{}% 

%    \end{macrocode}
%
% This one, instead, issues a warning if a specific name conflicts
% with another.
%    \begin{macrocode}
\def\WF@conflict{\WF@warning
  {\WF@wfname used inside a conflicting environment}}%

%    \end{macrocode}
%
% While this one issues a warning when a wrapping environment is
% too close to another one.
%    \begin{macrocode}
\def\WF@collision{\WF@warning{Collision between wrapping environments}}%

%    \end{macrocode}
%
% And this one is when two wrapping environments are too close to
% one another so that the second one is forced to float.
%    \begin{macrocode}
\def\WF@fltmes{%                                        message for floats
  \ifWF@float 
    \WF@info{\WF@wfname floats}%
 \else 
   \WF@warning{Stationary \WF@wfname forced to float}%
 \fi
}

%    \end{macrocode}
%
% These two aliases are just service macros for this package; in
% particular, the second one is used to insert info of any kind
% within a source file.
%    \begin{macrocode}
\let\WF@warning\@warning
\let\WF@info\@gobble

%    \end{macrocode}
%
% Arseneau says that his \pack{wrapfig} package is already compatible
% with  package \pack{float.sty}, since, after defining a new float
% \meta{foo}, it suffices to define the new environment
% \Env{wrap\meta{foo}}. This fork version of his package should do
% the same: is suffices to mimic the definitions of environments
% \Env{wrapfigure} or \Env{wraptable}.
%
% Here there is some Arseneau's code that renders his \pack{wrapfig}
% code compatible with \cs{newfloat} of class \class{memoir}, and
% with \cs{newfoatlist} of package \pack{ccaption}. We leave his code
% hereafter; but we did not test it with this package.
% \begin{macrocode}
\let\WF@floatstyhook\relax
%
\@ifundefined{newfloat}{}{%         \newfloat comes from somewhere besides
%                                                                float.sty
  \@ifundefined{restylefloat}{%
    \@ifclassloaded{memoir}{%
      \toks@=\expandafter\expandafter\expandafter
       {\csname\string\newfloat\endcsname [{#1}]{#2}{#3}{#4}%
       \newenvironment{wrap#2}{\wrapfloat{#2}}{\endwrapfloat}%
      }%                             Mmmm; this might be wrong. Not tested
   \edef\@tempa{\def\expandafter\noexpand\csname\string\newfloat\endcsname
        [##1]##2##3##4{\the\toks@}}%
      \@tempa
     }%                                                 end memoir support
     {}%                                  other origins of \newfloat here?
  }{%          float.sty handler. Ops: Two versions for different versions
%             Changing \floatstyle or \restylefloat changes \newfloat too.
  \@ifundefined{float@restyle}%
    {%                                                     older float.sty
      \toks@=\expandafter{\restylefloat{#1}%       env. might be undefined
      \@namedef{wrap#1}{%
        \def\@captype{#1}\@nameuse{fst@#1}%
        \def\WF@floatstyhook{\let\@currbox\WF@box \columnwidth\wd\WF@box 
          \global\setbox\WF@box\float@makebox}%
      \@ifnextchar[\WF@wr{\WF@wr[]}}%
      \expandafter\let\csname endwrap#1\endcsname \endwrapfigure
      }%
    \edef\@tempa{\def\noexpand\restylefloat##1{\the\toks@}}%
  }{%             newer float.sty: uses \float@restyle, and \float@makebox
%                                                          takes width arg
      \toks@=\expandafter{\float@restyle{#1}%      env. might be undefined 
        \@namedef{wrap#1}{\def\@captype{#1}\@nameuse{fst@#1}%
          \def\WF@floatstyhook{\let\@currbox\WF@box 
            \global\setbox\WF@box\float@makebox{\wd\WF@box}}%
        \@ifnextchar[\WF@wr{\WF@wr[]}}%
        \expandafter\let\csname endwrap#1\endcsname \endwrapfigure
      }%
      \edef\@tempa{\def\noexpand\float@restyle##1{\the\toks@}}%
    }%
    \@tempa %                                        perform redefinitions
%
    }%                                               end float.sty handler
}%                                          end redefinitions of \newfloat

\ifcsname newfloatlist\endcsname%                     support ccaption.sty 
  \toks@=\expandafter\expandafter\expandafter
    {\csname\string\newfloatlist\endcsname [{#1}]{#2}{#3}{#4}{#5}%
  \@namedef{wrap#2}{\wrapfloat{#2}}%
  \expandafter\let\csname endwrap#2\endcsname \endwrapfloat
  }%
  \edef\@tempa{%
  \def\expandafter\noexpand\csname\string\newfloatlist\endcsname
   [##1]##2##3##4##5{\the\toks@}}%
  \@tempa
\fi

%    \end{macrocode}
% We never described the package options; this code was present
% in Arseneau's code and ve leave it here, with the necessary
% package name change. We think that this \opz{verbose} option
% was and remains useless, since the instances of command
% \cs{WF@info} were mostly commented out in the original code;
% in any case, input of this code is stopped if the
% \cs{DeclareOption} command is not defined; this command was
% defined with \LaTeXe; therefore this is a residual of the old
% times when \LaTeXccix was still in use, more than 25 years
% ago\dots
%    \begin{macrocode}
\@ifundefined{DeclareOption}{\endinput}{%
\def\WF@warning{\PackageWarning{wrapfig2}}%
\DeclareOption{verbose}{\def\WF@info{\PackageInfo{wrapfig2}}}%
\ProcessOptions
\AtEndDocument{\WFclear}}%

\endinput
%    \end{macrocode}

%\iffalse
%</package>
%\fi
% \Finale
%
%^^A \endinput