% lua-widow-control
% https://github.com/gucci-on-fleek/lua-widow-control
% SPDX-License-Identifier: MPL-2.0+
% SPDX-FileCopyrightText: 2022 Max Chernoff

\wlog{lua-widow-control v2.0.5} %%version

\ifx\directlua\undefined
    \errmessage{%
        LuaTeX is required for this package.
        Make sure to compile with `luatex'%
    }
\fi

\catcode`@=11

\input ltluatex % \LuaTeX{}Base

\clubpenalty=1
\widowpenalty=1
\displaywidowpenalty=1
\brokenpenalty=1

\newdimen\lwcemergencystretch
\lwcemergencystretch=3em

\newcount\lwcmaxcost
\lwcmaxcost=2147483647

\directlua{require "lua-widow-control"}

% Here, we enable font expansion/contraction. It isn't strictly necessary for
% \lwc/'s functionality; however, it is required for the
% lengthened paragraphs to not have terrible spacing.
\expandglyphsinfont\the\font 20 20 5
\adjustspacing=2

% Define \TeX{} wrappers for Lua functions
\def\lwcenable{\directlua{lwc.enable_callbacks()}}
\def\lwcdisable{\directlua{lwc.disable_callbacks()}}
\def\iflwc{\directlua{lwc.if_lwc_enabled()}}

% Enable \lwc/ by default when the package is loaded.
\lwcenable

% Expansion of some parts of the document, such as section headings, is quite
% undesirable, so we'll disable \lwc/ for certain commands.

% We should only reenable \lwc/ at the end if it was already enabled.
\newcount\lwc@disable@count

\def\lwc@patch@pre{%
    \iflwc%
        \advance\lwc@disable@count by 1%
        \lwcdisable%
    \fi%
}

\def\lwc@patch@post{
    \ifnum\lwc@disable@count>0%
        \lwcenable%
        \advance\lwc@disable@count by -1%
    \fi
}

\def\lwc@extractcomponents #1:#2->#3\STOP{%
    \def\lwc@params{#2}%
    \def\lwc@body{#3}%
}

\def\lwcdisablecmd#1{%
    \ifdefined#1%
        \expandafter\lwc@extractcomponents\meaning#1\STOP%
        \begingroup%
            \catcode`@=11%
            \expanded{%
                \noexpand\scantokens{%
                    \gdef\noexpand#1\lwc@params{%
                        \noexpand\lwc@patch@pre\lwc@body\noexpand\lwc@patch@post%
                    }%
                }%
            }%
        \endgroup%
    \fi%
}

\begingroup
    \suppressoutererror=1
    \lwcdisablecmd{\beginsection} % Sectioning
\endgroup


\catcode`@=12
\endinput
