Debian Codegraph @

texmf-dist/source/luatex/lua-widow-control/tb133chernoff-widows.ltx

raw
1 % lua-widow-control
2 % https://github.com/gucci-on-fleek/lua-widow-control
3 % SPDX-License-Identifier: MPL-2.0+ OR CC-BY-SA-4.0+
4 % SPDX-FileCopyrightText: 2022 Max Chernoff
5
6 \documentclass[final]{ltugboat}
7
8 % This is the LaTeX source for the following article:
9 % @article{tb133chernoff-widows,
10 % title={Automatically removing widows and orphans with
11 % \texttt{lua-widow-control}},
12 % author={Chernoff, Max},
13 % journal={TUGboat},
14 % volume={43},
15 % number={1},
16 % pages={28--39},
17 % year={2022},
18 % month=may,
19 % DOI={10.47397/tb/43-1/tb133chernoff-widows},
20 % }
21 % Please refer to the PDF on tug.org for the authoritative version.
22
23 % Compiling:
24 % context tb133chernoff-widows-figure.ctx
25 % lualatex tb133chernoff-widows.ltx
26 % bibtex tb133chernoff-widows
27 % lualatex tb133chernoff-widows.ltx
28 % lualatex tb133chernoff-widows.ltx
29 % The original article was built with the final/frozen TeX Live 2021.
30
31 % Set the publication info
32 \vol 43, 1.
33 \issyear 2022.
34 \issueseqno=133
35 \setcounter{page}{28}
36 \PrelimDraftfalse
37
38 % Load lwc
39 \usepackage[balanced]{lua-widow-control}
40
41 % Table Stuff
42 \usepackage{tabularx}
43 \usepackage{hhline}
44 \usepackage{booktabs}
45 \AddToHook{env/tabularx/before}{\smallskip\noindent}
46 \AddToHook{env/tabularx/after}{\smallskip}
47 \AddToHook{env/tabular/before}{\smallskip\noindent}
48 \AddToHook{env/tabular/after}{\smallskip}
49 \renewcommand{\arraystretch}{1.15}
50
51 \usepackage{graphicx}
52
53 % Let the macro names in section headings be in boldface
54 \usepackage{lmodern}
55 \DeclareRobustCommand{\cs}[1]{\texttt{\textbackslash#1}}
56
57 \makeatletter
58 \DeclareRobustCommand{\eTeX}{%
59 \ifx\f@series\bfseries@rm%
60 \ensuremath{\boldsymbol{\varepsilon}}\mbox{-}\kern-.125em\TeX%
61 \else%
62 \ensuremath{\varepsilon}\mbox{-}\kern-.125em\TeX%
63 \fi%
64 }
65 \let\goodeTeX=\eTeX
66 \makeatother
67
68 \usepackage{mathtools}
69
70 % Abbreviations
71 % Most of these are just typewriter commands with `\allowbreak`s added.
72 \def\lwc/{\textsf{lua-\allowbreak widow-\allowbreak control}}
73 \def\Lwc/{\textsf{lua-\allowbreak widow-\allowbreak control}}
74 \def\estretch/{%
75 \texorpdfstring{\cs{emergency}\-\mbox{\ttfamily stretch}}{\textbackslash{}emergencystretch}%
76 }
77 \def\openalty/{\cs{output}\-\mbox{\ttfamily penalty}}
78 \def\waos/{widows and orphans}
79 \def\wao/{widow and orphan}
80 \def\woo/{widow or orphan}
81 \def\woos/{widow or orphans}
82 \def\latexuse/{%
83 \cs{use\-package\{lua-\allowbreak widow-\allowbreak control\}}
84 }
85 \def\lsness/{\texorpdfstring{%
86 \cs{loose}\-\mbox{\ttfamily ness}}{\textbackslash{}looseness}%
87 }
88 \def\plainop/{Plain~\TeX\slash\OpTeX{}}
89 \newcommand{\LuaMetaTeX}{Lua\-Meta\-\TeX{}}
90 \newcommand{\q}[1]{\texorpdfstring{``#1''}{“#1”}}
91
92 \def\inlineurl[#1]#2{\href{https://#1}{#2}\footnote{\raggedright\tbsurl{#1}}}
93
94 \def\longs/{\char"017F}
95 \def\endofline#1{\unskip\nobreak\hskip\fontdimen2\font plus 1fill\hbox{#1}}
96
97 % Additional macros
98 \def\dots{\ensuremath{\mathellipsis}}
99 \def\ttbs{{\tt\char`\\}}
100
101 \ifdefined\tubsentencespace\else
102 \def\tubsentencespace{\spacefactor=3000{}\space\ignorespaces}
103 \fi
104
105 % Figures
106 \makeatletter
107 \renewcommand*{\fps@figure}{tb}
108 \renewcommand*{\fps@table}{tb}
109 \g@addto@macro\@floatboxreset\centering
110 \makeatother
111
112 % pgfplots
113 \usepackage{pgfplots}
114 \usepackage{pgfplotstable}
115 \usetikzlibrary{patterns}
116
117 \pgfkeys{
118 /pgf/number format/.cd,
119 sci generic={%
120 mantissa sep={\times},
121 exponent={10^{##1}}
122 },
123 1000 sep={\,},
124 }
125
126 \pgfplotsset{
127 compat=1.18,
128 lua backend=true,
129 unbounded coords=discard,
130 filter discard warning=false,
131 }
132
133 \pgfplotstableread{\jobname-plot.dat}{\plotdata}
134
135 % Metadata
136 \title{Automatically removing \waos/ with \lwc/}
137 \author{Max Chernoff}
138 \address{Calgary, Alberta\\Canada}
139
140 % Load last
141 \AddToHookNext{shipout/foreground}{%
142 \put(1in, \dimexpr-2\baselineskip){%
143 \fbox{\parbox[t]{\textwidth}{%
144 This document is a part of the \lwc/ documentation. For the
145 authoritative version of the article, please see
146 \tbsurl{https://tug.org/TUGboat/tb43-1/tb133chernoff-widows.html}.
147 }%
148 }}%
149 \put(\dimexpr1in + 0.4\textwidth, \dimexpr-\paperheight + 4\baselineskip){%
150 \fbox{\parbox[t]{0.6\textwidth}{%
151 Some commands may have changed since publication. Please see the
152 \lwc/ manual for the current syntax. (Links:
153 \href{lua-widow-control.pdf}{local},
154 \href{http://mirrors.ctan.org/macros/luatex/generic/lua-widow-control/lua-widow-control.pdf}{\acro{CTAN}},
155 \href{https://github.com/gucci-on-fleek/lua-widow-control/releases/latest/download/lua-widow-control.pdf}{GitHub}.)
156 }%
157 }}%
158 }
159
160 \usepackage[hidelinks,pdfa]{hyperref}
161
162 \usepackage{hyperxmp}
163 \hypersetup{
164 pdfdisplaydoctitle=true,
165 pdftitle={Automatically removing widows and orphans with lua-widow-control},
166 pdfauthor={Max Chernoff},
167 pdflang={en},
168 pdfcontacturl={https://github.com/gucci-on-fleek/lua-widow-control},
169 pdfcopyright={SPDX-License-Identifier: MPL-2.0+ OR CC-BY-SA-4.0+},
170 pdflicenseurl={https://creativecommons.org/licenses/by-sa/4.0/},
171 pdfdoi={10.47397/tb/43-1/tb133chernoff-widows},
172 pdfpublication={TUGboat},
173 pdfpubtype={journal},
174 pdfvolumenum={43},
175 pdfissuenum={1},
176 pdfpagerange={28-39},
177 pdfdate={2022-05}
178 }
179
180 % TODO: Temporary fix
181 \def\Thanh{H{\`a}n Th\^e\llap{\raise0.5ex\hbox{\'{\relax}}} Th{\`a}nh}
182
183 \begin{document}
184 \maketitle
185
186 \begin{abstract}
187 The \textsf{lua-widow-control} package, for
188 plain~Lua\TeX\slash{}\LuaLaTeX\slash{}\ConTeXt\slash{}\OpTeX{},
189 removes widows and orphans without any user intervention.
190 Using the power of Lua\TeX{}, it does so \emph{without} stretching any glue
191 or shortening any pages or columns. Instead, \textsf{lua-widow-control}
192 automatically lengthens a paragraph on a page or column where a widow or
193 orphan would otherwise occur.
194
195 To use \textsf{lua-widow-control}, all that most users need do is
196 place \verb|\usepackage{lua-widow-control}| in their preamble. No further
197 changes are required.
198 \end{abstract}
199
200 \section{Motivation}
201
202 \TeX{} provides top-notch typesetting: even 40 years after its first
203 release, no other program produces higher quality mathematical
204 typesetting, and its paragraph-breaking algorithm is still
205 state-of-the-art. However, its page breaking is not quite as sophisticated
206 as its paragraph breaking and thus suffers from some minor issues.
207
208 Unmodified \TeX{} has only two familiar ways of dealing with \waos/: it can
209 either shorten a page by one line, or it can stretch vertical
210 whitespace. \TeX{} was designed for mathematical and scientific typesetting,
211 where a typical page has multiple section headings, tables, figures, and
212 equations. For this style of document, \TeX's default behaviour works quite
213 well, since the slight stretching of whitespace between the various document
214 elements is nearly imperceptible; however, for prose or other documents
215 composed almost entirely of paragraphs, there is little vertical whitespace
216 to stretch.
217
218 Since no ready-made and fully-automated solution to remove
219 \waos/ from all types of documents was available, I decided to
220 create \lwc/.
221
222 \section{What are \waos/?}
223
224 \subsection{Widows}
225
226 A \q{widow} occurs when the majority of a paragraph is on one page
227 or column,
228 but the last line is on the following page or column. It not only looks
229 quite odd for a lone line to be at the start of the page, but it makes a
230 paragraph harder to read since the separation of a paragraph and
231 its last line disconnects the two, causing the reader to lose context for
232 the widowed line.
233
234 \subsection{Orphans}
235
236 An \q{orphan} occurs when the first line of a paragraph is at the end
237 of the page or column preceding the remainder of the paragraph. They are not
238 as distracting for the reader, but they are still not ideal.
239 Visually, \waos/ are about equally disruptive; however, orphans tend not to
240 decrease the legibility of a text as much as widows, so many authors choose
241 to ignore them.
242
243 See figure~\ref{tab:widow} for a visual reference.
244
245 \begin{figure}
246 \def\firstpage#1{%
247 \parfillskip=0pt%
248 \spaceskip=0.2em plus 1fill%
249 \hskip 3em%
250 #1%
251 }
252
253 \def\lastpage#1{%
254 \parfillskip=3em%
255 \spaceskip=0.2em plus 1fill%
256 #1%
257 }
258
259 \renewcommand{\arraystretch}{1}
260 \renewcommand{\doublerulesep}{0.5em}
261 \begin{tabularx}{\linewidth}{|X|@{\hskip\doublerulesep}|X|}
262 \multicolumn1c{\bfseries Widow} &
263 \multicolumn1c{\bfseries Orphan}
264 \\ \hhline{-||-}
265 \firstpage{A widow occurs when the last line of a paragraph is
266 placed on a page separate from}
267 & \vskip2.25\baselineskip\relax\firstpage{An orphan is}
268 \\ \hhline{-||-}
269 \lastpage{where it begins.}
270 & \lastpage{when the first line of a paragraph occurs on the
271 page before all of the other lines.} \\ \hhline{-||-}
272 \end{tabularx}
273 \caption{The difference between \waos/. If we imagine that each box is a
274 different page, then this roughly simulates how \waos/ appear.}
275 \label{tab:widow}
276 \end{figure}
277
278 \subsection{Broken hyphens}
279
280 \q{Broken} hyphens occur whenever a page break occurs in a
281 hyphenated word. These are not related to \waos/; however,
282 breaking a word across two pages is at least as disruptive for the reader
283 as \waos/. \TeX{} identifies broken hyphens in the same ways as \waos/, so
284 \lwc/ treats broken hyphens in the same way.
285
286 \section{History and etymology}
287
288 The concept of \waos/ is nearly as old as printing itself. In \cite{old},
289 a printers manual from 1683, we have:
290 \begin{quote}
291 Nor do good \emph{Compo\longs/iters} account it good Workman\longs/hip
292 to begin a \emph{Page} with a \emph{Break-line}, unle\longs/s it be a
293 very \longs/hort \emph{Break}, and cannot be gotten in the foregoing
294 \emph{Page}\,; but if it be a long \emph{Break}, he will let it be the
295 \emph{Direction-line} of the fore-going \emph{Page}, and \emph{Set} his
296 \emph{Direction} at the end of it. \endofline{(p.~226)}
297 \end{quote}
298
299 \subsection{Widows}
300
301 However, the terms \q{widow} and \q{orphan} are much newer. The earliest
302 published source that I could find referencing \q{widows} in typography is
303 \textsl{Webster's New International Dictionary} from~1934. However, no
304 one \Dash not even the editors of the dictionary~\cite{widowhistory} \Dash
305 seems to know how it got there. Even then, the definition is somewhat
306 different than it is now:
307 \begin{quote}
308 widow, n.\ c.\ \emph{Print}\@. A short line or single word carried over from
309 the foot of one column or page to the head of a succeeding column or
310 page. \endofline{\cite{widowhistory}}
311 \end{quote}
312 Contrast this with the modern definition:
313 \begin{quote}
314 \emph{Typography}\@. A short line of text (usually one consisting of one
315 word or part of a word) which falls undesirably at the end of a
316 paragraph, esp.\ one set at the top of a page or column.
317 \endofline{\cite{oed-widow}}
318 \end{quote}
319 which includes a single lone line of any length.
320
321 \subsection{Orphans}
322
323 The term \q{orphan} is even more confusing. Its initial usage seems to have
324 occurred some time after \q{widow}~\cite{widowhistory}, and it is given many
325 contradictory definitions. Most sources define an orphan as a first line at
326 the bottom of the page and a widow as the last line at the
327 top~\cite{elements, widowhistory, widowhistory2, xIsambert:TB31-1-12,
328 texbook, widows-and-orphans, oed-line, oed-widow}; however, some sources
329 define these two terms as \emph{exact opposites} of each other, with a widow
330 as a first line at the bottom of the page and an orphan as the last
331 line!~\cite{backwards1, widowhistory, backwards3, oed-line,
332 backwards2}\tubsentencespace
333 This usage is plain wrong; nevertheless, it is sufficiently common that you
334 need to be careful when you see the terms \q{widow} and \q{orphan}.
335
336 \subsection{Clubs}
337
338 \textsl{The \TeX{}book} never refers to \q{orphans} as such; rather, it
339 refers to them as \q{clubs}. This term is remarkably rare: I could only find
340 a \emph{single} source published before \textsl{The \TeX{}book} \Dash a
341 compilation article about the definition of \q{widow} \Dash that mentions
342 a \q{club line}:
343 \begin{quote}
344 The Dictionary staff informs me that they have no example of the use of
345 the word widow in the typographical sense.~[\dots]
346
347 Mr. Watson of the technical staff says that the Edinburgh printing
348 houses referred to it as a ``clubline''.
349 \endofline{\cite[p.~4]{widowhistory}}
350 \end{quote}\medskip
351 \begin{quote}
352 To my knowledge, a `widow', or `widow-line,' is a short line, forming
353 the end of a paragraph, which is carried over from the foot of a page or
354 column to the top of the succeeding one.~[\dots]
355
356 To my personal knowledge, in typographical parlance in Edinburgh,
357 Scotland, the `widow' is called a `club-line.'
358 \endofline{\cite[p.~23]{widowhistory}}
359 \end{quote}
360
361 Both quotes above are from separate authors, and they each define a \q{club}
362 like we define \q{widow}, not an \q{orphan}. In addition, they both mention
363 that the term is only used in Scotland. Even the extensive
364 \acro{OED}\Dash which lists 17~full definitions and
365 103~subdefinitions for the noun \q{club}\Dash doesn't recognize the
366 phrase.~\cite{oed-club}
367
368 I spent a few hours searching through Google Books and my university library
369 catalogue, but I could not find a single additional source. If anyone has
370 any more information on the definition of a \q{club line} or why Knuth chose
371 to use this archaic Scottish term in \TeX{}, please let me know!
372
373 \section{Pagination in \TeX}
374
375 Let's move on to looking at how \TeX{} treats these \waos/.
376
377 \subsection{Algorithm}
378
379 It is tricky to understand how \lwc/ works if you aren't familiar with how
380 \TeX{} breaks pages and columns. For a full description, you should
381 consult Chapter~15 of \textit{\TB}~\cite{texbook} (\q{How \TeX{} Makes Lines
382 into Pages}); however, this goes into much more detail than most users
383 require, so here is a \emph{very} simplified summary of \TeX{}'s page
384 breaking algorithm:
385
386 \TeX{} fills the page with lines and other objects until the next object
387 will no longer fit. Once no more objects will fit, \TeX{} will align the
388 bottom of the last line with the bottom of the page by stretching any
389 available vertical spaces if (in \LaTeX) \cs{flushbottom} is set;
390 otherwise, it will
391 break the page and leave the bottom empty.
392
393 However, some objects have penalties attached. Penalties encourage or
394 discourage page breaks from occurring at specific places. For example,
395 \LaTeX{} sets a negative penalty before section headings to encourage a
396 page break there; conversely, it sets a positive penalty after section
397 headings to discourage breaking.
398
399 To reduce \waos/, \TeX{} sets weakly\hyph positive penalties between the
400 first and second lines of a paragraph to prevent orphans, and between the
401 penultimate and final lines to prevent widows.
402
403 One important note: once \TeX{} begins breaking a page, it never goes
404 back to modify any content on the page. Page breaking is a localized
405 algorithm, without any backtracking.
406
407 \subsection{Behaviour}
408
409 Merely describing the algorithm doesn't allow us to intuitively
410 understand how
411 \TeX{} deals with \waos/.
412
413 Due to the penalties attached to \waos/, \TeX{} tries to avoid
414 them. Widows and orphans with small penalties attached \Dash like
415 \LaTeX's default values of 150 \Dash are only lightly coupled to the rest
416 of the paragraph, while \waos/ with large penalties \Dash values of
417 10\,000 or more \Dash are treated as infinitely bad and are thus
418 unbreakable. Intermediate values behave just as you would expect,
419 discouraging page breaks proportional to their value.
420
421 When \TeX{} goes to break a page, it tries to avoid breaking at a
422 location with a high penalty. How it does so depends on a few settings:
423
424 \subsubsection{\cs{flushbottom} and \cs{normalbottom}}
425
426 With the settings \cs{normalbottom} (Plain \TeX{}) or
427 \cs{flushbottom} (\LaTeX{}), \TeX{} is willing to stretch any glue on the
428 page by an amount roughly commensurate to the magnitude of the
429 penalty: for small \cs{clubpenalty} and \cs{widowpenalty} values, \TeX{} will
430 only slightly stretch the glue on the page before creating a \woo/;
431 for very large penalties, \TeX{} will stretch the glue by a
432 near-infinite amount.
433
434 This corresponds to the \q{Stretch} column in
435 Figure~\ref{fig:demo}. It is
436 the default behaviour of Plain~\TeX{}, and of the standard \LaTeX{} classes
437 when the \verb|twocolumn| option is given.
438
439 \subsubsection{\cs{raggedbottom}}
440
441 When \cs{raggedbottom} is set, \TeX{} won't stretch any glue. Instead,
442 for sufficiently-high \cs{clubpenalty} and \cs{widowpenalty} values, \TeX{} will
443 shorten the page or column by one~line in order to prevent the \woo/ from
444 being created.
445
446 This corresponds to the \q{Shorten} column in Figure~\ref{fig:demo} and is
447 the default behaviour of the \LaTeX{} classes when the
448 \verb|twocolumn| option is not given.
449
450 \section{\lsness/}\label{sec:looseness}
451 Before we can continue further, we need to discuss one more \TeX{}
452 command: \lsness/. The following is excerpted from Chapter~14 of
453 \cite{texbook} (\q{How \TeX{} Breaks Paragraphs into Lines}):
454
455 \begin{quote}\parskip=0pt
456 If you set \lsness/\verb|=1|, \TeX{} will try to make the current
457 paragraph one line longer than its optimum length, provided that
458 there is a way to choose such breakpoints without exceeding the
459 tolerance you have specified for the badnesses of individual lines.
460 Similarly, if you set \lsness/\verb|=2|, \TeX{} will try to make the
461 paragraph two lines longer; and \lsness/\verb|=-1| causes an attempt
462 to make it shorter.~[\dots]
463
464 For example, you can set \lsness/\verb|=1| if you want to avoid a
465 lonely \q{club line} or \q{widow line} on some page that does not
466 have sufficiently flexible glue, or if you want the total number of
467 lines in some two-column document to come out to be an even number.
468
469 It's usually best to choose a paragraph that is already pretty
470 \q{full}, i.e., one whose last line doesn't have much white space,
471 since such paragraphs can generally be loosened without much harm.
472 You might also want to insert a tie between the last two words of
473 that paragraph, so that the loosened version will not end with only
474 one \q{widow word} on the orphans line; this tie will cover your
475 tracks, so that people will find it hard to detect the fact that you
476 have tampered with the spacing. On the other hand, \TeX{} can take
477 almost any sufficiently long paragraph and stretch it a bit, without
478 substantial harm.
479 \end{quote}
480
481 The \wao/ removal strategy suggested in the second paragraph works quite
482 well; however, it requires manual editing each and every time a page
483 or paragraph is rewritten or repositioned.
484
485 \begin{figure*}[p]
486 % Note: this figure may appear incorrect on some systems.
487 \divide\abovecaptionskip by 2
488 \includegraphics{\jobname-figure}
489 \caption{A visual comparison of various automated widow-handling
490 techniques.
491 }\label{fig:demo}
492 \end{figure*}
493
494 \section{Alternate removal strategies}
495
496 \looseness=1 There have been a few previous attempts to improve upon \TeX's
497 previously-discussed \wao/-handling abilities; however, none of these
498 have been able to automatically remove \waos/ without stretching any glue
499 or shortening any pages.
500
501 The articles \q{Strategies against
502 widows} by Paul Isambert~\cite{xIsambert:TB31-1-12} and
503 \q{Managing forlorn paragraph lines} by Frank
504 Mittelbach~\cite{Mittelbach:2018:MFP} both
505 begin with comprehensive discussions of the methods of preventing \waos/.
506 They agree that \waos/ are bad and ought to be avoided; however, they
507 differ in their solutions. \textsl{Strategies}~proposes an output routine
508 that reduces the length of facing pages by one line when necessary to
509 remove \waos/, while \textsl{Managing}~proposes that the author manually
510 rewrites or adjusts \lsness/ when needed.
511
512 \looseness=1 The post \q{Paragraph callback \dots} by
513 jeremie~\cite{widow-assist} contains a file
514 \verb|widow-assist.lua| that
515 automatically detects which paragraphs can be safely shortened or
516 lengthened by one line. Mittelbach's \textsf{widows-and-orphans}
517 package~\cite{widows-and-orphans} alerts the author to
518 the pages that contain widows or orphans. Combined, these packages make
519 it simple for the author to quickly remove \waos/ by adjusting the
520 values of \lsness/; however, it still requires the author to make manual
521 source changes after each revision.
522
523 Another article by Mittelbach~\cite{global} suggests an fully-automated
524 solution to remove \waos/. This would seem to offer a complete solution;
525 however, it requires multiple passes, an external tool, and has not yet been
526 publicly released.
527
528 \pagebreak
529
530 \Lwc/ is essentially a combination of
531 \verb|widow-assist.lua|~\cite{widow-assist} and
532 \textsf{widows-and-orphans}~\cite{widows-and-orphans} (although its
533 implementation is independent of both): when the \openalty/
534 value indicates
535 that a \woo/ has occurred, Lua is used to find a stretchable paragraph. What
536 \lwc/ mainly adds on top of these packages is automation: it eliminates the
537 requirement for any manual adjustments or changes to your document's
538 source.
539
540 \section{Visual comparison}
541
542 Although \TeX{}'s page breaking algorithm is reasonably
543 straightforward, it can lead to
544 complex behaviour when \waos/ are involved. The usual
545 choices, when rewriting is not possible, are to ignore them,
546 stretch some glue, or shorten the
547 page. Figure~\ref{fig:demo} has a visual comparison of these
548 options, which we'll discuss in the following:
549
550 \subsection{\q{Ignore}}
551
552 As you can see, the last line of the page is on a separate page from the
553 rest of its paragraph, creating a widow. This is usually highly
554 distracting for the reader, so it is best avoided for the reasons previously
555 discussed.
556
557 \subsection{\q{Shorten}}
558
559 This page did not leave any widows, but it did shorten the previous page
560 by one line. Sometimes this is acceptable, but usually it looks bad because
561 pages will then have different text-block heights. This can make the pages
562 look quite uneven, especially when typesetting with columns or in a book
563 with facing pages.
564
565 \subsection{\q{Stretch}}
566
567 This page also has no widows and it has a flush bottom margin. However,
568 the space between each pair of paragraphs had to be stretched.
569
570 If this page had many equations, headings, and other elements with
571 natural space between them, the stretched out space would be much less
572 noticeable. \TeX{} was designed for mathematical typesetting, so it makes
573 sense that this is its default behaviour. However, in a page with mostly
574 text, these paragraph gaps look unsightly.
575
576 Also, this method is incompatible with grid typesetting, where
577 all glue stretching must be quantised to the height of a line.
578
579 \subsection{\q{\lwc/}}
580
581 \Lwc/ has none of these issues: it eliminates the widows in a document
582 while keeping a flush bottom margin and constant paragraph spacing.
583
584 To do so, \lwc/ lengthened the second paragraph by one line. If you look
585 closely, you can see that this stretched the interword spaces. This
586 stretching is noticeable when typesetting in a narrow text block, but
587 is mostly imperceptible with larger widths.
588
589 \Lwc/ automatically finds the \q{best} paragraph to stretch, so the
590 increase in interword spaces should almost always be minimal.
591
592 \section{Installation and standard usage}
593
594 The \lwc/ package was first released in
595 October~2021. It is available in the default installations of both
596 MiK\TeX{} and \TeX{}~Live, although you will need recent versions
597 of either.
598
599 You may also download \lwc/ manually from either
600 \inlineurl[ctan.org/pkg/lua-widow-control]{\acro{CTAN},}
601 the \inlineurl%
602 [modules.contextgarden.net/cgi-bin/module.cgi/action=view/id=127]%
603 {\ConTeXt{} Garden,} or \inlineurl%
604 [github.com/gucci-on-fleek/lua-widow-control/releases/latest/]%
605 {GitHub,} although it is best if you can install it through your
606 \TeX~distribution.
607
608 As its name may suggest, \lwc/ \textit{requires} \LuaTeX{}\footnote{Or
609 \LuaMetaTeX{} in the case of \ConTeXt{}.} regardless of the format used.
610 With that in mind, using \lwc/ is quite simple:
611
612 \begin{tabularx}{\linewidth}{@{}l@{}>{\raggedleft\arraybackslash}X@{}}
613 Plain \TeX{} &
614 \cs{input lua-widow-control}\phantom{\tt]} \\
615 \OpTeX {} &
616 \cs{load[lua-widow-control]} \\
617 \LaTeX{} &
618 \latexuse/ \\
619 \ConTeXt{} &
620 \cs{usemodule[lua-widow-control]} \\
621 \end{tabularx}
622
623 And that's usually enough. Most users won't need to do anything else since
624 \lwc/ comes preconfigured and ready-to-go.
625
626 \section{Options}
627
628 Nevertheless, \lwc/ does have a few options.
629
630 \Lwc/ tries very hard to have a \q{natural} user interface with each
631 format, so how you set an option heavily depends on how you are running
632 \lwc/. Also note that not every option is available in every format.
633
634 Some general guidelines:
635 \begin{description}
636 \item[\rm \plainop/\ ] Some options are set
637 by modifying a register, while others must be set manually using
638 \cs{directlua}.
639
640 \item[\rm \LaTeX{}\ ] Options can be set either as package options
641 or at any point in the document with \cs{lwcsetup}.
642
643 \item[\rm \ConTeXt{}\ ] Always use \cs{setuplwc}.
644 \end{description}
645
646 \subsection{Disabling}
647
648 You may want to disable \lwc/ for certain portions of your
649 document. You can do so with the following commands:
650
651 \begin{tabularx}{\linewidth}{@{}Xl@{}}
652 \plainop/ &
653 \cs{lwcdisable} \\
654 \LaTeX{} &
655 \cs{lwcsetup\{disable\}} \\
656 \ConTeXt{} &
657 \cs{setuplwc[state=stop]}\hphantom{\texttt{a}} \\
658 \end{tabularx}
659
660 This prevents \lwc/ from stretching any paragraphs that follow. If a page
661 has earlier paragraphs where \lwc/ was still enabled and a \woo/ is
662 detected, \lwc/ will still attempt to remove the \woo/.
663
664 \subsection{Enabling}
665
666 \Lwc/ is enabled as soon as the package is loaded. If you
667 have previously disabled it, you will need to re-enable it to save new paragraphs.
668
669 \begin{tabularx}{\linewidth}{@{}Xl@{}}
670 \plainop/ &
671 \cs{lwcenable} \\
672 \LaTeX{} &
673 \cs{lwcsetup\{enable\}} \\
674 \ConTeXt{} &
675 \cs{setuplwc[state=start]} \\
676 \end{tabularx}
677
678 \subsection{Automatically disabling}
679
680 You may want to disable \lwc/ for certain commands where
681 stretching is undesirable such as section headings. Of course, manually
682 disabling and
683 then enabling \lwc/ multiple times
684 throughout a document would quickly become tedious, so \lwc/ provides
685 some options to do this automatically for you.
686
687 \Lwc/ automatically patches the default \LaTeX{}, \ConTeXt{},
688 Plain~\TeX{}, \OpTeX{}, \textsf{\mbox{memoir}}, \KOMAScript, and
689 \textsf{titlesec} section commands, so you don't need to patch these.
690 Any others, though, you'll need to patch yourself.
691
692 \begin{tabularx}{\linewidth}{@{}Xl@{}}
693 \leavevmode\rlap{\plainop/} & \texttt{ }%
694 \cs{lwcdisablecmd\{\meta{\ttbs macro}\}} \\
695 \LaTeX{} & \texttt{ }%
696 \cs{lwcsetup\{disablecmds=\{} \\
697 & \hfill\texttt{\meta{csnameone},
698 \meta{csnametwo}\}\}} \\
699 \ConTeXt{} &
700 \cs{prependtoks\textbackslash{}lwc@patch@pre} \\
701 & \hfill\cs{to\textbackslash{}everybefore\meta{hook}} \\
702 & \cs{prependtoks\textbackslash{}lwc@patch@post} \\
703 & \hfill\cs{to\textbackslash{}everyafter\meta{hook}} \\
704 \end{tabularx}
705
706 \subsection{\estretch/}
707
708 \Lwc/ defaults to an \estretch/ value of 3~em for stretched paragraphs,
709 but you can configure this.
710
711 \Lwc/ will only use the \estretch/ when it cannot lengthen a paragraph
712 in any other way, so it is fairly safe to set this to a large value.
713 \TeX{} accumulates badness when \estretch/ is
714 used~\cite{Knuth:TB10-3-325}, so it's pretty rare that a paragraph that
715 requires any \estretch/ will actually be used on the page.
716
717 \begin{tabularx}{\linewidth}{@{}Xl@{}}
718 \leavevmode\rlap{\plainop/} &
719 \hskip2em\cs{lwcemergencystretch=} \\
720 & \hfill\texttt{\meta{dimension}} \\
721 \LaTeX{} &
722 \cs{lwcsetup\{emergencystretch=\hphantom{\}}}\\
723 & \hfill\texttt{\meta{dimension}\}} \\
724 \ConTeXt{} &
725 \cs{setuplwc[emergencystretch=\hphantom{]}} \\
726 & \hfill\texttt{\meta{dimension}]} \\
727 \end{tabularx}
728
729 \subsection{Penalties}
730
731 You can also manually adjust the penalties that \TeX{} assigns to \waos/.
732 Usually, the defaults are fine, but there are a few circumstances where you
733 may want to change them.
734
735 \begin{tabular}{@{}p{.175\linewidth}@{}r@{\texttt{=\meta{integer}}}l@{}}
736 \leavevmode\rlap{\plainop/} &
737 \hskip6em\cs{widowpenalty} \\
738 & \hskip6em\cs{clubpenalty} \\
739 & \hskip6em\cs{brokenpenalty} \\
740 \LaTeX{} &
741 \cs{lwcsetup\{ widowpenalty} & \texttt{\}} \\
742 & \cs{lwcsetup\{orphanpenalty} & \texttt{\}} \\
743 & \cs{lwcsetup\{brokenpenalty} & \texttt{\}} \\
744 \leavevmode\hbox{\ConTeXt{}} &
745 \cs{setuplwc[ widowpenalty} & \texttt{]} \\
746 & \cs{setuplwc[orphanpenalty} & \texttt{]} \\
747 & \cs{setuplwc[brokenpenalty} & \texttt{]} \\
748 \end{tabular}
749
750 The value of these penalties determines how much \TeX{} should attempt
751 to stretch glue before passing the \woo/ to \lwc/. If you set the values to~1
752 (default), \TeX{} will stretch nothing and immediately trigger \lwc/;
753 if you set the values to 10\,000, \TeX{} will stretch infinitely and
754 \lwc/ will never be triggered. If you set the value to some intermediate
755 number, \TeX{} will first attempt to stretch some glue to remove the \woo/;
756 only if it fails will \lwc/ come in and lengthen a paragraph. As a special
757 case, if you set the values to~0, both \TeX{} and \lwc/ will completely
758 ignore the \woo/.
759
760 \subsection{\cs{nobreak} behaviour}
761
762 When \lwc/ encounters an orphan, it removes it by moving the orphaned
763 line to the next page. The majority of the time, this is an appropriate
764 solution. However, if the orphan is immediately preceded by a section
765 heading (or \cs{nobreak}\slash\cs{penalty 10000}), \lwc/ would na\"ively separate a section heading from
766 the paragraph that follows. This is almost always undesirable, so \lwc/
767 provides some options to configure this.
768
769 \begin{tabularx}{\linewidth}{@{}Xr@{}}
770 \leavevmode\rlap{\plainop/} &
771 \cs{directlua\{lwc.}\hskip4em\null \\
772 & \hfill\texttt{nobreak\_behaviour="\meta{value}"\}} \\
773 \LaTeX{} &
774 \cs{lwcsetup\{nobreak=\meta{value}\}\hphantom{"}} \\
775 \ConTeXt{} &
776 \cs{setuplwc[nobreak=\meta{value}]\hphantom{"}} \\
777 \end{tabularx}
778
779 The default value, \texttt{keep}, \emph{keep}s the section heading with
780 the orphan by moving both to the next page. The advantage to this option
781 is that it removes the orphan and retains any \cs{nobreak}s; the
782 disadvantage is that moving the section heading can create a large blank
783 space at the end of the page.
784
785 The value \texttt{split} \emph{split}s up the section heading and the
786 orphan by moving the orphan to the next page while leaving the heading
787 behind. This is usually a bad idea, but exists for the sake of
788 flexibility.
789
790 The value \texttt{warn} causes \lwc/ to give up on the page and do nothing,
791 leaving an orphaned line. \Lwc/ \emph{warn}s the user so that they can
792 manually remove the orphan.
793
794 See figure~\ref{tab:nobreak} for a visual reference.
795
796 \begin{figure}
797 \renewcommand{\arraystretch}{1}
798 \renewcommand{\doublerulesep}{0.5em}
799 \begin{tabularx}{\linewidth}{%
800 |X|@{\hskip\doublerulesep}|X|@{\hskip\doublerulesep}|X|%
801 }
802 \multicolumn1c{\ttfamily keep} &
803 \multicolumn1c{\ttfamily split} &
804 \multicolumn1c{\ttfamily warn}
805 \\ \hhline{-||-||-}
806 &
807 &
808 \textbf{Heading} \\
809 &
810 \textbf{Heading} &
811 The\hfill first\hfill line
812 \\ \hhline{-||-||-}
813 \textbf{Heading} &
814 The\hfill first\hfill line &
815 text\hfill text\hfill text \\
816 The\hfill first\hfill line &
817 text\hfill text\hfill text &
818 last line. \\
819 text\hfill text\hfill text &
820 last line. &
821 % Nothing
822 \\ \hhline{-||-||-}
823 \end{tabularx}
824 \caption{A visual comparison of the \texttt{nobreak} option values.}
825 \label{tab:nobreak}
826 \end{figure}
827
828 \subsection{Maximum cost}
829
830 \Lwc/ ranks each paragraph on the page by how much it would \q{cost} to
831 lengthen that paragraph. By default, \lwc/ selects the paragraph on
832 the page with the lowest cost; however, you can configure it to only
833 select paragraphs below a selected cost.
834
835 If there aren't any paragraphs below the set threshold, then \lwc/ won't
836 remove the \woo/ and will instead issue a warning.
837
838 \begin{tabularx}{\linewidth}{@{}Xr@{\texttt{=\meta{integer}}}l@{}}
839 \leavevmode\rlap{\plainop/} &
840 \cs{lwcmaxcost} \\
841 \LaTeX{} &
842 \cs{lwcsetup\{max-cost} & \texttt{\}} \\
843 \leavevmode\hbox{\ConTeXt{}} &
844 \cs{setuplwc[maxcost} & \texttt{]} \\
845 \end{tabularx}
846
847 Based on my testing, \texttt{max-cost} values less than 1\,000
848 cause completely imperceptible changes in interword spacing; values less
849 than 5\,000 are only noticeable if you are specifically trying to pick out the
850 expanded paragraph on the page; values less than 15\,000 are typically
851 acceptable; and larger values may become distracting. \Lwc/ defaults to an
852 infinite \texttt{max-cost}, although the \q{strict} and \q{balanced} modes
853 sets the values to~5\,000 and 10\,000 respectively.
854
855 \section{Presets}
856
857 As you can see, \lwc/ provides quite a few options. Luckily, there are a few
858 presets that you can use to set multiple options at once. These presets are
859 a good starting point for most documents, and you can always manually
860 override individual options.
861
862 Currently, these presets are \LaTeX{}-only.
863
864 \begin{tabular}{@{}rl@{}}
865 \LaTeX{} &
866 \cs{lwcsetup\{\meta{preset}\}} \\
867 \end{tabular}
868
869 \subsection{\texttt{default}}
870
871 If you use \lwc/ without any options, it defaults to this preset. In default
872 mode, \lwc/ takes all possible measures to remove \waos/ and will not
873 attempt to stretch any vertical glue. This usually
874 removes~$\mathord{>}\,95\%$ of all
875 possible \waos/. The catch here is that this mode is quite aggressive, so
876 it often leaves behind some fairly \q{spacey} paragraphs.
877
878 This mode is good if you want to remove (nearly) all \waos/ from your
879 document, without fine-tuning the results.
880
881 \subsection{\texttt{strict}}
882
883 \Lwc/ also offers a strict mode. This greatly restricts \lwc/'s tolerance
884 and makes it so that it will only lengthen paragraphs where the change will
885 be imperceptible.
886
887 The caveat with strict mode is that\Dash depending on the document\Dash
888 \lwc/ will be able to remove less than a third of the \waos/.
889 For the \waos/ that can't be automatically removed, a warning will be
890 printed to your terminal and log file so that a human can manually fix the
891 situation.
892
893 This mode is good if you want the best possible typesetting and are willing
894 to do some manual editing.
895
896 \subsection{\texttt{balanced}}
897
898 Balanced mode sits somewhere between default mode and strict mode. This mode
899 first lets \TeX{} stretch a little glue to remove the \woo/; only if that
900 fails will it then trigger \lwc/. Even then, the maximum paragraph cost is
901 capped. Here, \lwc/ can usually remove 90\% of a document's
902 potential \waos/, and it does so while making a minimal visual impact.
903
904 This mode is recommended for most users who care about their document's
905 typography. This mode is not the default since it doesn't remove all
906 \waos/: it
907 still requires a little manual intervention.
908
909 \begin{table}
910 \caption{\Lwc/ options set by each mode.}\label{tab:modes}
911 \ttfamily\setlength{\tabcolsep}{4pt}
912 \begin{tabular}{l*3r}\toprule
913 \textrm{Option} & default & balanced & strict \\ \midrule
914 max-cost & $\infty$ & 10000 & 5000 \\
915 \rlap{emergencystretch} & 3em & 1em & 0pt \\
916 nobreak & keep & keep & warn \\
917 widowpenalty & 1 & 500 & 1 \\
918 orphanpenalty & 1 & 500 & 1 \\
919 brokenpenalty & 1 & 500 & 1 \\
920 \bottomrule\end{tabular}
921 \end{table}
922
923 \section{Compatibility}
924
925 The \lwc/ implementation is almost entirely in Lua, with only a minimal
926 \TeX{} footprint. It
927 doesn't modify the output routine, inserts\slash floats, \cs{everypar}, and
928 it doesn't insert any whatsits. This means that it should be compatible with
929 nearly any \TeX{} package, class, and format. Most changes that \lwc/ makes
930 are not observable on the \TeX{} side.
931
932 However, on the Lua side, \lwc/ modifies much of a page's internal
933 structure.
934 This should not affect any \TeX{} code; however, it may surprise
935 Lua code that modifies or depends on the page's low-level structure. This
936 does not matter for Plain~\TeX{} or \LaTeX{}, where even most Lua-based
937 packages don't depend on the node list structure; nevertheless, there are
938 a few issues with \ConTeXt{}.
939
940 Simple \ConTeXt{} documents tend to be fine, but many advanced
941 \ConTeXt{} features rely heavily on Lua and can thus be disturbed by
942 \lwc/. This is not a huge issue\Dash the \lwc/ manual is
943 written in \ConTeXt{}\Dash but \lwc/ is inevitably more reliable
944 with Plain \TeX{} and \LaTeX{} than with \ConTeXt{}.
945
946 Finally, keep in mind that adding \lwc/ to a document will almost certainly
947 change its page break locations.
948
949 \subsection{Formats}
950
951 \Lwc/ runs on all known \LuaTeX{}-based formats: Plain~\LuaTeX{},
952 \LuaLaTeX{}, \CMkIV{}, \ConTeXt{} Mk\acro{XL}\slash\acro{LMTX},
953 and~\OpTeX{}. Unless otherwise documented, all features should work
954 equally well in all formats.
955
956 \subsection{Columns}
957
958 Since \TeX{} and the formats implement column breaking and page
959 breaking through the
960 same internal mechanisms, \lwc/ removes \waos/ between columns just
961 as it does with \waos/ between pages.
962
963 \Lwc/ is known to work with the \LaTeX{} class option \verb|twocolumn|
964 and the two-column output routine from Chapter~23 of \cite{texbook}.
965
966 \subsection{Performance}
967
968 \Lwc/ runs entirely in a single pass, without depending on any
969 \verb|.aux| files or the like. Thus, it shouldn't meaningfully
970 increase compile times. Although \lwc/ internally breaks each paragraph
971 twice, modern computers break paragraphs near-instantaneously, so you
972 are not likely to notice any slowdown.
973
974 \subsection{\eTeX{} penalties}
975
976 Knuth's original \TeX{} has three basic line penalties:
977 \cs{interlinepenalty}, which
978 is inserted between all lines; \cs{club\-penalty}, which is inserted after
979 the first line; and \cs{widow\-penalty}, which is inserted before the last
980 line. The \eTeX{} extensions~\cite{etex} generalize these commands with a
981 syntax similar to \cs{parshape}: with \cs{widow\-penalties} you can set the
982 penalty between the last, second last, and $n$th last lines of a paragraph;
983 \cs{inter\-line\-penalties} and \cs{club\-penalties} behave similarly.
984
985 \Lwc/ makes no explicit attempts to support these new -\texttt{penalties}
986 commands. Specifically, if you give a line a penalty that matches either
987 \cs{widowpenalty} or \cs{clubpenalty}, \lwc/ will treat the lines
988 exactly as it would a \woo/. So while these commands won't break \lwc/, they
989 are likely to lead to some unexpected behaviour.
990
991 \section{Short last lines}
992
993 \looseness=1
994 When lengthening a paragraph with \lsness/, it is common advice to insert
995 ties (\verb|~|) between the last few words of the paragraph to avoid
996 overly-short last lines \cite{texbook}. \Lwc/ does this automatically,
997 but instead of using ties or \cs{hbox}es, it uses the
998 \cs{par\allowbreak fill\allowbreak skip}
999 parameter~\cite{texbook, Wermuth:2018:ECP}. When lengthening a paragraph
1000 (and only when lengthening a paragraph\Dash remember, \lwc/ doesn't
1001 interfere with \TeX{}'s output unless it detects a \woo/), \lwc/ sets
1002 \cs{parfillskip} to \verb|0pt plus 0.8\hsize|.
1003 This normally makes the last line of a paragraph be at least
1004 20\% of the overall paragraph's width, thus preventing
1005 ultra-short~lines.
1006
1007 \section{How it works}
1008
1009 \Lwc/ uses a fairly simple algorithm to eliminate \waos/, but there
1010 are a few subtleties.
1011
1012 \subsection{Setup}
1013
1014 \Lwc/ sets the parameters \cs{clubpenalty}, \cs{widowpenalty}, and
1015 \cs{brokenpenalty} to sentinel values of~1. This will signal to \lwc/ when
1016 a \woo/ occurs, yet it is small enough that it won't stretch any glue.
1017
1018 \Lwc/ also enables \LuaTeX{}'s micro\-typographic
1019 extensions~\cite{xThanh:2000:MTE}. This isn't strictly necessary;
1020 however, it significantly increases the number of paragraphs that can
1021 be acceptably \q{loosened}.
1022
1023 That is all that happens on the \TeX{} end. The rest of \lwc/ is pure Lua.
1024
1025 \subsection{Paragraph breaking}
1026
1027 First, \lwc/ hooks into the paragraph breaking process, before any output
1028 routines or page breaking.
1029
1030 Before a paragraph is broken by \TeX{}, \lwc/ grabs the unbroken
1031 paragraph. Then \lwc/ breaks the paragraph one line longer than its natural
1032 length and stores it for later. It does this in the background,
1033 \emph{without} interfering with how \TeX{} breaks paragraphs into their
1034 natural length.
1035
1036 After \TeX{} has broken its paragraph into its natural length, \lwc/
1037 appears again. Before the broken paragraph is added to the main
1038 vertical list, \lwc/ \q{tags} the first and last nodes of the paragraph
1039 using a \LuaTeX{} attribute. These attributes associate the
1040 previously-saved lengthened paragraph with the naturally-typeset
1041 paragraph on the page.
1042
1043 \subsection{Page breaking}
1044
1045 \Lwc/ intercepts \cs{box255} (the \cs{vbox} output by \TeX) immediately
1046 before the output routine runs,
1047 after all the paragraphs have been typeset.
1048
1049 First, \lwc/ looks at the \openalty/ of the page or column. If the page
1050 was broken at a \woo/, the \openalty/ will be equal to either
1051 the \cs{widowpenalty} or the \cs{clubpenalty}. If the \openalty/ does not
1052 indicate a \woo/, \lwc/ will stop and return \cs{box255} unmodified to
1053 the output~routine, and \TeX{} continues as normal.
1054
1055 Otherwise, we assume that we have a \woo/ on the page,
1056 meaning that we should lengthen the page by 1~line. We iterate through
1057 the list of saved paragraphs to find the lengthened paragraph with the
1058 least cost. After we've selected a good paragraph, we traverse
1059 through the page to find the original version of this paragraph\Dash the
1060 one that unmodified \TeX{} originally typeset. Having found the original
1061 paragraph, we splice in the lengthened paragraph in place of the original.
1062
1063 Since the page is now 1~line longer than it was before, we pull the last
1064 line off the page to bring it back to its original length, and place
1065 that line onto the top of \TeX's \q{recent contributions} list. When
1066 the next page begins, this line will be inserted before all other
1067 paragraphs, right at the top. Now, we can return the new, widow-free page
1068 (updated \cs{box255}) to the output routine, which proceeds
1069 as normal.
1070
1071 \section{Choosing the \q{best} paragraph}
1072
1073 As we discussed previously, \lwc/ lengthens the paragraph with the lowest
1074 cost. However, assigning a cost to each paragraph is not quite as simple as
1075 it sounds. Before we look at how \lwc/ assigns costs, let's look at how
1076 \TeX{} scores paragraphs when breaking them naturally.
1077
1078 \subsection{How \TeX{} scores paragraphs}
1079
1080 All glue in \TeX{} has a certain natural size: the size that it would be
1081 in an ideal scenario. However, most glue also has stretch and shrink
1082 components so that the glue can change in size to adapt to its
1083 surroundings. For each line, \TeX{} individually sums the total
1084 stretch/shrink for the line and the stretch/shrink that was actually used.
1085 We define the stretch/shrink ratio~$r$ as the quotient of the
1086 stretch/shrink used and the stretch/shrink available. Then the badness~$b$
1087 of a line is approximately defined as
1088 \begin{equation*}
1089 b = 100r^3.
1090 \end{equation*}
1091 This is the badness referenced in the commonly-seen
1092 \texttt{Underfull \cs{hbox}
1093 (badness 1234)} warnings that \TeX{} produces.
1094
1095 \TeX{} calculates the badness for each line individually; however, we also
1096 need to assess the paragraph as a whole. To do so, \TeX{} defines the
1097 demerits for a whole paragraph~$d$ as approximately\footnotemark{} the sum of
1098 the squared badnesses for each line. The natural paragraph that \TeX{}
1099 breaks is the one that minimizes~$d$.
1100
1101 \footnotetext{We ignore any additional demerits or penalties that
1102 \TeX{} may add.}
1103
1104 One important thing to realize is that demerits grow incredibly fast:
1105 demerits are proportional to the \emph{sixth} power of glue stretch. This
1106 means that you can expect to see extremely large demerit values, even for
1107 a relatively \q{good} paragraph.
1108
1109 \subsection{Possible cost functions}
1110
1111 Now, let's return to how \lwc/ assigns costs to each paragraph. This is
1112 surprisingly more complicated than it sounds, so we'll go through a few
1113 possible cost functions first.
1114
1115 Here, we use $c$~for the cost of a paragraph, $d$~for the total demerits,
1116 and $l$~for the number of lines (\cs{prevgraf}).
1117
1118 \subsubsection{The original implementation}
1119
1120 The original implementation of \lwc/ used the very simple cost function
1121 \begin{equation*}
1122 c = d.
1123 \end{equation*}
1124 This cost function works reasonably well, but has one major issue: it doesn't
1125 take into account the number of lines in the paragraph. The demerits for a
1126 paragraph is the sum of the demerits for each line. This means this cost
1127 function will prefer using shorter paragraphs since they tend to have fewer
1128 demerits. However, long paragraphs tend to have much more available glue
1129 stretch, so this strategy can lead to suboptimal solutions.
1130
1131 \subsubsection{Scaling by the number of lines}
1132
1133 Once I realized this issue, I tried correcting it by dividing by the number
1134 of lines in the paragraph to get the average demerits instead of the total
1135 demerits:
1136 \begin{equation*}
1137 c = \frac{d}{l}
1138 \end{equation*}
1139 This works better than the previous function, but still has an issue.
1140 If we have a fairly bad ten-line paragraph with total demerits $10d$ and an
1141 almost-equally bad two-line paragraph with total demerits $2d + 1$, then by
1142 this cost function, the ten-line paragraph will have a lower cost and will
1143 be chosen. This means that our page now has ten bad lines instead of two bad
1144 lines, which is not ideal.
1145
1146 \subsubsection{Current implementation}
1147
1148 Our first cost function, $c=dl^0$, doesn't consider the number of lines at
1149 all, while our second cost function, $c=dl^{-1}$, considers the number of
1150 lines too much. Splitting the difference between the two functions, we get
1151 the current implementation:
1152 \begin{equation*}
1153 c = \frac{d}{\sqrt{l}}
1154 \end{equation*}
1155
1156 I didn't arrive at this function through any sort of scientific testing;
1157 rather, I picked the simplest function that I could think of that satisfies
1158 the following two properties:
1159 \begin{itemize}
1160 \item Given a long paragraph and a short paragraph with different
1161 average badnesses per line, prefer the one with the least average
1162 badness.
1163 \item Given two paragraphs with equal average badnesses per line,
1164 prefer the shorter one.
1165 \end{itemize}
1166
1167 \section{Quantitative analysis}
1168
1169 \begin{figure}
1170 \begin{tikzpicture}\begin{axis}[
1171 ybar interval,
1172 xticklabels={1, ..., 15,
1173 {$\,\ge\! 16$}},
1174 x tick label style={font=\small},
1175 y tick label style={font=\small},
1176 enlarge y limits=upper,
1177 enlarge x limits={abs=1},
1178 grid=none,
1179 scaled y ticks=base 10:-3,
1180 ytick scale label code/.code={},
1181 xlabel={Paragraph length (lines)},
1182 ylabel={Count (thousands)}
1183 ]
1184 \addplot+ [
1185 draw=black,
1186 fill=black!10,
1187 semithick,
1188 ] table {
1189 Length Count
1190 1 4429
1191 2 3704
1192 3 2045
1193 4 1320
1194 5 894
1195 6 717
1196 7 498
1197 8 406
1198 9 379
1199 10 251
1200 11 175
1201 12 152
1202 13 111
1203 14 95
1204 15 79
1205 16 437
1206 18 0
1207 };
1208
1209 \filldraw [fill=black!25, draw=black] (16, 0) rectangle (18, 437);
1210 \end{axis}\end{tikzpicture}
1211 \caption{Histogram of natural paragraph lengths in the sample text.}
1212 \label{fig:hist}
1213 \end{figure}
1214
1215 Let's look at some statistics for \lwc/. For testing, I
1216 downloaded the top~ten books on \textsl{Project Gutenberg},\footnotemark{}
1217 converted them to \LaTeX{} using \textsf{pandoc}, concatenated them into a
1218 single \textsf{article} file, and compiled twice. This gives us a \acro{PDF}
1219 with 1\,381~pages, 15\,692~paragraphs, 61\,865~lines, and 399~\waos/
1220 (if they aren't removed).
1221 \footnotetext{\textsl{Frankenstein},
1222 \textsl{Pride and Prejudice},
1223 \textsl{Alice's Adventures in Wonderland},
1224 \textsl{The Great Gatsby},
1225 \textsl{The Adventures of Sherlock Holmes},
1226 \textsl{Simple Sabotage Field Manual},
1227 \textsl{A Tale of Two Cities},
1228 \textsl{The Picture of Dorian Gray},
1229 \textsl{Moby Dick},
1230 and \textsl{A Doll's House}.
1231 }
1232
1233 This is a fairly challenging test: almost every third page has a \woo/, over
1234 half of the paragraphs have two lines or fewer, and the text block is set to
1235 the fairly wide \textsf{article} defaults. An average document is
1236 much less challenging for \lwc/, so we can consider this to be a
1237 worst-case scenario.
1238
1239 \subsection{Widows and orphans removed}
1240
1241 \begin{figure}
1242 \begin{tikzpicture}\begin{axis}[
1243 ybar=0pt,
1244 bar width=0.8,
1245 xtick=data,
1246 ylabel={Widows and orphans removed},
1247 width=\linewidth,
1248 height=0.8\linewidth,
1249 xticklabels={
1250 \shortstack[c]{\hfill Maximum\\\hfill possible},
1251 \textsf{lwc} \texttt{default},
1252 \texttt{balanced},
1253 \LaTeX{},
1254 \texttt{strict},
1255 },
1256 x tick label style={
1257 font=\small,
1258 rotate=45,
1259 anchor=east,
1260 },
1261 enlarge x limits=0.2,
1262 ]
1263 \addplot+ [
1264 draw=black,
1265 fill=black!10,
1266 semithick,
1267 ] table [x expr=\coordindex, y index=0] {
1268 399
1269 392
1270 348
1271 179
1272 52
1273 };
1274
1275 \filldraw [fill=black!25, draw=black]
1276 (-0.4, 0) rectangle (0.4, 399);
1277 \end{axis}\end{tikzpicture}
1278 \divide\abovecaptionskip by 2
1279 \caption{The number of \waos/ removed by each method.}\label{fig:modes}
1280 \end{figure}
1281
1282 When we run \LaTeX{} with its default settings on the file, 179~(47\%) of
1283 the \waos/ are removed. When we add \lwc/ with default settings, we remove
1284 392~(98\%). Switching to strict mode, we can only remove 52~(13\%) of the
1285 \waos/. In balanced mode, we remove 348~(87\%). See figure~\ref{fig:modes}
1286 for a visual comparison.
1287
1288 \subsection{Paragraph costs}
1289
1290 \begin{figure}
1291 \begin{tikzpicture}\begin{axis}[
1292 width=\linewidth,
1293 height=0.8\linewidth,
1294 xlabel={Percentile},
1295 ylabel={Cost},
1296 ymode=log,
1297 legend entries={Long, Natural},
1298 legend pos=north west,
1299 cycle list={
1300 {black, thick},
1301 {black!35, thick},
1302 },
1303 ]
1304 \addplot+ table [x=Percentile, y=Long] {\plotdata};
1305 \addplot+ table [x=Percentile, y=Natural] {\plotdata};
1306
1307 \end{axis}\end{tikzpicture}
1308 \divide\abovecaptionskip by 2
1309 \caption{Paragraph costs by percentile rank for naturally-broken and
1310 one-line lengthened paragraphs.}\label{fig:costs}
1311 \end{figure}
1312
1313 The last section showed us that \lwc/ is quite effective at removing \waos/,
1314 so now let's look at the paragraphs that \lwc/ expands. As \TeX{}
1315 processes a document, \lwc/ is recording the costs for the naturally-broken
1316 and expanded versions of each paragraph in the document. Costs don't
1317 mean that much on their own, but a lower cost is always better.
1318
1319 As you can see in figure~\ref{fig:costs}, the lengthened paragraphs tend to
1320 have \emph{much} higher costs than the naturally-broken paragraphs. This
1321 is not surprising, since (as we've seen) a paragraph's demerits
1322 scale with the sixth
1323 power of glue stretch, so even a small amount of glue stretch can cause a
1324 huge increase in demerits.
1325
1326 The empty space on the left of the \q{long} line is from the paragraphs
1327 that \lwc/ was unable to lengthen at any cost. \LuaTeX{} assigns these
1328 paragraphs zero~demerits, so they disappear on a logarithmic plot.
1329
1330 \subsection{Lengthening vs.\ shortening paragraphs}
1331 \begin{figure}
1332 \begin{tikzpicture}\begin{axis}[
1333 xbar stacked,
1334 height=0.2\linewidth,
1335 width=\dimexpr\linewidth-1em,
1336 scale only axis,
1337 bar width=1,
1338 enlargelimits=false,
1339 xmin=0,
1340 ymin=-0.5,
1341 ymax=1,
1342 ymajorticks=false,
1343 xtick style={draw=none},
1344 xlabel={Paragraphs (thousands)},
1345 scaled x ticks=base 10:-3,
1346 xtick scale label code/.code={},
1347 legend style={at={(0.5,1)}, anchor=north},
1348 legend columns=5,
1349 legend cell align=left,
1350 legend style={
1351 /tikz/every even column/.append style={column sep=1em},
1352 draw=none,
1353 fill=none,
1354 },
1355 legend entries={
1356 {$n=1$},
1357 {$n$},
1358 {$n+1$},
1359 {$n\pm1$},
1360 {$n-1$}
1361 },
1362 ]
1363 \addplot [fill=black!10 ] coordinates {(4429, 0)}; % One
1364 \addplot [fill=white ] coordinates {(4474, 0)}; % None
1365 \addplot [pattern=north east lines] coordinates {(5457, 0)}; % Long
1366 \addplot [pattern=crosshatch ] coordinates {( 482, 0)}; % Both
1367 \addplot [pattern=north west lines] coordinates {( 850, 0)}; % Short
1368 \end{axis}\end{tikzpicture}
1369 \divide\abovecaptionskip by 2
1370 \caption{The number of paragraphs in the test sample that
1371 (respectively) have exactly
1372 one line, cannot be stretched or shrunk, can be only stretched
1373 by one~line, can be either stretched or shrunk, and can be
1374 only shrunk.}
1375 \label{fig:stretchshrink}
1376 \end{figure}
1377
1378 Figure~\ref{fig:stretchshrink} shows the number of paragraphs that \lwc/
1379 could potentially stretch or shrink. The one-line paragraphs are broken out
1380 separately since this test sample has an anomalous number of them.
1381 Otherwise, we can see that \lwc/ is capable of stretching the majority of
1382 paragraphs.
1383
1384 We can also see that of non-single-line paragraphs, only about 8\%
1385 of paragraphs can only be shrunk (the last segment of
1386 figure~\ref{fig:stretchshrink}), and this is in a document where 13\%
1387 of paragraphs have at least eight~lines. Most documents rarely have
1388 such long paragraphs, and it is these long paragraphs that are the
1389 easiest to shrink.
1390
1391 Because of this, \lwc/ doesn't even attempt to shrink paragraphs; it
1392 only stretches them.
1393
1394 \section{Known issues}
1395
1396 \Lwc/ is quite stable these days, a few issues remain:
1397
1398 \begin{itemize}
1399 \item When a three-line paragraph is at the end of a page forming a
1400 widow, \lwc/ will remove the widow; however, it will leave an orphan.
1401 This issue is inherent to any process that removes widows through
1402 paragraph expansion and is thus unavoidable. Orphans are considered
1403 to be better than widows~\cite{elements}, so this is still an
1404 improvement.
1405
1406 \item Sometimes a \woo/ cannot be eliminated because no paragraph has
1407 enough stretch. Sometimes this can be remediated by
1408 increasing \lwc/'s \estretch/; however, some pages just don't have
1409 any suitable paragraph.
1410
1411 Long paragraphs with short words tend to be stretchier than short
1412 paragraphs with long words since these long paragraphs have more
1413 interword glue. Narrow columns also stretch more easily than wide columns
1414 since you need to expand a paragraph by less to make a new line.
1415
1416 \item When running under \LuaMetaTeX{} (\ConTeXt{}), the log may
1417 contain many lines like \q{\texttt{%
1418 \spaceskip=\fontdimen2\font plus1.25pt minus1.25pt
1419 luatex warning > tex: left parfill skip is gone}}. These messages
1420 are completely harmless (although admittedly quite annoying).
1421
1422 \item \TeX{} may warn about overfull \cs{vbox}es on pages where
1423 \lwc/ removed a \woo/. This happens due to the way that \lwc/
1424 corrects for the \cs{prevdepth} when replacing paragraphs. It
1425 does not actually produce an overfull \texttt{vbox}, but there
1426 is a warning nevertheless. You can set \cs{vfuzz=2.5pt} to
1427 hide the
1428 warning.
1429
1430 \item \Lwc/ only attempts to expand paragraphs on a page with
1431 a \woo/. A global system like in~\cite{global} would solve this;
1432 however, this is both \acro{NP}-complete~\cite{plass} and
1433 impossible to solve in a single pass. Very rarely would such a
1434 system remove \woos/ that \lwc/ cannot.
1435 \end{itemize}
1436
1437 \section{Conclusion}
1438
1439 All this probably makes \lwc/ look quite complicated, and this is true to
1440 some extent. However, this complexity is hidden from the end~user:
1441 as stated at the outset, most
1442 users merely need to place \latexuse/ in their \LaTeX{} document
1443 preamble, and \lwc/ will remove all the troublesome \waos/, without needing
1444 any manual intervention.
1445
1446 Should you have any issues, questions, or suggestions for \lwc/, please
1447 visit the project's GitHub page:
1448 \href{https://github.com/gucci-on-fleek/lua-widow-control}
1449 {\ttfamily github.com/gucci-on-fleek/lua-widow-control}.
1450 Any feedback is greatly appreciated!
1451
1452 \bibliographystyle{tugboat}
1453 \AddToHook{env/thebibliography/begin}{%
1454 \let\eTeX=\goodeTeX%
1455 \let\tubeTeX=\goodeTeX%
1456 }
1457 \let\macro=\cs
1458 \SetBibJustification{\raggedright \advance\itemsep by 1pt plus1pt minus1pt
1459 \def\url{\tbsurl}
1460 }
1461 \smallskip
1462 \bibliography{\jobname.bib, tugboat.bib}
1463
1464 \makesignature
1465 \end{document}