% !TEX program = lualatex
% wrapblock-doc.tex -- documentation of the wrapblock package
% Compiles with LuaLaTeX and with pdfLaTeX.
\documentclass[a4paper,11pt]{article}

\usepackage{iftex}
\ifPDFTeX
  \usepackage[T1]{fontenc}
  \usepackage{lmodern}
\fi
\usepackage[english]{babel}
\usepackage[margin=2.4cm]{geometry}
\usepackage{microtype}
\usepackage{amsmath,graphicx,booktabs,tabularx}
\usepackage[skins,documentation]{tcolorbox}
\hypersetup{hidelinks}
\makeatletter\renewcommand*\l@subsection{\@dottedtocline{2}{1.5em}{2.9em}}\makeatother
\usepackage{wrapblock}

\tcbset{color command=red!60!black, color key=blue!60!black, color value=teal!70!black}

\newcommand\pkg[1]{\textsf{#1}}
\newcommand\key[1]{\texttt{#1}}
\providecommand\env[1]{\texttt{#1}}
% The implementation: the code is read from wrapblock.sty itself, chunk by
% chunk, between the lines "% <name>" and "% </name>" of the file. The
% file is the one TeX finds: beside this one, or through TEXINPUTS.
\usepackage{listings,url}
\lstset{basicstyle=\ttfamily\footnotesize, columns=fixed, basewidth=0.52em, keepspaces=true, upquote=true, numbers=left, numberstyle=\tiny\color{black!50}, numbersep=6pt, breaklines=true, morecomment=[l]{\%}, commentstyle=\color{black!60}, aboveskip=0.6\baselineskip, belowskip=0.6\baselineskip, rangebeginprefix=\%\ <, rangebeginsuffix=>, rangeendprefix=\%\ </, rangeendsuffix=>, includerangemarker=false}
% listings takes over the \everypar that \@afterheading uses to clear
% @nobreak: a heading followed by code would leave it set, and the next
% heading would get no space above it.
\makeatletter
\newcommand\code[1]{\lstinputlisting[linerange=#1-#1]{wrapblock.sty}\par\global\@nobreakfalse}
\makeatother
% Names of the package: \fn{shape:Nnnn}, \gv{ship_int}, \lv{base_dim}.
\DeclareUrlCommand\csurl{\urlstyle{tt}\def\UrlBreaks{\do\_}\def\UrlBigBreaks{\do\:}}
\newcommand\fn[1]{\mbox{\texttt{\textbackslash\_\_wrapblock\_}}\csurl{#1}}
\newcommand\gv[1]{\mbox{\texttt{\textbackslash g\_\_wrapblock\_}}\csurl{#1}}
% A message of the package, then what it means.
\newcommand\msgitem[1]{\par\medskip\noindent{\ttfamily\raggedright #1\par}\nobreak\smallskip\noindent\ignorespaces}
\newcommand\ecs[1]{\texttt{\textbackslash}\csurl{#1}}
\newcommand\lv[1]{\mbox{\texttt{\textbackslash l\_\_wrapblock\_}}\csurl{#1}}
% The image of the examples, with its alternative text.
\newcommand\sample[1][0.25\linewidth]{\includegraphics[width=#1, alt={Sample image}]{example-image-a}}
\newcommand\sampletext{A ball of mass $m$ bounces on the floor; we look for its velocity and angular velocity after the impact, assuming a point contact where the ball may slip. }

\title{\pkg{wrapblock}\\[0.4em]
  \large An image beside its own text, which wraps around it and runs below}
\author{Antonin Marchand}
\date{Version 0.1.3 --- 18 November 2026}

\begin{document}
\maketitle

\begin{abstract}
The \pkg{wrapblock} package provides one environment, which sets an image beside a block of text. The text is narrowed along the image, then takes the full width again below it. The block is closed: the text that follows the environment never runs beside the image.

The package gives the image no size of its own. The room it takes from the text is the width and the height of the image as it is given; only the width can be forced, with a key.

Four properties set it apart from the other wrapping packages:
\begin{enumerate}
\item the text beside the image may hold lists, nested to any depth, and a whole block may be the first thing in a list item, right after \cs{item};
\item the image and the lines beside it stay on the same page;
\item it works with pdf\LaTeX{} and with Lua\LaTeX;
\item in a tagged PDF, the structure is what it would be without the package.
\end{enumerate}
\end{abstract}

\tableofcontents

% =========================================================================
\section{What the package does}

\subsection{An example}

\begin{wrapblock}{\includegraphics[width=0.24\linewidth, alt={Sample image}]{example-image-9x16}}
This paragraph is typeset by \pkg{wrapblock}. The text runs along the image, on its left, then takes the full width again once it is past it.
\begin{itemize}
\item A list beside the image is narrowed too: each of its lines stops where the room of the image starts, like the lines of a paragraph.
\item Its labels stay in their place, and a long item such as this one is broken at the same limit as the text around it.
\end{itemize}
The text after the list goes on wrapping, down to the bottom of the image and beyond. \sampletext\sampletext\sampletext
\end{wrapblock}

This paragraph comes after the environment. It is full width, however long the block is: when the text of the block is shorter than the image, vertical space is added down to the bottom of the image (section~\ref{sec:know}).

In this documentation, the \emph{block} is the contents of the environment, the \emph{image} is whatever is set beside it (a picture, a diagram, a table), and the image is \emph{deferred} when it is set at the top of the next page.

\subsection{Near the bottom of a page}\label{sec:bottom}

The image and the lines beside it are never split by a page break. When a block starts near the bottom of a page, one of three things happens:
\begin{enumerate}
\item \emph{The image fits.} The text wraps around it, and what is left of the text runs at full width on the next page.
\item \emph{The image does not fit, and the text is long.} The text runs at full width to the bottom of the page. The image is deferred: it goes to the top of the next page, where the text wraps around it.
\item \emph{The image does not fit, and the text is short.} At full width, the text would end on this page and leave the image alone on the next one. The whole block moves to the next page instead, together with the heading that precedes it, if any. The bottom of the page is left empty, and a warning in the \texttt{.log} says so: the author may want to change something.
\end{enumerate}
Below the image, the text of the block breaks like any other text. The file \texttt{mwe-pagebreak.tex}, one of the examples that come with the package, shows the three cases with long, medium and short texts.

\subsection{What it does not do}

The package does only this. It does not wrap an image in the middle of a paragraph, flow text around a shape, or float the image: for those, see \pkg{wrapfig2}, \pkg{wrapstuff}, \pkg{cutwin} or \pkg{picinpar}. Section~\ref{sec:others} explains why none of them has the four properties above.

% =========================================================================
\section{Three things to know}\label{sec:know}

\subsection{The text should be at least as long as the image}

The block is closed: the text after it never runs beside the image. When the text of the block is shorter than the image, the block ends with vertical space, down to the bottom of the image:

\begin{wrapblock}{\sample[0.2\linewidth]}
A short text, two lines long, beside a taller image: the block ends below the image, and leaves this blank.
\end{wrapblock}

This paragraph comes after the block. Lengthening the text of the block, taking the next paragraph into it or making the image smaller removes the blank.

\pkg{wrapfig}, \pkg{wrapfig2} and \pkg{wrapstuff} leave no blank: their image is not closed in a block, so the paragraphs that follow run beside it in turn, until they are past it (checked with both engines, November 2026). The price is that whatever follows is narrowed: a heading, or a list, which \pkg{wrapfig} cannot narrow. With \pkg{wrapblock}, the text that runs beside the image is always the text of the block, and nothing else.

\subsection{Near the bottom of a page, the text is typeset twice}

When the image does not fit at the bottom of the page, the package must know how long the text is, to choose between cases 2 and 3 of section~\ref{sec:bottom}. It typesets the text of the block a first time, at full width, in a box that it then throws away. Everywhere else on the page, the text is typeset once.

This first pass leaves almost no trace:
\begin{itemize}
\item \LaTeX{} counters, those made by \cs{newcounter} --- equations, footnotes, list items, theorems, sections --- are put back after the first pass: the numbers are right.
\item Labels, footnotes, index entries, table-of-contents lines, floats and marginal notes vanish with the box: they come out once.
\item But anything else the text does globally is done twice: a \cs{gdef}, an \verb|\immediate\write|, a \TeX{} count stepped globally, a global \pkg{expl3} integer. The first use of an acronym is a common case, checked with \pkg{glossaries} and with \pkg{acro}: the first use, which prints the long form, is spent on the first pass, and the text shows the short form.
\end{itemize}

When the text holds such a command, there are two ways out. The key \key{defer=false} turns the first pass off: a block whose image does not fit then always moves to the next page (case 3), and its text is typeset once. Or the command can be moved out of the block: the first use of an acronym, for instance.

The image, for its part, is typeset twice at every block, wherever it is on the page: once to measure it, once for good. The \LaTeX{} counters it steps (a numbered equation, a caption) are put back after the first time; anything else it does globally is done twice.

\subsection{No verbatim in the block}

The text of the block is read as an argument before it is typeset, so that it can be measured. \cs{verb}, \env{verbatim}, \env{lstlisting} or \env{minted} cannot be used in it: they give an error. Verbatim material can be typeset beforehand in a box, which the block then uses:
\begin{verbatim}
\newsavebox\code
\begin{lrbox}{\code}\verb|\int_gincr:N|\end{lrbox}
\begin{wrapblock}{\includegraphics{diagram}}
  The function \usebox{\code} steps an integer.
\end{wrapblock}
\end{verbatim}

% =========================================================================
\section{Usage}

\begin{verbatim}
\usepackage{wrapblock}
...
\begin{wrapblock}[side=l, hsep=1.5em]{\includegraphics[width=4cm]{diagram}}
  The text of the block: paragraphs, lists, equations.
\end{wrapblock}
\end{verbatim}

\subsection{Requirements}\label{sec:req}

\begin{itemize}
\item A \LaTeX{} kernel of June 2023 or later; the package checks it. It was tested with TeX~Live~2026 only.
\item pdf\LaTeX{} or Lua\LaTeX: the tests run with both. With Xe\LaTeX, two of the examples (\texttt{mwe-pagebreak}, \texttt{mwe-lists}) were compiled once and gave the expected pages, but the tests do not run it.
\item One correction needs a kernel of June 2025 or later: the second pass that makes room for a footnote before a deferred image (message ``The page broke too early'', section~\ref{sec:messages}). An older kernel does not have the hook it uses: the correction is then never made.
\end{itemize}

\subsection{The environment}

\begin{docEnvironment}{wrapblock}{\oarg{keys}\marg{image}}
  Sets \meta{image} beside the contents of the environment. \meta{image} is any material in horizontal mode: an \cs{includegraphics}, an \cs{includestandalone}, a \env{tikzpicture}, a \env{tabular}. Its top is aligned with the top of the first line of the block. The package does not scale it: the image has the size it is given, with the \key{width} or \key{height} of \cs{includegraphics} for instance, and the text is narrowed by that width, over that height. The \key{width} key below can only reserve a wider room, in which the image is centred. The environment starts a new paragraph, and so does the text after it.

  The contents are read as an argument, before they are typeset: they cannot hold verbatim material (\cs{verb}, \env{verbatim}); see section~\ref{sec:know}.
\end{docEnvironment}

\begin{docCommand}{wrapblockset}{\marg{keys}}
  Sets the keys for all the following blocks, within the current group.
\end{docCommand}

\subsection{Keys}

\begin{center}
\begin{tabularx}{\linewidth}{@{}llX@{}}
\toprule
Key & Default & Meaning \\
\midrule
\key{side} & \texttt{r} & side of the image: \texttt{r} (right) or \texttt{l} (left); \key{l} and \key{r} alone are short forms \\
\key{width} & \texttt{natural} & width reserved for the image: \texttt{natural}, the width of the image itself, or a length \\
\key{hsep} & \texttt{1em} & horizontal space between the image and the text \\
\key{vsep} & \texttt{0.5\textbackslash baselineskip} & vertical space below the image \\
\key{defer} & \texttt{true} & whether the image may go to the top of the next page \\
\bottomrule
\end{tabularx}
\end{center}

\begin{docKey}[wrapblock]{side}{=\texttt{l}\textbar\texttt{r}}{default \texttt{r}}
  The side of the image: right (\key{r}) or left (\key{l}) of the text.
\end{docKey}

\begin{docKey}[wrapblock]{l}{}{}
  Short for \key{side=l}. Likewise \key{r} for \key{side=r}.
\end{docKey}

\begin{docKey}[wrapblock]{width}{=\texttt{natural}\textbar\meta{length}}{default \texttt{natural}}
  The width reserved for the image. With \texttt{natural}, it is the width of the image itself. With a \meta{length}, the image is centred in a room of that width: this aligns several blocks whose images differ in width. The length is taken as it is: a room narrower than the image lets the image stick out on both sides, and \texttt{0pt} is a room of no width.
\end{docKey}

\begin{docKey}[wrapblock]{hsep}{=\meta{length}}{default \texttt{1em}}
  The horizontal space between the image and the text.
\end{docKey}

\begin{docKey}[wrapblock]{vsep}{=\meta{length}}{default \texttt{0.5\textbackslash baselineskip}}
  The vertical space below the image, before the text takes the full width again.
\end{docKey}

\begin{docKey}[wrapblock]{defer}{=\texttt{true}\textbar\texttt{false}}{default \texttt{true}}
  Whether the image may go to the top of the next page while the text fills the bottom of this one (case 2 of section~\ref{sec:bottom}). With \key{false}, a block whose image does not fit at the bottom of the page always moves to the next page as a whole (case 3), and its text is not typeset a first time to be measured (section~\ref{sec:know}).
\end{docKey}

The defaults of \key{hsep} and \key{vsep} are computed once, when the package is loaded, with the font and the \cs{baselineskip} of that moment: those of the normal size of the document. A length given in the document is computed where it is given.

\subsection{What the image may be}\label{sec:image}

The image is typeset the way \cs{mbox} typesets its contents: on one line, without line breaks. Anything that can go in an \cs{mbox} can be an image. These were tried, with both engines:

\begin{center}
\begin{tabularx}{\linewidth}{@{}lX@{}}
\toprule
Given as the image & What happens \\
\midrule
\cs{includegraphics}, \env{tikzpicture}, \env{tabular} & as expected \\
\env{minipage}, \cs{parbox} & as expected; this is the way to give paragraphs, a list, a displayed equation or a caption (\cs{captionof}) as the image \\
\env{tcolorbox} & as expected; a \texttt{breakable} one does not break: near the bottom of a page it is deferred or moved as a whole, like any image \\
a few words & set on one line beside the text \\
nothing & the text is narrowed by \key{hsep} on its first line only \\
a long text, without \cs{parbox} & one very long line: see ``too wide'' below \\
a list or a displayed equation, without \env{minipage} & errors of \LaTeX{} (``Not allowed in LR mode'', ``Bad math environment delimiter''): they need a \env{minipage} \\
\cs{verb}, \env{verbatim} & errors: the image is read as an argument. Typeset the verbatim material beforehand in a box, and give \cs{usebox} as the image (section~\ref{sec:know}) \\
a \env{figure}, a \cs{marginpar} & the error ``Not in outer par mode'': a float cannot be the image; for a caption, use \cs{captionof} in a \env{minipage} \\
a footnote in a box (\cs{fbox}, \env{tabular}) & its text is lost, as in any box: use \cs{footnotemark} in the image and \cs{footnotetext} in the text. In a \env{minipage}, the footnote is set at the foot of the \env{minipage} \\
another \env{wrapblock} & the error ``blocks cannot be nested'' \\
\bottomrule
\end{tabularx}
\end{center}

Two sizes are special:
\begin{itemize}
\item \emph{An image too wide.} When less than 3\,em would be left for the text beside the image, the text is not wrapped: the image is set on a line of its own, above the text, and a warning says so.
\item \emph{An image taller than the page.} It fits nowhere: the block starts a new page, the image runs out of the page at the bottom, and a warning says so.
\end{itemize}

\subsection{Image on the left}

\begin{verbatim}
\begin{wrapblock}[l]{\includegraphics[width=0.25\linewidth]{example-image-a}}
\end{verbatim}

\begin{wrapblock}[l]{\sample}
\sampletext\sampletext\sampletext\sampletext
\end{wrapblock}

% =========================================================================
\section{What the block may contain}

\subsection{Lists}

A list in the block is narrowed along the image, labels included, at any depth; it gets its normal width back below the image.

A block may also be the first thing in an item of a list, right after \cs{item}, as the second question below: the image is then aligned with the margin of the item and, on the left, the label stays in the margin, before the image.
\begin{verbatim}
\begin{enumerate}
\item A question without an image.
\item \begin{wrapblock}[l]{\includegraphics[width=3cm]{diagram}}
  A question with its diagram, on the left: ...
\end{wrapblock}
\item The next question, after the block.
\end{enumerate}
\end{verbatim}
A block may also hold several items of a list that is opened before it and closed after it, with the image on the right:
\begin{verbatim}
\begin{enumerate}
\item A question without an image.
\begin{wrapblock}{\includegraphics[width=3cm]{diagram}}
\item The first question beside the diagram.
\item The second one.
\end{wrapblock}
\item The next question, after the block.
\end{enumerate}
\end{verbatim}
With the image on the left, this does not work: only the label of the first item is kept out of the image, and the labels of the following items are set over it.

What cannot be done is to open a list in the block and close it after the block, or the reverse: the block is an environment, and \LaTeX{} wants environments nested.

\begin{enumerate}
\item A question without an image. \sampletext
\item \begin{wrapblock}[l]{\sample[0.2\linewidth]}
A question with its diagram, on the left:
\begin{enumerate}
\item a sub-question \sampletext
\item another one.
\end{enumerate}
\sampletext
\end{wrapblock}
\item The next question, after the block.
\end{enumerate}

\subsection{Displayed equations}

A displayed equation (\verb|\[ \]|, \env{equation}, \env{align}\dots) is centred in the width left beside the image. After it, the paragraph goes on wrapping from where the equation ended.

\begin{wrapblock}{\sample[0.22\linewidth]}
The conservation of angular momentum about the contact point gives
\[ J\omega' + m R v' = J\omega + m R v , \]
and Coulomb's law, while the contact slips,
\begin{equation} \lVert \vec T \rVert = f \lVert \vec N \rVert . \end{equation}
The text goes on below the equation, still along the image as long as it has not passed it. \sampletext
\end{wrapblock}

\subsection{Footnotes, inline formulas}

A footnote called in the block goes to the foot of the page, as anywhere else. A line taller than the others, with an inline fraction for instance, pushes the next ones down; since the package counts lines in \cs{baselineskip}, the wrapping may then last one line longer than needed, never one line shorter.

\subsection{Centred or ragged text}

\cs{centering}, \cs{raggedright} and \cs{raggedleft} work in the block, and so does a block in a \env{center}, \env{flushleft} or \env{flushright} environment: the lines are centred or ragged in the width left beside the image.

\subsection{Boxes and wide material}

The text of a box --- \cs{parbox}, \env{minipage}, \texttt{p} column of a table --- keeps the width it was given and is not wrapped. A box wider than the room left beside the image therefore overlaps the image; the package says so with a warning. A box set below the image raises no problem.

Other material that cannot be broken --- a wide \env{tabular} without \texttt{p} column, a wide picture, a long formula --- also overlaps the image when it is wider than the room left beside it. The package does not warn about it, but \TeX{} does, with its usual \texttt{Overfull \textbackslash hbox}.

\subsection{Floats}

A \env{figure} or a \env{table} may be declared in the block; it floats as usual. When a float lands at the top of the page that receives a deferred image, the image is set below it, beside its text.

% =========================================================================
\section{Where the environment may be used}\label{sec:where}

\begin{description}
\item[In running text and in lists] All of the above.
\item[In \texttt{twocolumn} mode and in \env{multicols}] The block wraps its text within its column, and does not break from one column to the next while it runs along the image. The image is never deferred there: when it does not fit at the bottom of the column, the whole block moves to the next one.
\item[In a box] In a \env{minipage}, a \cs{parbox}, a \env{tcolorbox}\dots, the package cannot tell where it stands, and no page breaks there anyway. The text is then set in a \env{minipage} beside the image, aligned on its first line, without running below the image; an information message in the \texttt{.log} says so.
\item[In another block] Blocks do not nest: this is an error.
\end{description}

% =========================================================================
\section{Tagged PDF}

With \verb|\DocumentMetadata{tagging=on}|, the text of the block is typeset in the main galley: paragraphs, lists and formulas keep the structure \LaTeX{} gives them. The image is typeset at the start of the first paragraph of the block, as if it had been written there: an \cs{includegraphics} becomes a \texttt{Figure} element there, before the text it goes with, and its alternative text is given as usual, with the \key{alt} key:

\begin{verbatim}
\begin{wrapblock}{\includegraphics[width=4cm, alt={The ball}]{ball}}
\end{verbatim}

A deferred image, set at the top of the next page, keeps its place in the reading order: the package makes an empty structure element where the block starts, and puts the image into it, in a \texttt{P} element, when its page is shipped out. It therefore comes before the text it goes with, as when it is not deferred.

An image of another kind --- \env{tikzpicture}, \env{tabular}, \cs{fbox} --- is tagged exactly as it would be at the start of a paragraph without the package; describing it is left to the author, as it is without the package.

The package was tried with both engines, \verb|tagging=on| and \verb|pdfstandard=ua-2|, with an \cs{includegraphics}, a \env{tabular}, a \env{tikzpicture}, a \cs{parbox}, a \env{minipage} and an \cs{fbox} as image: tagpdf gives no more warnings than with the same image at the start of an ordinary paragraph, and the structure tree is the same with pdf\LaTeX{} and Lua\LaTeX. veraPDF~1.30 finds the tagged example \texttt{mwe-tagged.tex} conformant to PDF/UA-2 with both engines, and finds nothing in the tests that the same document does not give without the package; with pdf\LaTeX, a footnote breaks clause~8.2.2, with or without the package. The PDF/UA conformance of a whole document does not depend on this package only.

% =========================================================================
\section{Messages}\label{sec:messages}

Each message names the input line where the block \emph{ends}, the line of its \verb|\end{wrapblock}|: the text of the block is read as a whole before anything is typeset, and \TeX{} is on that line by then. Here is what each message means, and what to do about it.

\msgitem{wrapblock blocks cannot be nested.}
\emph{Error.} A block was opened in the text of another one, or in its image. Close the first block before opening the second.

\msgitem{The image of the block that ends on input line \dots{} does not fit at the bottom of the page, and its text is too short \dots}
\emph{Warning.} This is case 3 of section~\ref{sec:bottom}: the whole block moved to the next page, and the bottom of this page is empty. Shorten the image, lengthen the text, or move the block in the source.

\msgitem{The image of the block that ends on input line \dots{} leaves only \dots{} for the text beside it: it is set above the text, which is not wrapped.}
\emph{Warning.} Less than 3\,em would be left for the text beside the image (section~\ref{sec:image}). Make the image narrower; a long text given as the image needs a \cs{parbox}.

\msgitem{The image of the block that ends on input line \dots{} is taller than the page.}
\emph{Warning.} The image runs out of the page at the bottom. Make it smaller.

\msgitem{A box of width \dots, in the block that ends on input line \dots, sits beside the image, where only \dots{} is left.}
\emph{Warning.} A \cs{parbox}, a \env{minipage} or a \texttt{p} cell beside the image is wider than the room left there, and overlaps the image. The warning is given once per block, for the first such box. Make the box narrower, or put it below the image.

\msgitem{The page broke too early in the text of the block that ends on input line \dots}
\emph{Warning.} The image is deferred, and a footnote in the lines that run at full width at the bottom of the page took room that was not counted: a page with only a few lines is left before the image. Rerun \LaTeX: the room the footnote took is written to the \texttt{.aux} file, and the next run counts the lines without it (this needs a kernel of June 2025, section~\ref{sec:req}).

\msgitem{The text of the block that ends on input line \dots{} ended before the bottom of the page: its image is set after it.}
\emph{Warning.} The image was deferred because the text was measured long enough to reach the next page; but the text ended on this page, and the image comes after it. This should not happen; a float or a very tall line in the text can cause it. Use \key{defer=false} for this block.

\msgitem{The block that ends on input line \dots{} moved to a new page while its text was set.}
\emph{Warning.} The lines beside the image moved to another page after their number was counted, which only a very large footnote can cause. The wrapping may be wrong by a few lines. The tests could not make this happen: \TeX{} moves the whole block before it comes to that.

\msgitem{The block that ends on input line \dots{} is inside a box \dots}
\emph{Information}, in the \texttt{.log} only. The block is in a \env{minipage}, a \cs{parbox} or the like: its text is set beside the image, without wrapping under it (section~\ref{sec:where}).

% =========================================================================
\section{How it works, in short}\label{sec:works}

The text of the block is typeset where it stands, in the main galley, as ordinary paragraphs. Nothing is put in a box: this is what leaves page breaks, lists and tagging untouched. The package only changes the shape of the paragraphs.

\begin{itemize}
\item \emph{The image} is typeset at the start of the first line of the block, in a box with no width, height or depth.
\item \emph{Each paragraph} of the block is narrowed at its start, by a hook: the package reads on the page where the paragraph starts, works out how many of its lines run beside the image, and gives those lines a shorter length with \cs{parshape}.
\item \emph{No page break} may separate the lines beside the image: penalties forbid it inside the paragraphs and between them.
\item \emph{When the image does not fit} at the bottom of the page, the text is typeset once at full width, in a box that is thrown away, to measure it. A short text moves to the next page with its image. A long text stays: the package counts the lines that still fit on the page, forces the page break after the last of them, and narrows the lines that follow; the image is drawn at the top of the next page when that page is shipped out.
\end{itemize}

Section~\ref{sec:impl}, at the end of this documentation, prints the whole code and explains it.

% =========================================================================
\section{Other packages}\label{sec:others}

These packages were tried on the same scenes as \pkg{wrapblock} (short text, list beside the image, image in a list, equations, image set lower and lower on the page), with both engines, in November 2026.

\begin{center}
\begin{tabularx}{\linewidth}{@{}lX@{}}
\toprule
Package & What was observed \\
\midrule
\pkg{wrapfig} 3.6 & Does not work in lists, as its documentation says; at the bottom of the page, the image overflows the text area. \\
\pkg{wrapfig2} 7.0.2 & An image in a list breaks the list; at the bottom of the page, the image overflows as with \pkg{wrapfig}. \\
\pkg{wrapstuff} 0.3 & Handles page breaks, by moving the block on the next run; but loses text when a list or a displayed equation runs along the image. \\
\pkg{sidefig-latex} & Wraps lists well; at the bottom of the page, the image goes out of the text area. Not in TeX~Live. \\
side-by-side \env{minipage}s & The text does not run below the image, and the block never breaks. \\
\bottomrule
\end{tabularx}
\end{center}

\pkg{cutwin}, \pkg{picinpar} and \pkg{floatflt} were not tried: according to their documentation, the first two cut a window in a paragraph, and the third one floats the image, which is a different need.

% =========================================================================
\section{History}

\begin{description}
\item[0.1 (15 November 2026)] First version.
\item[0.1.1 (18 November 2026)] Corrections:
  \begin{itemize}
  \item in centred or ragged-left text, an image on the left was moved over the text;
  \item a deferred image was drawn over a float at the top of its page; it is now set below it;
  \item a float or a \cs{marginpar} in a block near the bottom of a page gave an error;
  \item a float in a block gave the warning about a box that is too wide;
  \item the messages now say that the line they give is that of the end of the block.
  \end{itemize}
  The documentation was rewritten, and now ends with the whole code, explained.
\item[0.1.2 (18 November 2026)] The image:
  \begin{itemize}
  \item the default of the \key{width} key is now \texttt{natural}, the width of the image itself, instead of \texttt{0pt}; a length, \texttt{0pt} included, is always taken as it is;
  \item an image that leaves less than 3\,em beside it is set above the text, which is not wrapped;
  \item an image taller than the page no longer leaves an empty page;
  \item the counters stepped by the image (an equation, a caption) are no longer stepped twice;
  \item a block given as the image of another is an error.
  \end{itemize}
  Lists: a block may hold items of a list opened before it and closed after it. A block moved to the next page no longer starts with a blank when its text starts with an \cs{item}, a list or a heading, and it keeps the indentation of the list around it.

  The documentation says what the image may be (section~\ref{sec:image}).
\item[0.1.3 (18 November 2026)] No change in the code. The README says where to report a bug, and the documentation reads the code of the package wherever \TeX{} finds it, so that it compiles from one folder.
\end{description}

% =========================================================================
\clearpage
\section{Implementation}\label{sec:impl}
% the names of the code are long, and break only at _ and :
\setlength{\emergencystretch}{3em}\tolerance=2000

This section prints the whole of \texttt{wrapblock.sty} and explains it. It is meant for someone who wants to check, repair or extend the package; using the package does not require reading it.

\paragraph{How the code is shown.} The code is read from the file itself when this documentation is compiled, so that the two cannot drift apart. The line numbers are those of the file. The pieces are shown in the order in which they are best read, from the environment down to the details, not in the order of the file, where a function is declared before it is used. In the file, each piece is framed by two comment lines, \verb|% <name>| and \verb|% </name>|, which are only there for this documentation.

\paragraph{Names.} The package is written in \pkg{expl3}. Its functions are named \fn{...}, its global variables \gv{...} and its local ones \lv{...}. A few \LaTeXe{} internals are used under their own names: \cs{@labels}, \cs{@totalleftmargin}, \cs{@itempenalty}, \cs{cl@@ckpt}, \cs{@arrayparboxrestore}, \cs{@toplist}, and the switches \texttt{@inlabel}, \texttt{@nobreak}, \texttt{@twoside}, \texttt{@twocolumn}.

\subsection{The principle}

\paragraph{The text stays in the galley.} Most packages that wrap text around an image set the text in boxes of their own. \pkg{wrapblock} does not: the text of the block is typeset where it stands, in the main vertical list, as if the package were not there. The package only acts at the start and at the end of each paragraph, through the paragraph hooks of \LaTeX, and changes three things there:
\begin{itemize}
\item the \cs{parshape} of the paragraph, to narrow the lines that run beside the image;
\item its \cs{interlinepenalties}, to forbid a page break between those lines;
\item the penalties of lists and displayed equations, to forbid a page break between the paragraphs beside the image.
\end{itemize}
\LaTeX{} sees ordinary paragraphs: this is why lists, page breaks and tagging work in the block as they do elsewhere.

\paragraph{The picture to keep in mind.}

\begin{center}
\begin{tikzpicture}[x=0.8cm, y=1cm, font=\footnotesize, txt/.style={line width=2.2pt, black!30}]
  \draw[black!50] (0,1.5) rectangle (7,6.3);
  \foreach \y in {5.9,5.6} \draw[txt] (0.3,\y) -- (6.7,\y);
  \draw[fill=black!10] (4.6,3.1) rectangle (6.7,5.2);
  \node at (5.65,4.15) {image};
  \foreach \y in {5.1,4.8,4.5,4.2,3.9,3.6,3.3,3.0} \draw[txt] (0.3,\y) -- (4.3,\y);
  \foreach \y in {2.7,2.4,2.1,1.8} \draw[txt] (0.3,\y) -- (6.7,\y);
  \draw[dashed] (0.1,2.85) -- (7.3,2.85) node[right] {\gv{bottom_dim}};
  \draw[<->] (6.85,3.1) -- (6.85,2.85);
  \node[right] at (7.3,3.2) {\key{vsep}};
  \draw[<->] (4.3,5.4) -- (6.7,5.4);
  \node[right] at (7.3,5.4) {\gv{shift_dim}: image and \key{hsep}};
  \draw[->] (-0.3,6.3) -- (-0.3,5.1);
  \node[left, align=right] at (-0.4,5.7) {\cs{pagetotal}\\grows downwards};
  \draw[<-] (0.3,5.1) -- (-0.4,5.1) node[left] {first line of the block};
  \node[left, align=right] at (-0.4,4.05) {the \emph{zone}:\\narrowed lines,\\no page break};
  \node[left, align=right] at (-0.4,2.25) {full width again};
\end{tikzpicture}
\end{center}

\paragraph{Positions on the page.} To know which lines run beside the image, the package needs the position of each line on the page. It reads it from \cs{pagetotal}, the height of the material already on the current page. Every position it keeps is expressed the same way: the value \cs{pagetotal} would have at that point, measured downwards from the top of the text area. The main one is \gv{bottom_dim}, the bottom of the area taken by the image, \key{vsep} included. A line whose top lies above \gv{bottom_dim} is narrowed; the others keep their width.

\paragraph{Vocabulary.} The code and this commentary use these words:
\begin{description}
\item[zone] the lines beside the image. It starts with the first line of the block and ends with the first paragraph that goes below the image. No page break may happen inside it. \gv{active_bool} is true while it runs.
\item[pending] the image is not typeset yet; the first paragraph of the block will place it (\gv{pending_bool}).
\item[deferred] the image does not fit at the bottom of the page and will be drawn at the top of the next one, while the text starts on this page at full width.
\item[waiting] a deferred image whose page has not broken yet (\gv{wait_bool}).
\item[committed] a deferred image whose page is known; it is drawn when that page is shipped out.
\end{description}

\paragraph{The life of a block.}
\begin{enumerate}
\item The environment reads its arguments, typesets the image once to measure it, and compares its height with the room left on the page (\fn{begin:n}).
\item If the room is too small, \fn{decide:n} chooses: either the whole block moves to the next page (\fn{need_space:}), or, when the text is long enough, the block stays and the image is deferred.
\item At the start of each paragraph, the \texttt{para/begin} hook computes how many lines of the paragraph run beside the image, and sets \cs{parshape} (\fn{para_begin:}, \fn{shape:Nnnn}). In the first paragraph, it also puts the image at the start of the first line (\fn{place_image:}).
\item At the end of each paragraph, the \texttt{para/after} hook decides whether the zone goes on; if it does, it forbids a page break before the next paragraph (\fn{para_after:}).
\item At the end of the environment, vertical space is added if the text is shorter than the image (\fn{end:}).
\end{enumerate}
A block inside a box (a \env{minipage}, a \cs{parbox}) takes another, much simpler road (section~\ref{sec:impl-boxes}).

\paragraph{Where the package hooks in.}

\begin{center}
\begin{tabularx}{\linewidth}{@{}lX@{}}
\toprule
Hook & What the package does there \\
\midrule
\texttt{para/before} & keeps \cs{prevdepth}, needed to place the first line \\
\texttt{para/begin} & sets the shape of the paragraph; places the image in the first one \\
\texttt{para/end} & clears three penalties in the paragraph that ends the page (deferred image) \\
\texttt{para/after} & ends the zone or keeps it together; commits a deferred image \\
\cs{everydisplay} & sets the shape again after a displayed equation \\
\cs{@arrayparboxrestore} & at the start of a box in the block: warns if it is too wide, and turns the package off inside \\
\texttt{shipout/after} & counts the pages shipped out \\
\texttt{shipout/foreground} & draws the deferred images of the page \\
\texttt{build/column/before} & measures the floats at the top of the page; notices a page that broke too early \\
\texttt{enddocument/afterlastpage} & writes to the \texttt{.aux} file the room footnotes took \\
\bottomrule
\end{tabularx}
\end{center}

\subsection{Identification and state}

\code{ident}

The package asks for a kernel of June 2023: an older format stops with a clear message. Older kernels were not tried, and the package was tested with TeX~Live~2026 only. The hook \texttt{build/column/before} exists since June 2025 (section~\ref{sec:req}).

\code{state}

The variables of a block are global, because a block runs over several paragraphs, and a paragraph often ends in another group than the one the block started in (an item, an environment). They describe:
\begin{itemize}
\item \emph{the image}: the material given (\gv{img_tl}), the box built from it (\gv{img_box}), its \key{width} key, its height plus \key{vsep} (\gv{height_dim}), and the width it takes from the lines, \key{hsep} included (\gv{shift_dim});
\item \emph{the block}: its left edge and its width (\gv{left_dim}, \gv{width_dim}), the side of the image, and the bottom of the image area (\gv{bottom_dim});
\item \emph{the zone}: running or not (\gv{active_bool}), image placed or not yet (\gv{pending_bool}), the number of lines narrowed in the current paragraph (\gv{narrowed_int}), the line width left beside the image (\gv{avail_dim}), and the shapes set so far (\gv{shapes_seq}, see \fn{unstale:});
\item \emph{the pages}: the number of pages shipped out so far (\gv{ship_int}), and its value where the zone started (\gv{origin_ship_int}); when the two differ, the zone has moved to another page;
\item \emph{the penalties the block changes}, saved to be put back: \cs{predisplaypenalty}, \cs{postdisplaypenalty}, \cs{@itempenalty}, \cs{@beginparpenalty}, \cs{@endparpenalty}.
\end{itemize}
Three local switches say where the code stands:
\begin{itemize}
\item \lv{outer_bool} is true in the text of the block itself. It is false in a box inside the block (a \cs{parbox}, a footnote, a float) and in the box where the text is measured: the hooks then leave the paragraphs alone.
\item \lv{inside_bool} is true within the environment.
\item \lv{inbox_bool} is true when the block itself sits in a box.
\item \lv{inimage_bool} is true while the image is typeset, to catch a block given as the image of another; \lv{alone_bool} is true when the image is too wide to have text beside it.
\end{itemize}
The remaining local variables are scratch space for the computations.

\code{statedefer}

These variables serve the deferred image and the measure of the text:
\begin{itemize}
\item \gv{wait_bool}: a deferred image is waiting for its page break; \gv{full_end_int}: the number of the last full-width line before that break; \gv{breakpar_bool}: the current paragraph is the one that ends the page;
\item \gv{def_seq}, \gv{def_int}: the deferred images committed and not yet drawn, and their numbering; \gv{struct_int}: the structure element that will hold the image in a tagged PDF; \gv{top_dim}: the height of the floats at the top of the page being built;
\item \gv{block_int}, \gv{goal_dim}, \gv{short_dim} and the two property lists: the room footnotes take, kept from one run to the next (see the chunk \texttt{aux});
\item \gv{text_dim}, \gv{counters_tl}, \lv{measure_box}, \lv{labels_box}, the two float boxes and the two lists of float boxes: the measure of the text (\fn{measure:n}).
\end{itemize}

\code{shipcount}

\gv{ship_int} counts the pages shipped out. The page counter would not do: the document can reset it. The count serves two purposes: to notice that the zone has moved to another page (\fn{check_ship:}), and to know on which page a deferred image must be drawn (\fn{overlay:nnnnnnn}).

\subsection{Keys}

\code{keys}

The keys are local: \cs{wrapblockset} sets them for the current group, and the optional argument of the environment for one block. \key{width=natural} is kept as a width of minus \cs{maxdimen}, which no length can be; the code reads it as ``the width of the image''. The initial values of \key{hsep} and \key{vsep} are computed when the package is loaded, with the font and the \cs{baselineskip} of that moment.

\subsection{The environment}

\code{env}

The environment takes its text as an argument (\texttt{+b}), because the text may have to be measured before it is typeset (\fn{measure:n}). This is what forbids verbatim material in it.

In order, the environment:
\begin{enumerate}
\item ends the current paragraph, numbers the block and sets its keys;
\item builds the image once, with tagging suspended, only to measure it: \gv{height_dim} is its height and depth plus \key{vsep}, \gv{shift_dim} its width plus \key{hsep}. The \LaTeX{} counters are kept before and put back after (\fn{counters_save:}), so that a numbered equation or a caption in the image is not counted twice. The image is built for good later, inside the first paragraph;
\item warns about an image taller than the page. An image that leaves less than 3\,em beside it is not wrapped at all: it is typeset on a line of its own, the text follows at full width, and nothing of the rest of the package is used (\lv{alone_bool});
\item tells a block in a box from a block on the page. After \cs{par}, \TeX{} is in internal vertical mode in a \env{minipage} or a \cs{parbox}, and in outer vertical mode on the page: \ecs{mode_if_inner:TF} tests it. On the page, \fn{begin:n} prepares the zone;
\item typesets the text, as it is.
\end{enumerate}

\code{begin}

\fn{begin:n} receives the text only to measure it if needed. In order:
\begin{enumerate}
\item A block in the text of another block is an error: the state of a block is global, and two blocks would share it.
\item The left edge and the width of the block are read from \cs{@totalleftmargin} and \cs{linewidth}: in a list, they are those of the current item.
\item The room left on the page is compared with what the image needs: its height and one line more. On an empty page there is always room (\cs{pagegoal} is \cs{maxdimen} until something is put on the page). When the room is too small, \fn{decide:n} finds a way out (section~\ref{sec:impl-room}).
\item The penalties are saved, to be put back at the end of the zone.
\item \fn{box_check:} is put at the front of \cs{@arrayparboxrestore}, which \LaTeX{} runs at the start of every \cs{parbox}, \env{minipage}, \texttt{p} cell, footnote and float. It warns about a box too wide for the room beside the image, then turns \lv{outer_bool} off inside the box (section~\ref{sec:impl-boxes}). The change is local to the environment.
\item The state of the image is set. Normally the image is pending: the first paragraph will place it. When \fn{decide:n} has deferred it, the zone is prepared on the next page instead: its bottom is computed from \cs{topskip}, the first baseline of a page; \gv{goal_dim} keeps the \cs{pagegoal} of this point and \gv{short_dim} the room footnotes took in the previous run (see the chunk \texttt{aux}); and an empty structure element is made for the tagged PDF (\fn{placeholder:}).
\end{enumerate}

\code{end}

At the end of the text, \fn{end:} deals with three cases, in order:
\begin{enumerate}
\item \emph{A deferred image is still waiting.} The text was measured long enough to reach the next page, but it ended on this one. This should not happen; a tall line can cause it. The image goes back to the pending state, and the page is broken first if the image does not fit after the text.
\item \emph{The image is still pending}, because the block is empty or because of the case above. A paragraph made of one empty line is typeset to carry it.
\item \emph{The text ended above the bottom of the image.} Vertical space is added down to it, with \cs{nobreak} before it. The next text thus starts below the image: this is what closes the block.
\end{enumerate}
\fn{stop:} then ends the zone and puts the penalties back.

\subsection{Is there room for the image?}\label{sec:impl-room}

\code{room}

The room left on the page is \cs{pagegoal} minus \cs{pagetotal}, with one correction right after a heading. A heading puts a space below itself, but the page builder only moves that space to the page when the next box comes: \cs{pagetotal} does not count it yet. That space is the last item of the vertical list, and \cs{lastskip} gives it.

When the block does not follow a heading and the page ends with some other glue, that glue is subtracted although \cs{pagetotal} already counts it. The room is then found a little smaller than it is. The error is on the safe side: the block may move when its image would just have fitted, but the image never overflows.

\code{decide}

\fn{decide:n} is called when the image does not fit. It ends in one of two states: \lv{defer_bool} is true, and the block stays; or \fn{need_space:} has broken the page, and the block is at the top of the next one. The tests come in this order:
\begin{enumerate}
\item \emph{Two columns}, or a \env{multicols} environment with more than one column: the block moves. A deferred image is drawn at the top of the page, and the package does not know the column.
\item \emph{\key{defer=false}, or less than two lines of room}: the block moves, and the text is not measured.
\item \emph{Otherwise the text is measured} at full width. A deferred image needs a text that fills the room left on this page, and two lines of the next page. A shorter text would leave the image alone on the next page: the block moves, with the warning \texttt{short}. A longer one stays, and the image is deferred.
\end{enumerate}

\code{needspace}

\fn{need_space:} moves the block to the next page. An image taller than the page is a case apart: the block gets a plain \cs{newpage}, since the rule described below would itself not fit on the next page, and would leave it empty. In every other case, \fn{need_space_aux:} does the work, and \cs{newpage} would not do: a block that follows a heading must take the heading with it. The package lets the page builder of \TeX{} choose the break, since it knows the best breakpoint before this point. In order:
\begin{enumerate}
\item \cs{prevdepth} is kept, to be put back at the end.
\item A \cs{penalty}~0 offers a breakpoint just before the block; not after a heading (\texttt{@nobreak} is then true), which must stay with the block.
\item An invisible rule is added, too tall for the page: as tall as the image area plus a line, plus the shrink of the page (\cs{pageshrink}) and 1\,sp.
\item A \cs{penalty}~9999 offers a breakpoint after the rule, and the primitive \cs{par}, in vertical mode, runs the page builder. The \cs{par} is in a group, because it clears \cs{parshape}, which carries the indentation of a list. The page cannot hold the rule, so \TeX{} breaks at the best breakpoint it has seen: before the block, or before the heading, since a heading forbids a break after itself. The rule goes to the next page.
\item There, a negative skip gives the height of the rule back, and \cs{prevdepth} is put back: \cs{pagetotal} and the interline glue are as if the rule had never been there. The skip sits between two \cs{penalty}~10000: the first keeps a page break away from it; the second hides it from \cs{addvspace}, which an \cs{item}, a list or a heading at the start of the block calls, and which cancels a negative skip it finds last.
\end{enumerate}
The rule must be taller than the room by the shrink of the page. Otherwise, when the image is only a little too tall, the page could still hold the rule by shrinking its glue: \TeX{} would break after the rule, and leave the heading alone at the bottom of the page.

\code{measure}

The measure typesets the text at full width in a \cs{vbox} that is thrown away, and keeps its height and depth in \gv{text_dim}. Whatever the text writes to a file without \cs{immediate} (labels, table of contents, index) and its footnotes vanish with the box. Its other global effects are undone by hand:
\begin{itemize}
\item \emph{The \LaTeX{} counters}, by \fn{counters_save:}. \cs{cl@@ckpt} lists them all, as \cs{@elt}\marg{name}. \cs{@elt} is redefined so that running the list appends to \gv{counters_tl} one command per counter, which sets it back to its present value.
\item \emph{The label of an item.} \cs{@labels} is the box where \cs{item} leaves its label for the next paragraph. A block that comes first in an item would use the label in the measure, and leave none for the text. The box is copied, and set again from the copy after the measure.
\item \emph{The switches of lists and headings} (\texttt{@inlabel}, \texttt{@newlist}, \texttt{@noparitem}, \texttt{@minipage}, \texttt{@nobreak}), which the first paragraph of the text turns off. They are appended to \gv{counters_tl} as well. Without this, \texttt{@nobreak} would be left false after a heading, and the page could break between the heading and the block.
\item \emph{Floats and \cs{marginpar}.} They cannot leave a box. Between two paragraphs, \LaTeX{} notices the box and gives the error ``Not in outer par mode'': the error is turned off, and the float is set in a box of the package. Inside a paragraph, \LaTeX{} does not notice it and takes one of its float boxes, which would end as ``Float(s) lost'': its two lists of float boxes, \cs{@freelist} and \cs{@currlist}, are put back after the measure.
\end{itemize}
In the box, \lv{outer_bool} is false, so that the hooks of the package leave the text alone. The width is \cs{linewidth}, without the indentation of a list (\cs{@totalleftmargin} and \cs{parshape} are cleared). Overfull and underfull boxes are not reported, since the box is never seen. Tagging is suspended, so that nothing of the text goes into the structure tree twice.

What is not undone is done twice: an \cs{immediate}\cs{write}, a \cs{gdef}, a \TeX{} or \pkg{expl3} counter stepped globally (section~\ref{sec:know}).

\subsection{Each paragraph of the block}

\code{parahooks}

The two hooks act only while a zone runs, and only in the text of the block itself (\lv{outer_bool}).
\begin{itemize}
\item \texttt{para/before} runs in vertical mode. \LaTeX{} has already added \cs{parskip} and run the page builder. The hook keeps \cs{prevdepth}, the depth of the line before the paragraph.
\item \texttt{para/begin} runs in horizontal mode, before the first character of the paragraph, and before \LaTeX{} puts the indentation box back. The \cs{parshape} of the paragraph can still be set there, and the image is placed there, at the very start of the first line.
\end{itemize}

\code{baseline}

This function gives the baseline of the first line of the paragraph, in page coordinates. There are three cases:
\begin{itemize}
\item \emph{An empty page}: the first baseline is at \cs{topskip}.
\item \emph{The usual case.} When \texttt{para/begin} runs, the page builder has taken the \cs{parskip} glue, and a glue on the page adds the depth of the line before it to \cs{pagetotal}. The baseline of that line is therefore at \cs{pagetotal} minus its depth, kept by \texttt{para/before}; the new baseline is one \cs{baselineskip} lower.
\item \emph{No interline glue} (\cs{prevdepth} is $-1000$\,pt or less, after a rule or \cs{nointerlineskip}): the line sits right below \cs{pagetotal}, and its baseline is taken a strut height lower.
\end{itemize}

\code{parabegin}

\fn{para_begin:} computes the first baseline, then sends a paragraph of a waiting deferred image to \fn{defer_para:N} (section~\ref{sec:impl-defer}), and the others to \fn{para_begin_aux:}. There:
\begin{enumerate}
\item The first paragraph of the zone, the one that finds the image pending, fixes the bottom of the image area: the top of its first line (its baseline minus the height of a strut) plus \gv{height_dim}. The following paragraphs only check that the zone has not moved to another page.
\item The shape is computed by \fn{shape:nn}.
\item If some lines run beside the image, the penalties around displayed equations are set to 10\,000, and the first paragraph places the image. If none does, the paragraph starts below the image: the zone is over.
\end{enumerate}

\code{shape}

\fn{shape:Nnnn} is the heart of the package: it sets the \cs{parshape} and the \cs{interlinepenalties} of the paragraph. Its arguments are:
\begin{description}
\item[\texttt{\#1}] nothing, or \cs{global} after a displayed equation (section~\ref{sec:impl-display});
\item[\texttt{\#2}] the number of lines of the paragraph already typeset, before a displayed equation; 0 at the start of a paragraph;
\item[\texttt{\#3}] the number of lines kept at full width before the narrowed ones, for a deferred image; 0 otherwise;
\item[\texttt{\#4}] the baseline of the first line to narrow.
\end{description}
\fn{shape:nn} and \fn{shape:Nnn} are short forms for the usual cases, where \texttt{\#3} is 0.

\emph{How many lines are narrowed.} The lines to narrow are those whose top lies above \gv{bottom_dim}. Line $k$, counted from 0, has its baseline at \(\text{\#4} + k\,\text{\cs{baselineskip}}\) and its top a strut height higher. It is narrowed when \(k < (\text{\gv{bottom_dim}} - \text{\#4} + h_{\text{strut}}) / \text{\cs{baselineskip}}\): the count is the ceiling of that ratio. A line taller than a strut pushes the next ones down; the count is then one line too large, never too small. A line may be narrowed below the image, but no line runs over it.

\emph{How wide they are.} The narrowed lines are cut from the shape \LaTeX{} gave the paragraph, which is not always the full width: in a list, \LaTeX{} sets a \cs{parshape} of one line, with the indentation and the width of the item. With the image on the left, the indentation of the line grows by \gv{shift_dim} and its width shrinks as much. With the image on the right, the line keeps its indentation and ends \gv{shift_dim} before the right edge of the block; a nested list, which starts further right, loses less of its own width. The width left is kept in \gv{avail_dim}, for \fn{box_check:}.

\emph{The two lists.} The new \cs{parshape} lists, in order: \texttt{\#2} entries for the lines already typeset (their values no longer matter, but \cs{parshape} counts from the first line of the paragraph); \texttt{\#3} full-width lines; the narrowed lines; and a last entry, the shape \LaTeX{} had given, which \TeX{} repeats for all the lines that follow. \cs{interlinepenalties} follows the same order:
\begin{itemize}
\item after a narrowed line, 10\,000: the zone cannot break across pages;
\item after a full-width line, the usual \cs{interlinepenalty};
\item after the last full-width line, $-10\,000$: this forces the page break of a deferred image. A lower value is not used: \LaTeX{} keeps those for its own output routine.
\end{itemize}
For instance, in the usual case (\texttt{\#2} and \texttt{\#3} are 0), a paragraph of full width 345\,pt with four lines beside an image that takes 100\,pt on the right gets
\begin{verbatim}
\parshape 5  0pt 245pt  0pt 245pt  0pt 245pt  0pt 245pt  0pt 345pt
\interlinepenalties 5  10000 10000 10000 10000 0
\end{verbatim}

\emph{The signature.} The number of entries of each shape, with the indentation and the width of its first entry, is kept in \gv{shapes_seq}, for \fn{unstale:}.

\code{unstale}

\TeX{} clears \cs{parshape} at the end of every paragraph, but only locally. Suppose a paragraph ends inside a deeper group than the one it started in: an item whose text opens a nested list, for instance. When that group ends, the narrowed shape comes back, and the next paragraph of the outer level would be narrowed a second time. \fn{unstale:} recognises such a leftover at the start of a paragraph of the block: a \cs{parshape} of more than one line whose signature is among those the block has set. It keeps only its last entry, which is the shape \LaTeX{} had given.

\subsection{Setting the image}

\code{build}

\fn{build:} typesets the image in \gv{img_box}, centred in the width of the \key{width} key when one is given. It is called twice: by the environment, to measure the image, and by \fn{place_image:}, inside the first paragraph. \lv{inimage_bool} is set inside the box: a \env{wrapblock} met there is an error. The second call is not a waste: in a tagged PDF, an \cs{fbox}, a \env{tabular} or a \cs{parbox} built outside a paragraph would open its structure elements at the wrong place.

\fn{place_image:} puts the image at the start of the first line of the block:
\begin{itemize}
\item The image goes in a box of zero width, height and depth, so that the line keeps its height and its natural width.
\item The first line starts at its own indentation, the narrowed one. A kern moves the image from there to the left edge of the block, or to its right edge minus the width of the image.
\item The image is lowered so that its top is at the top of the first line, a strut height above the baseline.
\item In centred or ragged-left text, \cs{leftskip} comes before the image in the line, and would move it. The opposite glue is put before the image, and \cs{leftskip} again after it: the two cancel exactly, whatever their stretch, and the image is back at the start of the line. The two penalties forbid a line break at these glues.
\end{itemize}

\code{labels}

When the block comes first in an \cs{item}, \LaTeX{} typesets the label at the start of the first line, from the box \cs{@labels}; the label reaches into the margin by a negative kern. With the image on the left, the first line starts after the image, and the label would land on the image. The label box is wrapped in two kerns: the first moves the label back by \gv{shift_dim}, the second gives the width back.

\subsection{Keeping the zone on one page}

\code{paraafter}

At the end of each paragraph, \fn{para_after:} first tidies up: it clears the \cs{interlinepenalties} of the paragraph (\TeX{} keeps them, unlike \cs{parshape}) and puts back the penalties around displayed equations. After a displayed equation, shape and penalties were set globally, and are cleared globally.

The branch for a waiting deferred image is explained in section~\ref{sec:impl-defer}. Otherwise \fn{zone_after:} decides whether the zone goes on:
\begin{itemize}
\item \emph{The paragraph has more lines than were narrowed}: it went below the image, and the zone is over.
\item \emph{Otherwise}, the primitive \cs{par} has run the page builder, and \cs{pagetotal} plus \cs{pagedepth} is where the paragraph ended. If that is above the bottom of the image, the next paragraph starts beside the image too. \cs{nobreak} forbids a page break between the two paragraphs, and the list penalties do the same when the next paragraph is an item, or starts or ends a list. If the paragraph ended at or below the bottom of the image, the zone is over.
\end{itemize}

\code{listpen}

\cs{@itempenalty}, \cs{@beginparpenalty} and \cs{@endparpenalty} are the penalties \LaTeX{} puts before an item, before a list and after a list. They are set globally to 10\,000 while the zone runs. \fn{stop:} ends the zone and puts them back.

\code{checkship}

All these penalties forbid a page break in the zone. A footnote can still make the page too short for lines that were already counted, and \TeX{} then breaks where it can. \fn{check_ship:} notices it: the number of pages shipped is no longer what it was at the start of the zone. The zone is then assumed to go on at the top of the new page, and the warning \texttt{moved} says that the wrapping may be wrong by a few lines. The tests could not make this happen: \TeX{} moves the whole block before it comes to that.

\subsection{Displayed equations}\label{sec:impl-display}

\code{display}

A displayed equation interrupts a paragraph without ending it. \TeX{} breaks the lines before the equation, typesets the equation, then goes on with the same paragraph, whose \cs{parshape} still counts from its first line. But below the equation, the lines are no longer where \fn{shape:Nnnn} expected them: the equation has its own height and its own spacing. The shape must be computed again.
\begin{itemize}
\item \fn{display_hook:} is added to \cs{everydisplay}. It uses \ecs{group_insert_after:N} to run \fn{after_display:} right after the end of the equation.
\item At that point, the equation is on the page and the page builder has run. \cs{prevgraf} is the number of lines typeset so far, the equation counting for three. The baseline of the next line is estimated from \cs{pagetotal}, taking the depth of a strut for that of the equation.
\item The shape is computed again from line \cs{prevgraf} on: this is what the argument \texttt{\#2} of \fn{shape:Nnnn} is for.
\end{itemize}
The shape is set globally. With \pkg{amsmath}, the end of an \env{equation} or an \env{align} is followed by the end of the group of the environment, which would undo a local \cs{parshape}. \gv{global_bool} tells \fn{para_after:} to clear it globally too.

\subsection{The deferred image}\label{sec:impl-defer}

When the image does not fit at the bottom of the page and the text is long enough, the text runs at full width to the bottom of the page, and the image goes to the top of the next one.

\begin{center}
\begin{tikzpicture}[x=0.85cm, y=1cm, font=\footnotesize, txt/.style={line width=2.2pt, black!30}]
  \draw[black!50] (0,0) rectangle (4.4,5.6);
  \foreach \y in {5.2,4.9,4.6,4.3,4.0,3.7,3.4,3.1,2.8,2.5} \draw[txt] (0.3,\y) -- (4.1,\y);
  \draw[line width=2.6pt, black!70] (0.3,2.0) -- (2.2,2.0);
  \foreach \y in {1.5,1.2,0.9,0.6} \draw[txt] (0.3,\y) -- (4.1,\y);
  \node[above] at (2.2,5.6) {the page where the block starts};
  \node[left, align=right] at (-0.1,2.0) {heading};
  \node[left, align=right] at (-0.1,1.05) {the block starts:\\full-width lines};
  \draw[<-] (4.1,0.5) -- (4.9,-0.2);
  \node[below, align=center] at (5.6,-0.2) {forced page break ($-10\,000$)\\after the last line that fits};
  \draw[black!50] (6.8,0) rectangle (11.2,5.6);
  \draw[fill=black!10] (9.1,3.1) rectangle (10.9,5.3);
  \node at (10.0,4.2) {image};
  \foreach \y in {5.2,4.9,4.6,4.3,4.0,3.7,3.4,3.1} \draw[txt] (7.1,\y) -- (8.8,\y);
  \foreach \y in {2.8,2.5,2.2,1.9,1.6} \draw[txt] (7.1,\y) -- (10.9,\y);
  \node[above] at (9.0,5.6) {the next page};
  \node[right, align=left] at (11.3,4.2) {drawn when the\\page is shipped out};
  \node[right, align=left] at (11.3,2.2) {the block goes on};
\end{tikzpicture}
\end{center}

\TeX{} does neither of two things by itself: break the page after a given line of a paragraph, and draw an image on a page where it was not typeset. The image goes through three states: \emph{waiting}, from the start of the block until the page breaks; \emph{committed}, once its page is known; drawn, when that page is shipped out.

\code{deferpara}

\fn{defer_para:N} runs while the image is waiting: at the start of each paragraph of the block, and after each displayed equation in it. Its job is to count the full-width lines that still fit on the page.

\emph{The room.} A line fits when its bottom, a strut depth below its baseline, is above the bottom of the page, \cs{pagegoal}. Footnotes that come later in these lines will take room that \cs{pagegoal} does not show yet. The previous run measured it: \gv{short_dim} is the room the footnotes of the block took (see the chunk \texttt{aux}). What they take already is the decrease of \cs{pagegoal} since the block started, \gv{goal_dim} minus \cs{pagegoal}. The difference is still to come, and is subtracted from \cs{pagegoal}.

\emph{The three cases.}
\begin{itemize}
\item \emph{Some lines fit.} The shape keeps them at full width, forces the break after the last of them, and narrows the lines that follow, which will be at the top of the next page: their first baseline is \cs{topskip}. \gv{full_end_int} keeps the number of that last full-width line. If the paragraph ends before it, nothing more happens, and the next paragraph counts again. If the paragraph goes past it, the page breaks inside the paragraph: \gv{breakpar_bool} is set for \texttt{para/end}, and \fn{para_after:} will commit the image.
\item \emph{No line fits.} The page must break before the first line of the paragraph: a \cs{vadjust}\texttt{\,pre} puts a penalty of $-10\,000$ above that line. The image is committed at once, to the next page, and the lines are narrowed from the first one.
\item \emph{The page has already broken}, between two paragraphs: the image is committed to the page being built, and the lines are narrowed from the first one.
\end{itemize}

\code{paraend}

The $-10\,000$ that ends the page must reach the page builder unchanged: a penalty of $-10\,000$ or less forces a break, anything above only suggests one. But \TeX{} adds to the penalty between two lines the club penalty after the first line of a paragraph, the widow penalty before the last one, and the broken penalty after a hyphenated line. With a club penalty of 150, the forced break becomes $-9\,850$, and \TeX{} breaks the page a line earlier or later, as it pleases.

These penalties are therefore cleared in the paragraph that ends the page. This is done at \texttt{para/end}, just before \TeX{} breaks the paragraph into lines. At \texttt{para/begin} it would be too early: the \cs{everypar} of \LaTeX, which runs afterwards (for \cs{@afterheading}, for \cs{item}), sets \cs{clubpenalty} again.

\paragraph{When the page has broken.} This is the branch of \fn{para_after:} for a waiting image (chunk \texttt{paraafter}, above). It acts when the paragraph has more lines than \gv{full_end_int}: the forced break is then inside the paragraph that just ended. The primitive \cs{par} that ended it has run the page builder, which met the $-10\,000$ and ran the output routine: the page is shipped out, and \gv{ship_int} counts it. The image is committed to the page being built, the one that starts with the narrowed lines, and \fn{zone_after:} takes over as for any zone.

One check comes first. If more than one page was shipped since the block started, the page broke twice: a footnote in the full-width lines shortened the page, which broke before the planned line. The image is still drawn on the page with the narrowed lines, but a page with a few lines is left before it. The warning \texttt{early} asks for another run, which will avoid it (chunk \texttt{aux}).

\code{commit}

\fn{commit:n} records a deferred image for the page that will be shipped out after \texttt{\#1} pages. The material of the image and its data (page, left edge and width of the block, \key{width} key, side, structure element) are kept in two token lists numbered by \gv{def_int}, and the number is added to \gv{def_seq}, the list of the images that wait for their page. The image is not typeset here: it is typeset when its page is shipped out.

\code{placeholder}

In a tagged PDF, the structure follows the order in which things are typeset. An image drawn when the page is shipped out would come after everything else on its page, after the text it goes with. An empty structure element, of type \texttt{NonStruct}, is therefore made where the block starts; the image will be attached to it. Without tagging, \gv{struct_int} stays at 0.

\code{topfloats}

\LaTeX{} adds the floats of the top of a page when the page is finished, in the output routine: \cs{pagetotal} never counts them, and the narrowed lines, which follow the text, come out below them. The deferred image must be drawn below them too. The \texttt{build/column/before} hook runs just before \LaTeX{} puts them in place, and they are still in the list \cs{@toplist}. \fn{top_floats:} adds up their height, the way \LaTeX{} stacks them: each box, \cs{floatsep} between two of them, \cs{textfloatsep} below the last. The natural lengths are used: on a page stretched by \cs{flushbottom}, the image may be off by the stretch of \cs{textfloatsep}, a few points.

\code{overlay}

The deferred images are drawn by the \texttt{shipout/foreground} hook. It runs as each page is shipped out, in a \env{picture} whose origin is the top left corner of the paper.
\begin{itemize}
\item \fn{overlays:} goes through the images that wait. The images drawn are removed from the list afterwards, not during the loop that reads it.
\item \fn{overlay:nnnnnnn} draws an image if its page is the one being shipped: the image was committed for the page shipped after \texttt{\#1} pages, and \gv{ship_int} pages have been shipped.
\item \emph{Vertically}, the image is put below the top of the text area (1\,in, \cs{voffset}, \cs{topmargin}, \cs{headheight}, \cs{headsep}), below the floats of the top of the page, with its top at the top of the first line: \cs{topskip} minus the height of a strut. This is where an image that is not deferred sits.
\item \emph{Horizontally}, it starts from the left margin, which depends on the parity of the page in a two-sided document, then from the left edge of the block; on the right, it is flush with the right edge of the block.
\item \emph{In a tagged PDF}, the image is wrapped in a marked-content sequence and a \texttt{P} structure element, whose parent is the placeholder made where the block started.
\end{itemize}

\code{aux}

This chunk repairs, on the next run, a page that broke too early because of a footnote.

\emph{The problem.} A footnote in the full-width lines takes room at the bottom of the page. That room is only known when the footnote is typeset, after the lines were counted. The page then breaks before the planned line, and breaks again at the forced break: a page with a few lines is left before the image.

\emph{Noticing it.} The \texttt{build/column/before} hook runs each time a page is finished, and \cs{outputpenalty} is then the penalty of the break. While an image is waiting, a value other than $-10\,000$ means that the page broke elsewhere than planned.

\emph{Measuring the room.} The room the footnotes of the block took is the height of all the footnotes of the page (the box \cs{footins} and the glue above it) minus what the footnotes before the block had taken, \cs{vsize} minus \gv{goal_dim}. If nothing is found, one line is assumed. (\cs{footins} is the number of an insertion: the glue above the footnotes is read with the primitive \cs{skip}, not with \ecs{skip_use:N}.)

\emph{Keeping it.} The room is kept under the number of the block, and written to the \texttt{.aux} file at the end of the document, as \verb|\wrapblock@short|\marg{block}\marg{room}. The next run reads it into \gv{short_dim}, and \fn{defer_para:N} counts the lines without that room.

\emph{Not forgetting it.} On that next run, the page holds fewer lines, and the footnote may now be below the break: no early break is noticed. If the value were dropped then, the run after would break too early again, and the runs would alternate for ever. A value found once is therefore written again as long as no new one replaces it.

The \cs{providecommand} written first lets the \texttt{.aux} file be read by a document that no longer loads the package.

\code{msgs}

The two warnings of the deferred image: \texttt{early} for a page that broke too early (above), \texttt{alone} for a text that ended before the page broke (\fn{end:}).

\subsection{Boxes}\label{sec:impl-boxes}

\code{boxcheck}

The text of a \cs{parbox}, a \env{minipage} or a \texttt{p} cell is typeset with the width it was given: the package cannot narrow it. \fn{box_check:} runs at the start of every such box, through \cs{@arrayparboxrestore}, where \cs{hsize} is already the width of the box. It warns when the box is wider than the room left beside the image, once per block: the input line it compares is that of the end of the block, the same for all its boxes. It stays silent when the box cannot be beside the image:
\begin{itemize}
\item before the image is placed, and while a deferred image waits;
\item below the image (\cs{pagetotal} is past \gv{bottom_dim});
\item in a footnote, whose text is typeset in an insertion (group type~11) and goes to the foot of the page;
\item in a float (\cs{@captype} is defined there), which goes elsewhere on the page.
\end{itemize}

\code{inbox}

A block that is itself in a box cannot use any of the above: in a box, \cs{pagetotal} says nothing of the position, and no page can break anyway. The block is then made of two boxes side by side: the text in a \env{minipage} as wide as the line minus \gv{shift_dim}, and the image, lowered so that its top is at the top of the first line. The text does not run below the image. An information message in the \texttt{.log} says so.

\end{document}
