% \iffalse meta-comment
%
% memoir.dtx 
% Author: Peter Wilson (Herries Press) herries dot press at earthlink dot net 
% Maintainer: Lars Madsen (daleif at math dot au dot dk) 
% Copyright 2001--2010 Peter R. Wilson
% Copyright 2011--     Lars Madsen
% 
% This work may be distributed and/or modified under the
% conditions of the LaTeX Project Public License, either
% version 1.3c of this license or (at your option) any 
% later version.
% The latest version of the license is in
%    http://www.latex-project.org/lppl.txt
% and version 1.3c or later is part of all distributions of
% LaTeX version 2008/05/04 or later.
%
% This work has the LPPL maintenance status "maintained".
%
% This work consists of the files listed in the README file.
% 
% \fi
% ^^A\CheckSum{28340} 
%
% \changes{v0.1}{2001/05/20}{First public alpha release}
% \changes{v0.2}{2001/06/03}{First beta release}
% \changes{v0.3}{2001/07/09}{Bug fixing}
% \changes{v0.31}{2001/07/09}{Bug fixing} 
% \changes{v0.32}{2001/08/03}{Fix for old versions of amsmath package}
% \changes{v0.33}{2001/08/03}{Added controllable chapter/LoF spacing}
% \changes{v0.33}{2001/08/03}{Fixed bug in \cs{appendixpage}}
% \changes{v1.0}{2001/10/30}{First production release}
% \changes{v1.0a}{2001/12/07}{Feature fixes} ^^A never released
% \changes{v1.1}{2002/03/10}{More fixups}
% \changes{v1.1}{2002/03/10}{Replaced all the subfigure code}
% \changes{v1.1}{2002/03/28}{Added sidebars}
% \changes{v1.1}{2002/03/28}{Upgraded verse typesetting}
% \changes{v1.2}{2002/07/07}{Added 17pt option}
% \changes{v1.2}{2002/07/07}{Added extra \cs{provide} commands}
% \changes{v1.2}{2002/07/27}{Major verbatim, box and file additions}
% \changes{v1.2}{2002/07/27}{Removed extraneous space from change marks}
% \changes{v1.2}{2002/07/27}{Extra optarg in \cs{chapter} and \cs{chapter*}}
% \changes{v1.2}{2002/07/27}{Twiddled font sizes a little}
% \changes{v1.2}{2002/08/27}{Fixed 12pt bug}
% \changes{v1.3}{2002/09/27}{Minor tweaks wrt v1.2}
% \changes{v1.3}{2002/10/10}{Extra trimming styles}
% \changes{v1.3}{2002/10/10}{Major extensions for indexing}
% \changes{v1.3}{2002/11/14}{Automatically call a patch file}
% \changes{v1.3a}{2002/11/22}{Fixed nasty figure/table bug}
% \changes{v1.4}{2003/02/27}{Added patches v1.1}
% \changes{v1.4}{2003/02/27}{Added patches v1.3}
% \changes{v1.4}{2003/11/16}{Including current patches}
% \changes{v1.4}{2003/11/16}{Added patches v1.2}
% \changes{v1.4}{2003/11/22}{Added patches v1.4}
% \changes{v1.4}{2003/11/22}{Added patches v1.5}
% \changes{v1.4}{2003/11/22}{Added patches v1.6}
% \changes{v1.4}{2003/11/22}{Added patches v1.7}
% \changes{v1.4}{2003/11/30}{Added patches v1.8}
% \changes{v1.4}{2003/11/30}{Added patches v1.9}
% \changes{v1.6}{2004/01/31}{Decided to issue v1.4 as v1.6 on the way to 
%                            the golden section 1.6180339887...}
% \changes{v1.61}{2004/03/14}{Changes to clo files, and footnotes} 
% \changes{v1.61}{2004/03/21}{Removed a potential problem with the 
%                             hangul package}
% \changes{v1.618}{2005/09/02}{Folded in all v1.61 patches}
% \changes{v1.618}{2005/09/15}{Some minor extensions}
% \changes{v1.618}{2005/09/25}{Support for glossaries}
% \changes{v1.6180}{2006/06/12}{Footnote font fix}
% \changes{v1.61803}{2008/05/26}{Folded in all mempatch v4.9a patches}
% \changes{v1.618033}{2008/06/02}{Fixed(?) page layout algorithms}
% \changes{v1.6180339}{2008/07/23}{Unemulated if... packages}
% \changes{v1.6180339}{2008/07/23}{Folded in all mempatch v5.1 patches}
% \changes{v1.6180339a}{2008/08/07}{Removed extra space in footnotes}
% \changes{v1.6180339c}{2009/01/21}{Minor bug fixes and extensions}
% \changes{v1.6180339c}{2009/01/25}{A few more}
% \changes{v1.6180339d}{2009/02/04}{Fixed a bug in the running
%                                   head/foot widths}
% \changes{v1.6180339f}{2009/03/16}{Start of `f' version.}
% \changes{v1.6180339f}{2009/03/16}{Fixed problem with companion pagestyle
%                                   and added 2 col Toc}
% \changes{v1.6180339f}{2009/04/25}{Extended description lists}
% \changes{v1.6180339f}{2009/07/12}{Added three \cs{memlet...} macros}
% \changes{v1.6180339g}{2009/07/13}{Fixed a bug regading extre enties
% in the page note list}
% \changes{v1.61803398}{2009/07/17}{Added bidi (RTL) support}
% \changes{v1.61803398}{2009/07/27}{Fixed bug in \cs{@setclcnt}, added simple pagestyle}
% \changes{v1.61803398}{2009/08/08}{changed the code that defined the
% main function out of \cs{newlistof}}
% \changes{v1.61803398}{2009/09/10}{fixed bug with upquote}
% \changes{v1.61803398b}{2009/09/21}{fixed typo}
% \changes{v1.61803398c}{2009/11/13}{fixed typo}
% \changes{v1.61803398d}{2009/11/13}{fixed infelicity with \cs{@starttoc}}
% \changes{v1.61803398d}{2009/12/01}{fixed bug in ifxetex, ifpdf,...}
% \changes{v1.61803398d}{2009/12/18}{made \cs{subcaptionref} robust}
% \changes{v1.61803398d}{2010/xx/xx}{several changes}
% \changes{v1.618033988}{2010/02/16}{bumped version to v1.618033988}
% \changes{v1.618033988b}{2010/02/17}{fixed typo that broke \cs{feetbelowfloat}}
% \changes{v1.618033988c}{2010/02/20}{fixed sporadic space in \cs{@footnotetext}}
% \changes{v1.618033988d}{2010/02/26}{fixed bug in
% \cs{marginparmargin}\{left\} in twoside mode}
%
% \changes{v3.6}{2010/04/19}{Reversioned memoir to a more suitable scheme}
% \changes{v3.6d}{2010/07/01}{Various bug fixes}
% \changes{v3.6e}{2010/08/20}{Maintenance}
% \changes{v3.6f}{2010/08/22}{Bad typo}
% \changes{v3.6g}{2010/09/19}{Maintenance}
% \changes{v3.6h}{2011/02/13}{Various things}
% \changes{v3.6i}{2011/02/18}{Two bug fixes}
% \changes{v3.6j}{2011/03/06}{Bug fixes}
% \changes{v3.6k}{2013/05/17}{Various fixes and long overdue maintenance}
% \changes{v3.7}{2013/05/22}{Bumped version}
% \changes{v3.7b}{2013/05/30}{Bugfix, sidecaption}
% \changes{v3.7c}{2015/03/05}{Bugfix}
% \changes{v3.7d}{2015/04/23}{Misc. bugfixes}
% \changes{v3.7e}{2015/07/08}{Per request from LaTeX Team, etex is not
%                             autoloaded on newer kernels}
% \changes{v3.7f}{2016/05/16}{Maintenance, luatex85 and booktabs update}
% 
% \changes{v3.7h}{2018/12/12}{Maintenance, removing some emulated packages}
% \changes{v3.7i}{2019/11/15}{Maintenance, various edits}
% \changes{v3.7j}{2019/11/21}{Typo in embeded textcase, now that it is
%                             inside \cs{IfFileExists} \# needs to be doubled}
% \changes{v3.7k}{2020/03/25}{Maintenance} 
% \changes{v3.7l}{2020/06/02}{Small preparation for october kernel update} 
% \changes{v3.7m}{2020/09/10}{More preparations for october kernel update} 
% \changes{v3.7n}{2020/10/04}{Foced # doubling in AtBegin/EndX macros
% to ensure backwards compatability} 
% \changes{v3.7o}{2021/03/23}{Maintenance and a provide for the kernel}
% \changes{v3.7p}{2021/06/16}{Small adjustments of memoir vs memhfixc}
% \changes{v3.7q}{2022/02/20}{Maintenance}
% \changes{v3.7r}{2022/07/29}{Maintenance}
% \changes{v3.7.19}{2022/11/17}{Maintenance}
% \changes{v3.8}{2023/08/08}{Maintenance, see the README for details}
% \changes{v3.8a}{2023/08/14}{Forgot to enable stopping if the LaTeX
%                             format is too old}
% \changes{v3.8.1}{2023/08/21}{Moved AddToHook from \@xfloat to
% \@floatboxreset as the float package causes issues}
% \changes{v3.8.3}{2025/03/06}{Various updates}
% \changes{v3.8.3b}{2025/03/10}{Bug fix}
% \changes{v3.8.4}{2025/03/10}{Maintenance}
% 
% \def\dtxfile{memoir.dtx}
%
% \def\fileversion{v0.1}  \def\filedate{2001/05/20}
% \def\fileversion{v0.2}  \def\filedate{2001/06/03}
% \def\fileversion{v0.3}  \def\filedate{2001/07/14}
% \def\fileversion{v0.31} \def\filedate{2001/07/24}
% \def\fileversion{v0.32} \def\filedate{2001/08/03}
% \def\fileversion{v0.33} \def\filedate{2001/08/31}
% \def\fileversion{v1.0}  \def\filedate{2001/11/17}
% \def\fileversion{v1.0a} \def\filedate{2001/12/07}
% \def\fileversion{v1.1}  \def\filedate{2002/03/28}
% \def\fileversion{v1.1a} \def\filedate{2002/04/28}
% \def\fileversion{v1.2}  \def\filedate{2002/08/10}
% \def\fileversion{v1.2}  \def\filedate{2002/08/27}
% \def\fileversion{v1.3}  \def\filedate{2002/11/14}
% \def\fileversion{v1.3a} \def\filedate{2002/11/22}
% \def\fileversion{v1.4}  \def\filedate{2003/12/18}
% \def\fileversion{v1.6}  \def\filedate{2004/01/31}
% \def\fileversion{v1.61}  \def\filedate{2004/04/04}
% \def\fileversion{v1.618}  \def\filedate{2005/09/27}
% \def\fileversion{v1.6180}  \def\filedate{2006/06/12}
% \def\fileversion{v1.61803}  \def\filedate{2008/05/26}
% \def\fileversion{v1.618033}  \def\filedate{2008/06/02}
% \def\fileversion{v1.6180339}  \def\filedate{2008/07/23}
% \def\fileversion{v1.6180339a}  \def\filedate{2008/08/07}
% \def\fileversion{v1.6180339c}  \def\filedate{2009/01/21}
% \def\fileversion{v1.6180339c}  \def\filedate{2009/01/25}
% \def\fileversion{v1.6180339d}  \def\filedate{2009/02/04}
% \def\fileversion{v1.6180339e}  \def\filedate{2009/02/06}
% \def\fileversion{v1.6180339f}  \def\filedate{2009/07/12}
% \def\fileversion{v1.6180339g}  \def\filedate{2009/07/13}
% \def\fileversion{v1.61803398}  \def\filedate{2009/09/10}
% \def\fileversion{v1.61803398b}  \def\filedate{2009/09/21}
% \def\fileversion{v1.61803398c}  \def\filedate{2009/11/17}
% \def\fileversion{v1.61803398d}  \def\filedate{2009/11/23}
% \def\fileversion{v1.618033988}  \def\filedate{2010/02/16}
% \def\fileversion{v1.618033988b}  \def\filedate{2010/02/17}
% \def\fileversion{v1.618033988c}  \def\filedate{2010/02/20}
% \def\fileversion{v3.6}           \def\filedate{2010/04/19}
% \def\fileversion{v3.6d}          \def\filedate{2010/07/01}
% \def\fileversion{v3.6e}          \def\filedate{2010/08/20}
% \def\fileversion{v3.6f}          \def\filedate{2010/08/22}
% \def\fileversion{v3.6g}          \def\filedate{2010/09/19}
% \def\fileversion{v3.6h}          \def\filedate{2011/02/13}
% \def\fileversion{v3.6i}          \def\filedate{2011/02/18}
% \def\fileversion{v3.6j}          \def\filedate{2011/03/06}
% \def\fileversion{v3.6k}          \def\filedate{2013/05/17}
% \def\fileversion{v3.7}          \def\filedate{2013/05/22}
% \def\fileversion{v3.7b}          \def\filedate{2013/05/30}
% \def\fileversion{v3.7c}          \def\filedate{2015/03/05}
% \def\fileversion{v3.7d}          \def\filedate{2015/04/23}
% \def\fileversion{v3.7e}          \def\filedate{2015/07/08}
% \def\fileversion{v3.7f}          \def\filedate{2016/05/16}
% \def\fileversion{v3.7g}          \def\filedate{2018/04/04}
% \def\fileversion{v3.7h}          \def\filedate{2018/12/12} 
% \def\fileversion{v3.7i}          \def\filedate{2019/11/15} 
% \def\fileversion{v3.7j}          \def\filedate{2019/11/21} 
% \def\fileversion{v3.7k}          \def\filedate{2020/03/25} 
% \def\fileversion{v3.7l}          \def\filedate{2020/06/02} 
% \def\fileversion{v3.7m}          \def\filedate{2020/09/10} 
% \def\fileversion{v3.7n}          \def\filedate{2020/10/04} 
% \def\fileversion{v3.7o}          \def\filedate{2021/03/23} 
% \def\fileversion{v3.7p}          \def\filedate{2021/06/16} 
% \def\fileversion{v3.7q}          \def\filedate{2022/02/20} 
% \def\fileversion{v3.7r}          \def\filedate{2022/07/29} 
% \def\fileversion{v3.7.19}          \def\filedate{2022/11/17} 
% \def\fileversion{v3.8}          \def\filedate{2023/08/08} 
% \def\fileversion{v3.8.1}          \def\filedate{2023/08/21} 
% \def\fileversion{v3.8.2}          \def\filedate{2024/01/26} 
% \def\fileversion{v3.8.3}          \def\filedate{2025/03/06} 
% \def\fileversion{v3.8.3b}          \def\filedate{2025/03/10} 
% \def\fileversion{v3.8.4}          \def\filedate{2025/10/02} 
% \title{The LaTeX \Lpack{memoir} class for configurable book 
%        typesetting: Source code\thanks{This
%        file (\texttt{\dtxfile}) has version number \fileversion, last revised
%        \filedate.}}
%
% \author{%
% Peter Wilson\\ ^^A\thanks{\texttt{herries dot press at earthlink dot net}}\\
% Herries Press \\
% (maintained by Lars Madsen\thanks{\texttt{daleif at math dot au dot dk}}\ )}
% \date{\filedate}
% \maketitle
%
% \begin{abstract}
% The \Lpack{memoir} class is designed for typesetting
% general books such as novels, biographies, histories, 
% and so on, although as it supports all the functionality of the 
% standard \Lpack{book} class it can also be used for technical writing.
% It provides more functions than the standard class as well as 
% presenting a more friendly interface for the book designer.
% It can also simulate the typesetting style of the standard \Lpack{article}
% class.
%
%    The class was first released in mid 2001 and has been well used ever
% since.
% \end{abstract}
%
% \tableofcontents
% \listoftables
%
% \StopEventually{}
%
% 
%
% \section{Introduction}
%
% This document provides the commented source 
% for the LaTeX \Lpack{memoir} class, which is designed for typesetting
% general books such as novels, biographies, histories, 
% and so on. It has all the functionality of the standard \Lpack{book}
% class and, as well as providing some extra functions, also provides
% a more friendly interface for the document designer. As it can encompass
% everything that the \Lpack{book} class provides it may also be used
% for technical writing.
%
%   The default appearance of a document typeset with this class is
% the same as if it had been typeset with the \Lpack{book} class and
% it can be made to simulate the \Lpack{article} class..
% The class, though, includes extra facilities that make it easy to
% change the appearance of such things as the page headers and footers,
% the style of chapter and other sectional headings, and the style of
% captions. It also makes it easy to both change the style of the
% Table of Contents, List of Figures, etc., as well as creating new
% kinds of `List of\ldots'. New types of floats, if needed, can be
% created very simply. Epigraphs can be put into the document in a
% variety of styles.
%
%    The class provides a variety of page, chapter and captioning
% styles that you can choose from if you don't want to create your own.
%
%    Documents can be typeset in 9pt, 10pt, 11pt, 12pt, 14pt or 17pt font
% sizes, and if you have scaleable fonts available they can be set at any size.
% There is a reasonably intuitive means of setting the margins
% and placement of the text on a page. There is an option to put
% trim marks on the printed pages if the stock sheets need to be trimmed
% down to the final page size. For those whose publishers like a
% manuscript to look as though it was typewritten, there is an option
% to do this (double spacing, ragged right, no hyphenation, 
% fixed width font). There is also an unsophisticated means of flagging any
% revisions to the text.
%
%    As this is a new class, by default it does not support the old 
% LaTeX v2.09
% font commands, namely the \cs{bf}, \cs{sl}, \cs{it} and \cs{sc} commands;
% it warns about using the \cs{em} command but does support it.
%
%
% I hope that apart from the font commands the class 
% is compatible with
% `standard' LaTeX.
%
%    Development of this class would never have been started without
% the wonderful work done by Leslie Lamport and others~\cite{CLASSES}
% from whom I have learned a great deal and borrowed much code. 
%
%    Sections~\ref{sec:docstrip} through~\ref{sec:ic} describe some
% administrative elements and code for general use later in the 
% specification.
% The macros forming the class file are defined in sections~\ref{sec:opt}
% through~\ref{sec:init}. 
% 
% This manual is typeset according to the conventions of the
% \LaTeX{} \textsc{docstrip} utility which enables the automatic
% extraction of the \LaTeX{} macro source files~\cite{GOOSSENS94}.
%
%
% \section{A driver for this document} \label{sec:docstrip}
%
% The next series of code contains the documentation driver file for
% \LaTeX, i.e., the file that will produce the documentation you are
% currently reading. This will be extracted from this file by the 
% \textsc{docstrip} program.
%
%    \begin{macrocode}
%<*driver>
\documentclass[twoside]{ltxdoc}
\usepackage[T1]{fontenc}
\usepackage{url,array}
%%\usepackage[draft=false,
%%            plainpages=false,
%%            pdfpagelabels,
%%            bookmarksnumbered,
%%            hyperindex=true
%%           ]{hyperref}  % Doesn't work with indexing of \DescribeMacro
\providecommand{\phantomsection}{} % just in case hyperref not used 
%    \end{macrocode}
%
%    We do want an index, using linenumbers, but not update information.
%    \begin{macrocode}
\EnableCrossrefs
\CodelineIndex
%% \RecordChanges
%    \end{macrocode}
% We had better have page headings to aid navigation, but I don't
% like Uppercased titles.
%    \begin{macrocode}
\makeatletter
  \@mparswitchfalse
\makeatother
\renewcommand{\MakeUppercase}[1]{#1}
\pagestyle{headings}
%    \end{macrocode}
%    We may use so many \file{docstrip} modules that we set the
%    \texttt{StandardModuleDepth} counter to 1.
%    \begin{macrocode}
\setcounter{StandardModuleDepth}{1}
%    \end{macrocode}
%    Some commonly used abbreviations
%    \begin{macrocode}
\newcommand*{\Lopt}[1]{\textsf {#1}}            % typeset an option
\newcommand*{\file}[1]{\texttt {#1}}            % typeset a file
\newcommand*{\Lcount}[1]{\textsl {\small#1}}    % typeset a counter
\newcommand*{\pstyle}[1]{\textsl {#1}}          % typeset a pagestyle
\newcommand*{\Lenv}[1]{\texttt {#1}}            % typeset an environment
\newcommand*{\Lpack}[1]{\textsf {#1}}           % typeset a package
\newcommand*{\ctt}{\textsc{ctt}}                % comp.text.tex
\newcommand*{\Lhook}[1]{\meta{#1}}              % name of a hook
\newenvironment{PW}{\em}{}
\newenvironment{dlf}{\em}{}
\newcommand*\MarkedForDeprecation[1]{\par\noindent%
  \textcolor{red}{#1 is marked for deprecation}\par}
\newcommand*{\theTeXbook}{\textit{The \TeX book}}
\let\oldllap\llap
\def\llap#1{\oldllap{#1\quad}} % might be evil
%    \end{macrocode}
%    We want the full details printed.
%    \begin{macrocode}
\begin{document}
\DeleteShortVerb{\|}
\raggedbottom
%\raggedright
\DocInput{\jobname.dtx}
\PrintIndex
%% \PrintChanges
\end{document}
%</driver>
%    \end{macrocode}
%
%
%   ^^A  There are some elements we do not want to appear in the index.
% \DoNotIndex{\',\.,\@M,\@@input,\@addtoreset,\@arabic,\@badmath}
% \DoNotIndex{\@centercr,\@cite}
% \DoNotIndex{\@dotsep,\@empty,\@gobble,\@gobbletwo,\@ignoretrue}
% \DoNotIndex{\@input,\@ixpt,\@m}
% \DoNotIndex{\@minus,\@ne,\@nil,\@nomath,\@plus,\@set@topoint}
% \DoNotIndex{\@tempboxa,\@tempcnta,\@tempdima,\@tempdimb}
% \DoNotIndex{\@tempswafalse,\@tempswatrue,\@viipt,\@viiipt,\@vipt}
% \DoNotIndex{\@vpt,\@warning,\@xiipt,\@xipt,\@xivpt,\@xpt,\@xviipt}
% \DoNotIndex{\@xxpt,\@xxvpt,\\,\ ,\addpenalty,\addtolength,\addvspace}
% \DoNotIndex{\advance,\Alph,\alph}
% \DoNotIndex{\arabic,\ast,\begin,\begingroup,\bfseries,\bgroup,\box}
% \DoNotIndex{\bullet}
% \DoNotIndex{\cdot,\cite,\CodelineIndex,\cr,\day,\DeclareOption}
% \DoNotIndex{\def,\DisableCrossrefs,\divide,\DocInput,\documentclass}
% \DoNotIndex{\DoNotIndex,\egroup,\ifdim,\else,\fi,\em,\endtrivlist}
% \DoNotIndex{\EnableCrossrefs,\end,\endgroup}
% \DoNotIndex{\endlist,\everycr,\everypar,\ExecuteOptions,\expandafter}
% \DoNotIndex{\fbox}
% \DoNotIndex{\filedate,\filename,\fileversion,\fontsize,\framebox,\gdef}
% \DoNotIndex{\global,\halign,\hbox,\hfil,\hfill,\hrule}
% \DoNotIndex{\hsize,\hskip,\hspace,\hss}
%  ^^A \DoNotIndex{\if@tempswa,\fi}
% \DoNotIndex{\ifcase,\or,\fi}
% \DoNotIndex{\ifhmode,\ifvmode,\ifnum,\iftrue,\ifx,\fi,\fi,\fi,\fi,\fi}
% \DoNotIndex{\input}
% \DoNotIndex{\jobname,\kern,\leavevmode,\let}
% \DoNotIndex{\list,\llap,\long,\m@ne,\m@th}
% \DoNotIndex{\month,\newcommand,\newcounter,\newenvironment}
% \DoNotIndex{\NeedsTeXFormat,\newdimen}
% \DoNotIndex{\newlength,\newpage,\nobreak,\noindent,\null,\number}
% \DoNotIndex{\numberline,\OldMakeindex,\OnlyDescription,\p@}
% \DoNotIndex{\par,\paragraph,\paragraphmark,\parfillskip}
% \DoNotIndex{\penalty,\PrintChanges,\PrintIndex,\ProcessOptions}
% \DoNotIndex{\protect,\ProvidesClass}
% \DoNotIndex{\refstepcounter,\relax,\renewcommand,\reset@font}
% \DoNotIndex{\rightskip,\rlap,\rmfamily,\roman}
% \DoNotIndex{\roman,\secdef,\selectfont,\setbox,\setcounter,\setlength}
% \DoNotIndex{\settowidth,\sfcode,\skip,\sloppy,\slshape,\space}
% \DoNotIndex{\symbol,\the,\trivlist,\typeout,\tw@,\undefined,\uppercase}
% \DoNotIndex{\usecounter,\usefont,\usepackage,\vfil,\vfill,\viiipt}
% \DoNotIndex{\viipt,\vipt,\vskip,\vspace}
% \DoNotIndex{\wd,\xiipt,\year,\z@}
% \DoNotIndex{\@namedef,\@nameuse,\csname,\endcsname}
%
%
%
% \section{Identification} \label{sec:id}
%
% The \Lpack{memoir} document class can only be used with LaTeX2e, so
% we make sure that an appropriate message is displayed when another
% \TeX{} format is used.
% \changes{v3.8}{2023/08/02}{Added requirement on the kernel}
% \changes{v3.8.4}{2025/08/08}{Bumped required kernel by a year}
%    \begin{macrocode}
%<class>\def\mem@atleast@kernel{2023/06/01}
%<class>\NeedsTeXFormat{LaTeX2e}[\mem@atleast@kernel]
%    \end{macrocode}
%
% ^^A Use the Golden Section as the version number (1.6180339887 4989484820 4586834365)
% \changes{v3.6}{2010/04/19}{Not any more, apparently people does not
% know the numeric value of the golden ration very well}
%
%
%    Announce the name, option files and version for LaTeX2e files:
%    \begin{macrocode}
%<class>\ProvidesClass{memoir}%
%<class>  [2025/10/02 v3.8.4 configurable book, report, article document class]
%<class>\newcommand\memversion{v3.8.4, 2025/10/02}
%    \end{macrocode}
%
% \changes{v3.7m}{2020/08/05}{Added \cs{IfFormatAtLeastTF}}
% \changes{v3.8}{2023/08/02}{Moved up earlier so we can use it to
% issue an error if the kernel is too old.}
% \begin{macro}{\IfFormatAtLeastTF}
% Credit to Frank Mittelbach. Using
% \cs{IfFormatAtLeastTF}\marg{date}\marg{true}\marg{false} we can
% execute \meta{true} if the format is dated after the given
% \meta{date} (in {\scriptsize\ttfamily YYYY/MM/DD} format) and
% \meta{false} otherwise. The main use is for when we get info that
% certain features are being added to the \LaTeX\ format, features
% that we want to base class features on. Then this is an easy method
% for providing the code only avaiable on newer formats and code left
% over for those still using the older \LaTeX\ formats.\footnote{The \dots TF is a
% nice \LaTeX3 convention.}
%    \begin{macrocode}
%<class>\providecommand\IfFormatAtLeastTF{\@ifl@t@r\fmtversion}
%    \end{macrocode}
% \end{macro}
%
% Stop the loading if the kernel is too old (as \cs{NeedsTeXFormat}
% only issues a warning). Though we cannot do much about nonstopmode.
% \changes{v3.8a}{2023/08/14}{Forgot to enable the stop mode}
%    \begin{macrocode}
%<class>\IfFormatAtLeastTF{\mem@atleast@kernel}{}{
%<class>  \ClassError{memoir}{%
%<class>    Your LaTeX release is too old.\MessageBreak
%<class>    The memoir class requires at LaTeX format\MessageBreak
%<class>    from at least \mem@atleast@kernel\space  onwards.
%<class>    Please update your\MessageBreak
%<class>    entire LaTeX installation instead of manually updating\MessageBreak
%<class>    just memoir}{}
%<class>    \batchmode\read-1to\@tempa% evil mode engaged
%<class>}
%    \end{macrocode}
%
%    \begin{macrocode}
%<9pt> \ProvidesFile{mem9.clo}%
%<9pt>              [2022/07/29 v0.5 memoir class 9pt size option]
%<10pt>\ProvidesFile{mem10.clo}%
%<10pt>             [2022/07/29 v0.5 memoir class 10pt size option]
%<11pt>\ProvidesFile{mem11.clo}%
%<11pt>             [2022/07/29 v0.5 memoir class 11pt size option]
%<12pt>\ProvidesFile{mem12.clo}%
%<12pt>             [2022/07/29 v0.5 memoir class 12pt size option]
%<14pt>\ProvidesFile{mem14.clo}%
%<14pt>             [2022/07/29 v0.5 memoir class 14pt size option]
%<17pt>\ProvidesFile{mem17.clo}%
%<17pt>             [2022/07/29 v0.5 memoir class 17pt size option]
%<20pt>\ProvidesFile{mem20.clo}%
%<20pt>             [2022/07/29 v0.5 memoir class 20pt size option]
%<25pt>\ProvidesFile{mem25.clo}%
%<25pt>             [2022/07/29 v0.5 memoir class 25pt size option]
%<30pt>\ProvidesFile{mem30.clo}%
%<30pt>             [2022/07/29 v0.5 memoir class 30pt size option]
%<36pt>\ProvidesFile{mem36.clo}%
%<36pt>             [2022/07/29 v0.5 memoir class 36pt size option]
%<48pt>\ProvidesFile{mem48.clo}%
%<48pt>             [2022/07/29 v0.5 memoir class 48pt size option]
%<60pt>\ProvidesFile{mem60.clo}%
%<60pt>             [2022/07/29 v0.5 memoir class 60pt size option]
%    \end{macrocode}
%
%
% \section{Initial Code} \label{sec:ic}
%
%    \begin{macrocode}
%<*class>
%    \end{macrocode}
%
% (2022/02/20): In order to be able to use a patching approach instead
% of overwriting kernel macros, we will now require the
% \Lpack{etoolbox} package. (2023/07/28) changed to \Lpack{xpatch} as
% it supports a little more.
% \changes{v3.8}{2023/07/28}{replaced etoolbox by xpatch}
%    \begin{macrocode}
\RequirePackage{xpatch}      
%    \end{macrocode}
%
% (2024/01/31): There are a lot of excessive code in the class that
% probably does not have much use anymore. We will start deprecating
% stuff set for removal. In order to provide a transition period we
% provide a few macros to mark such that they give a warning (we only
% give one per macro).
%
% \begin{macro}{\MarkDeprecated}
%   \changes{v3.8.3}{2024/01/31}{Added this deprecation macro}
%   \cs{MarkDeprecated(*)}\marg{env or macro}\marg{when comment}, can
%   be used to add a deprecation warning to macros or envs. We
%   automatically remove \cs{} from macro names when needed. Normally
%   er add a marker macro to note that we have shown the warning
%   once. The starred version shows the warning at all uses.  ^^A It
%   can be
% ^^A added to a command either manually or via a hook:
% ^^A \begin{verbatim}
% ^^A \AddToHook{cmd/foo/before}{\MarkDeprecated{\foo}{start 2025}}
% ^^A \AddToHook{env/foo/before}{\MarkDeprecated{foo}{start 2025}}
% ^^A \end{verbatim}
% ^^A Note that the hooks are added at the start of the document, so we
% ^^A cannot use it to add to our own macros and reveil where they are
% ^^A used. The starred version will warn every time the macro is used.
%    \begin{macrocode}
\ExplSyntaxOn
% note that this is not technically correct expl3 code
\NewDocumentCommand\MarkDeprecated{smm}{
  % see if macro exists, if so don't give warning
  \cs_if_exist:cTF {__memoir_deprecated_\cs_to_str:N #2:}{}{% already showed one warning
    % marker macro did not exist, globally define it and give warning
    \IfBooleanF{#1}{\cs_gset:cn {__memoir_deprecated_\cs_to_str:N #2:}{}}
    \@memwarn{
      \string#2~is~marked~deprecated~and~will~be\MessageBreak
      removed~#3
    }
  }
}
\ExplSyntaxOff

%    \end{macrocode}
% \end{macro}
%
%
% Note (2001/08/03): Old versions of the \Lpack{amsmath} package did odd
% things with \cs{@tempa}, \cs{@tempb} and \cs{@tempc}. I have now replaced
% any use of these with \cs{@memtempa}, etc.
%
% \medskip\noindent
% In this part we define a few commands that are used later on.
%
% \begin{macro}{\@ptsize}
% \begin{macro}{\@memptsize}
%    The \cs{@ptsize} control sequence is normally used to store the 
%    second digit of the
%    pointsize we are typesetting in. So, normally, it's value is one
%    of 0, 1 or 2.
%
% \cs{@memptsize} stores the full pointsize.
% \changes{v1.61803}{2008/01/30}{Added \cs{@memptsize}}
%    \begin{macrocode}
\newcommand*{\@ptsize}{}
\newcommand*{\@memptsize}{}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% Any new lengths that depend on the point size option must be declared
% before the options are executed.
% \begin{macro}{\onelineskip}
% \begin{macro}{\lxvchars}
% \begin{macro}{\xlvchars}
% The length \cs{onelineskip} is the vertical space taken
% by a normal line of text. The lengths \cs{lxvchars} and \cs{xlvchars} are
% the approximate lengths required for typesetting lines with either 65 or 45
% characters.
%    \begin{macrocode}
\newlength{\onelineskip}
\newlength{\lxvchars}
\newlength{\xlvchars}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@memcnta}
% \begin{macro}{\c@memmarkcntra}
% We need a scratch count register and a scratch counter.
% \changes{v1.61803}{2008/10/30}{Added @memmarkcntra scratch counter}
%    \begin{macrocode}
\newcount\@memcnta
\newcounter{@memmarkcntra}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \changes{v1.0a}{2001/11/28}{Deleted count register \cs{@memtempa}}
%
% \begin{macro}{\if@restonecol}
%    When the document has to be printed in two columns, we sometimes
%    have to temporarily switch to one column. This switch is used to
%    remember to switch back.
%    \begin{macrocode}
\newif\if@restonecol
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\if@openright}
% This is TRUE if chapters are to start on righthand (recto) pages;
% this is the default. FALSE means chapters can start on any page.
%    \begin{macrocode}
\newif\if@openright
  \@openrighttrue

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\if@openleft}
% This is TRUE if chapters are to start on lefthand (verso) pages.
%    \begin{macrocode}
\newif\if@openleft
  \@openleftfalse

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\if@mainmatter}
% This is TRUE if the main part of the document is being currently procesed;
% this is the default.
%    \begin{macrocode}
\newif\if@mainmatter
  \@mainmattertrue

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\if@memoldfont}
% This is TRUE if the \Lopt{oldfontcommands} option is used.
% \changes{v1.0a}{2002/01/29}{Added \cs{if@memoldfont}}
%    \begin{macrocode}
\newif\if@memoldfont
  \@memoldfontfalse

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ifextrafontsizes}
% This is TRUE if the \Lopt{extrafontsizes} option is used.
% \changes{v1.61803}{2008/01/30}{Added \cs{ifextrafontsizes}}
%    \begin{macrocode}
\newif\ifextrafontsizes
  \extrafontsizesfalse

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@memerror}
% \begin{macro}{\@memwarn}
% Two macros to save some space when reporting errors or warnings.
% The macros take the same arguments, ignoring the first in each case,
% as \cs{ClassError} and \cs{ClassWarning}, e.g., \\
% \verb?\@memwarn{Message}? \\
% instead of \\
% \verb?\ClassWarning{memoir}{Message}?.
% \changes{v1.4}{2003/02/27}{Added \cs{@memerror} and \cs{@memwarn}}
%    \begin{macrocode}
\newcommand*{\@memerror}{\ClassError{memoir}}
\newcommand*{\@memwarn}{\ClassWarning{memoir}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\ifsamename}
% \begin{macro}{\nametest}
%    The macro \cs{nametest}\marg{name1}\marg{name2} tests whether the
% characters forming the two arguments are the same or not. If they are the
% same then \cs{ifsamename} is set TRUE, otherwise it is set FALSE. \meta{name1}
% and \meta{name2} must both be either macro names (including the backslash)
% or must both not be macro names. That is, you cannot do 
% \verb?\nametest{\cs}{cs}?.
% \changes{v1.61803398d}{2010/02/13}{added some \% because the macro
% was leaking spaces}
%    \begin{macrocode}
\newif\ifsamename
\newcommand{\nametest}[2]{%
  \samenamefalse%
  \begingroup%
  \def\@memtempa{#1}\def\@memtempb{#2}%
  \ifx \@memtempa\@memtempb%
    \endgroup%
    \samenametrue%
  \else%
    \endgroup%
  \fi}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\ifm@m@And}
% \begin{macro}{\m@m@Andtrue}
% \begin{macro}{\m@m@Andfalse}
% \begin{macro}{\ifm@m@Or}
% \begin{macro}{\m@m@Ortrue}
% \begin{macro}{\m@m@Orfalse}
% \begin{macro}{\ifm@m@Xor}
% \begin{macro}{\m@m@Xortrue}
% \begin{macro}{\m@m@Xorfalse}
% These are for `if A and B', `if A or B' and `if A xor B'.
%
% For A and B:
% \begin{verbatim}
% \m@m@Andfalse
% \ifA
%   \ifB
%     \m@mAndtrue
%   \fi
% \fi
% \end{verbatim}
% For A or B:
% \begin{verbatim}
% \m@m@Ortrue
% \ifA
% \else
%   \ifB
%   \else
%     \m@m@Orfalse
%   \fi
% \fi
% \end{verbatim}
% For A xor B:
% \begin{verbatim}
% \m@m@Xortrue
% \ifA
%   \ifB
%     \m@m@Xfalse
%   \fi
% \else
%   \ifB
%   \else
%     \m@m@Xorfalse
%   \fi
% \fi
% \end{verbatim}
% \changes{v1.618}{2005/09/09}{Added \cs{ifm@m@And}, \cs{ifm@m@Or} and \cs{ifm@m@Xor}}
%    \begin{macrocode}
\newif\ifm@m@And
\newif\ifm@m@Or
\newif\ifm@m@Xor

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \changes{v0.3}{2001/07/09}{Deleted \cs{fillline} and \cs{makecommand} as
% they were not used}
%
%  
% \changes{v3.8.3}{2024/02/02}{Deleted \cs{kill@lastcounter} as it is not used}
% 
%
% \begin{macro}{\@name@p@xdf}
% \begin{macro}{\@name@unresp@xdef}
% \begin{macro}{\@namelet}
% \begin{macro}{\@namelongdef}
%  Utility definition macros, along the lines of the kernel's \cs{@namedef}.
% \changes{v1.4}{2003/11/22}{Added \cs{@namelet} and friends (from patch v1.8)}
%    \begin{macrocode}
\newcommand{\@name@p@xdef}[1]{%
  \expandafter\protected@xdef\csname #1\endcsname}
\newcommand{\@name@unresp@xdef}[1]{%
  \expandafter\unrestored@protected@xdef\csname #1\endcsname}
\newcommand{\@namelet}[1]{%
  \expandafter\let\csname #1\endcsname}
\newcommand{\@namelongdef}[1]{%
  \long\expandafter\def\csname #1\endcsname}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\memletcmdtxt}
% \begin{macro}{\memlettxttxt}
% \begin{macro}{\memlettxtcmd}
% More utility macros (for the user but perhaps better not to tell them about
% it in the manual) \\
% \verb?\memletcmdtxt{\cmd}{txt}  -> \let\cmd\txt? \\
% \verb?\memlettxttxt{txta}{txtb} -> \let\txta\txtb? \\
% \verb?\memlettxtcmd{txt}{\cmd}  -> \let\txt\cmd? \\
% \changes{v1.6180339f}{2009/06/25}{Added \cs{memletcmdtxt}, \cs{memlettxttxt}
%        and \cs{memlettxtcmd}}
%    \begin{macrocode}
\newcommand*{\memletcmdtxt}[2]{\expandafter\let\expandafter#1\csname#2\endcsname}
\newcommand*{\memlettxttxt}[1]{\expandafter\memletcmdtxt\csname#1\endcsname}
\newcommand*{\memlettxtcmd}[2]{\expandafter\let\csname#1\endcsname#2}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@nameedef}
% A shorthand for using \cs{protected@edef}.
%    \begin{macrocode}
\newcommand{\@nameedef}[1]{%
  \expandafter\protected@edef\csname #1\endcsname}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\memjustarg}
% \begin{macro}{\memgobble}
% Utility macros \emph{that are not to be changed by any user!}
% \changes{v1.618}{2005/09/25}{Added \cs{memjustarg} and \cs{memgobble}}
%    \begin{macrocode}
\newcommand{\memjustarg}[1]{#1}
\newcommand{\memgobble}[1]{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \changes{v3.6k}{2013/05/14}{Added macro used macros}
% \begin{macro}{\memsetmacroused}
% \begin{macro}{\memsetmacrounused}
% \begin{macro}{\memifmacroused}
%   We may want to make auto adjustment to the layout unless the user
%   has used certain macros (in which case the user is responsible for
%   their own actions). To make this macro test easier, we provide a
%   few utility macros. Their use should be self explanatory. Though
%   note that the macro being marked as used, is given in full, i.e.,
% \begin{verbatim}
% \memsetmacroused\setlrmargins
% \end{verbatim}
%    \begin{macrocode}
\newcommand\memsetmacroused[1]{%
  \@namedef{mem@macro@used@\expandafter\@gobble\string#1}{00}}
\newcommand\memsetmacrounused[1]{%
  \@namedef{mem@macro@used@\expandafter\@gobble\string#1}{01}}
\newcommand\memifmacroused[1]{%
  \if\@nameuse{mem@macro@used@\expandafter\@gobble\string#1}%
  \expandafter\@firstoftwo\else\expandafter\@secondoftwo\fi}

%    \end{macrocode}
%   
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\memsetlengthmin}
% \begin{macro}{\memsetlengthmax}
%   Returns the min or max of two lengths. Note we may alter this in
%   the future to use \cs{dimexpr}.
%    \begin{macrocode}
\newcommand\memsetlengthmin[3]{\ifdim#2<#3\setlength{#1}{#2}\else\setlength{#1}{#3}\fi}
\newcommand\memsetlengthmax[3]{\ifdim#2>#3\setlength{#1}{#2}\else\setlength{#1}{#3}\fi}

%    \end{macrocode}
%   
% \end{macro}
% \end{macro}
%
% \subsection{Hooks and provided kernel commands}
% 
% \changes{v3.8}{2023/07/28}{Section added}
%
% 
% \changes{v3.8.4}{2025/09/24}{Polyfils for \cs{ExpandArgs} and hooks with arguments no longer needed}
% As the current requirement for the class is kernel of 2023/06/01, we
% currently have no need to add polyfils other than we provide
% \cs{IfFormatAtLeastTF} at the very start in order to short circuit
% of the kernel is too old.
%
%
% As we now require a kernel that have support for the new kernel
% hooks, we'll use this area to define the hooks and provide commands
% that are useful in even newer kernels, but might not be in the
% kernels we'd like to support.
%
% The \Lhook{memoir/subcaption} hook is executed after
% \cs{refstepcounter} in \cs{subcaption}, \cs{subbottom}, \cs{subtop}
% and similar.
%    \begin{macrocode}
\NewHook{memoir/subcaption/aftercounter}

%    \end{macrocode}
%
%
% \subsection{Classes, Packages and Files}
%
% \begin{macro}{\@memfakeusepackage}
% \cs{@memfakeusepackage}\marg{pack} fools \LaTeX{} into thinking
% that the \meta{pack.sty} package has been loaded.
% \changes{v1.4}{2003/11/22}{Added \cs{@memfakeusepackage} (from patch v1.9)}
%    \begin{macrocode}
\newcommand*{\@memfakeusepackage}[1]{%
  \@namelet{ver@#1.sty}\@empty}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\EmulatedPackage}
% \begin{macro}{\EmulatedPackageWithOptions}
%  There was some discussion on CTT\footnote{\textit{Re: breakurl + pdfetex 
% for generating .dvi}, March 2005.} about how to prevent loading of
% a package. My response was to use \cs{@memfakusepackage}. Donald Arseneau
% came up with this comprehensive solution (there was a little discussion
% about naming with my final suggestion as here). \\
% \cs{EmulatedPackage}\marg{package}\oarg{date} \\
% \cs{EmulatedPackageWithOptions}\marg{option-list}\marg{package}\oarg{date} \\
%
% \changes{v1.618}{2005/09/04}{Added \cs{EmulatedPackage} and
%          \cs{EmulatedPackageWithOptions}}
% \changes{v1.6180339}{2008/07/23}{Extended \cs{EmulatedPackage}}
%    \begin{macrocode}
\providecommand*{\EmulatedPackage}{}
\renewcommand*{\EmulatedPackage}[1]{%
  \@ifnextchar[{\@emulated@package{#1}}%
               {\@emulated@package{#1}[\@empty]}%]
}
\providecommand*{\EmulatedPackageWithOptions}{}
\renewcommand*{\EmulatedPackageWithOptions}[2]{%
  \PassOptionsToPackage{#1}{#2}%
  \EmulatedPackage{#2}%
}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@emulated@package}
%   The workhorse for the user commands. At some point we might want
%   to do this differently as many users does not realise that a
%   package is being blocked by memoir.
%    \begin{macrocode}
\def\@emulated@package#1[#2]{%
  \expandafter\xdef\csname ver@#1.\@pkgextension\endcsname{#2}%
  \@ifundefined{opt@#1.\@pkgextension}%
  {\@namedef{opt@#1.\@pkgextension}{}}{}%
  \wlog{Package #1 \ifx\@empty#2\else[#2] \fi 
    \if,\csname opt@#1.\@pkgextension\endcsname,\else
      (with options \csname opt@#1.\@pkgextension\endcsname) \fi
    emulated by \@currname.}%
}
\@onlypreamble\EmulatedPackage
\@onlypreamble\EmulatedPackageWithOptions
\@onlypreamble\@emulated@package

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\DisemulatePackage}
% \cs{DisemulatePackage}\marg{package} undoes a previous 
% \cs{EmulatedPackage...}
% \changes{v1.61803}{2008/01/30}{Added \cs{DisemulatePackage} from memptach v4.5}
% \changes{v1.6180339}{2008/07/23}{Fixed \cs{DisemulatePackage} from mempatch v5.1}
%    \begin{macrocode}
\newcommand*{\DisemulatePackage}[1]{%
  \@namelet{ver@#1.\@pkgextension}\relax
}
\@onlypreamble\DisemulatePackage

%    \end{macrocode}
% \end{macro}
%
% \noindent
% From 2020/10/01 format onwards we will implement file hooks via the
% features provided by the \LaTeX\ kernel. This makes our code easier
% to do (actually, users really ought to use these hook macros instead
% of the ones the class provides) and it eliminates the need for us to
% redefine \cmd{\InputIfFileExists}.
% \changes{v3.7m}{2020/08/06}{Reimplemented file/package/class hooks}
% \changes{v3.8.4}{2025/09/24}{removed format check}
%
% As mentioned in \cite{LTHOOKS,LTFILEHOOK} the kernel provides hooks
% at the start of files, packages and classes. The class you implement
% the latter via our definition of the file hook. We will now instead
% use the separate hooks. Note that we will \emph{not} be adding any
% extra labels to these hooks and will provide no interface to do
% so. If more control is needed, please use the kerel interface directly. 
% \begin{macro}{\AtBeginFile}
% \begin{macro}{\AtEndFile}
% \cs{AtBeginFile}\marg{file}\marg{code} inserts \meta{code}
% just before \meta{file} is input. Similarly \cs{AtEndFile} inserts
% just after input.
%
% \medskip\noindent
% \textbf{Breaking change:} In the old implemenation
% \verb!\AtEndFile{file}! worked for \texttt{file.tex} even if one
% did not speficy the extension. Now you will need to use
% \verb!\AtEndFile{file.tex}! explicitly.
% \changes{v3.7n}{2020/10/04}{The old AtXFile code required \#\
% doubling. The new does not, and this is not backwards compatible. By
% suggestion from David Carlisle we change the code a little such that
% \#\ is needed}
% We add a \cs{temp} trick suggested by David Carlisle as the old code
% required \texttt{\#} doubling and the new does not. To be backwards
% compatible we force required \texttt{\#} doubling.
% \changes{v3.7q}{2022/01/07}{The LaTeX team reversed the order of the
% hook name}
%    \begin{macrocode}
\newcommand\AtBeginFile[2]{\def\temp{\AddToHook{file/#1/before}{#2}}\temp}
\newcommand\AtEndFile[2]{\def\temp{\AddToHook{file/#1/after}{#2}}\temp}
  
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \begin{macro}{\AtBeginPackage}
% \begin{macro}{\AtEndPackage}
% \begin{macro}{\RequireAtEndPackage}
% \cs{AtBeginPackage}\marg{pack}\marg{code} inserts \meta{code} 
% just before the \meta{pack} package is input, and \cs{AtEndPackage}
% is the equivalent for after input. \cs{RequireAtEndPackage} inserts
% \meta{code} either at the end of \meta{pack}, or immediately if
% \meta{pack} has already been input.
% \changes{v3.7n}{2020/10/04}{The old AtXPackage code required \#\
% doubling. The new does not, and this is not backwards compatible. By
% suggestion from David Carlisle we change the code a little such that
% \#\ is needed}
% We add a \cs{temp} trick suggested by David Carlisle as the old code
% required \#\ doubling and the new does not. To be backwards
% compatible we force required \#\ doubling.
% \changes{v3.7q}{2022/01/07}{The LaTeX team reversed the order of the
% hook name}
%    \begin{macrocode}
\newcommand\AtBeginPackage[2]{\def\temp{\AddToHook{package/#1/before}{#2}}\temp}
\newcommand\AtEndPackage[2]{\def\temp{\AddToHook{package/#1/after}{#2}}\temp}
\newcommand{\RequireAtEndPackage}[2]{%
  \@ifpackageloaded{#1}{#2}{\AtEndPackage{#1}{#2}}}
  
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \begin{macro}{\AtBeginClass}
% \begin{macro}{\AtEndClass}
% \begin{macro}{\RequireAtEndClass}
% \cs{AtBeginClass}\marg{class}\marg{code} and friends are the class
% equivalents of \cs{AtBeginPackage} and friends.
% \changes{v3.7n}{2020/10/04}{The old AtXPackage code required \#\
% doubling. The new does not, and this is not backwards compatible. By
% suggestion from David Carlisle we change the code a little such that
% \#\ is needed}
% We add a \cs{temp} trick suggested by David Carlisle as the old code
% required \#\ doubling and the new does not. To be backwards
% compatible we force required \#\ doubling.
% \changes{v3.7q}{2022/01/07}{The LaTeX team reversed the order of the
% hook name}
% \begin{macrocode}
\newcommand\AtBeginClass[2]{\def\temp{\AddToHook{class/#1/before}{#2}}\temp}
\newcommand\AtEndClass[2]{\def\temp{\AddToHook{class/#1/after}{#2}}\temp}
\newcommand{\RequireAtEndClass}[2]{%
  \@ifclassloaded{#1}{#2}{\AtEndClass{#1}{#2}}}
  
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% ^^A % \noindent
% ^^A % Here follows the old code, which will still be used on older formats:
% ^^A %
% ^^A %    Code, based on a hint from Morten H{\o}gholm\footnote{CTT posting
% ^^A % 2005/11/08, \textit{Re: Checking for packages froma class... 
% ^^A % revisited}} that the \Lpack{scrlfile} package from 
% ^^A % \Lpack{koma-script} includes commands such as \\
% ^^A % \cs{AfterFile}\marg{file}\marg{code} \\
% ^^A % plus before and after classes and packages.
% ^^A % \changes{v1.16803}{2008/01/30}{Added various \cs{AtBegin...} and 
% ^^A %         \cs{AtEnd...} macros (mempatch v4.2)}
% ^^A %
% ^^A %    Extend the \cs{InputIfFileExists} macro to call hooks before and
% ^^A % the actual inputting. The kernel version (as of 2005/11/21) is:
% ^^A % \begin{verbatim}
% ^^A % \newcommand{\InputIfFileExists}[2]{%
% ^^A %  \IfFileExists{#1}%
% ^^A %    {\#2\@addtofilelist{#1}\@@input \@filef@und}}
% ^^A % \end{verbatim}
% ^^A % and as of 2019/10/01:
% ^^A % \begin{verbatim}
% ^^A %  \DeclareRobustCommand \InputIfFileExists[2]{%
% ^^A %     \IfFileExists{#1}%
% ^^A %       {\expandafter\@swaptwoargs\expandafter
% ^^A %         {\@filef@und}{#2\@addtofilelist{#1}\@@input}}}
% ^^A % \end{verbatim}
% ^^A % Just to make sure we still work on formats prior and after
% ^^A % 2019/10/01 we `redefine' both
% ^^A %
% ^^A % \begin{macro}{\InputIfFileExists}
% ^^A % Effectively all file input is handled by this macro. Extend it
% ^^A % by adding pre- and post- input hooks.
% ^^A % 
% ^^A % \changes{3.7i}{2019/10/22}{Added latest kernel changes, special
% ^^A % thanks to Phelype Oleinik}
% ^^A %    \begin{macrocode}
% ^^A   \ifcsname InputIfFileExists \endcsname% looking for an explicit space
% ^^A                                   % here aka the robust version
% ^^A     \DeclareRobustCommand \InputIfFileExists[2]{%
% ^^A       \IfFileExists{#1}%
% ^^A       {%
% ^^A         \expandafter\@swaptwoargs\expandafter
% ^^A         {\@filef@und\m@matendf{#1}\killm@matf{#1}}{%
% ^^A           #2\@addtofilelist{#1}\m@matbeginf{#1}\@@input%
% ^^A         }%
% ^^A       }%
% ^^A     }
% ^^A   \else
% ^^A     % Old definition
% ^^A     \renewcommand{\InputIfFileExists}[2]{%
% ^^A       \IfFileExists{#1}%
% ^^A       {#2\@addtofilelist{#1}\m@matbeginf{#1}%
% ^^A         \@@input \@filef@und
% ^^A         \m@matendf{#1}%
% ^^A         \killm@matf{#1}}}
% ^^A   \fi
% ^^A 
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A %
% ^^A % \begin{macro}{\m@matbeginf}
% ^^A % \begin{macro}{\m@matendf}
% ^^A % \cs{m@matbeginf}\marg{file} calls macro \cs{file-m@mfb} if it 
% ^^A % is defined. Similarly \cs{m@matendf}\marg{file} calls
% ^^A % \cs{file-m@mfe} if it is defined.
% ^^A %    \begin{macrocode}
% ^^A   \newcommand{\m@matbeginf}[1]{\@ifundefined{#1-m@mfb}{}%
% ^^A     {\@nameuse{#1-m@mfb}}}
% ^^A   \newcommand{\m@matendf}[1]{\@ifundefined{#1-m@mfe}{}%
% ^^A     {\@nameuse{#1-m@mfe}}}
% ^^A 
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A % \end{macro}
% ^^A %
% ^^A % \begin{macro}{\killm@matf}
% ^^A % \cs{killm@matf}\marg{file} undefines the \cs{file-m@mfb} and
% ^^A % \cs{file-m@mfe} macros.
% ^^A % ^^A    \begin{macrocode}
% ^^A % ^^A  we use the better defintion below
% ^^A % ^^A % \newcommand*{\killm@matf}[1]{%
% ^^A % ^^A %   \@namelet{#1-m@mfb}\relax
% ^^A % ^^A %   \@namelet{#1-m@mfe}\relax}
% ^^A % ^^A
% ^^A % ^^A   \end{macrocode}
% ^^A %
% ^^A % ^^A \subsection{Input files into tabulars, and etex}
% ^^A %
% ^^A %     M.J. Williams (CTT \textit{\cs{noalign} problem with \cs{input} and 
% ^^A % tabular in memoir class}, 28 Aug 2007) reported that using \cs{input} in a 
% ^^A % tabular resulted in errors. His example was:
% ^^A % \begin{verbatim}
% ^^A % ...
% ^^A % \begin{tabular}{c|c} \hline
% ^^A % 1 & 2 \\ \hline
% ^^A % \input{data} \hline
% ^^A % 5 & 6 \\ \hline
% ^^A % \end{tabular}
% ^^A % \end{verbatim}
% ^^A % where \texttt{data.tex} contains the single line (and no newline) \\
% ^^A % \verb?3 & 4 \\?
% ^^A %
% ^^A % Morten H{\o}gholm noted that the problem
% ^^A % was caused by \Lpack{memoir}'s extension to \cs{input}
% ^^A % and gave a solution that depends on processing via 
% ^^A % \texttt{etex} rather than \texttt{tex}.
% ^^A %
% ^^A % Here's Morten's fix. Quoting, in part:
% ^^A % \begin{quotation}
% ^^A %     \Lpack{memoir} extends the file loading mechanism by providing 
% ^^A % \cs{AtBeginFile} and \cs{AtEndFile} whose arguments are executed as 
% ^^A % the names indicate. \ldots after inputting a file the storage bins are 
% ^^A % emptied. The problem [in your case] is that this emptying is an
% ^^A % assignment and so starts a new tabular cell and \cs{hline} is only
% ^^A % allowed after \verb?\\? or other \cs{hline}s.
% ^^A %
% ^^A % \ldots the tabular environment wraps each tabular cell in additional
% ^^A % groups so one can do an explicit test for which type of group we are in.
% ^^A % If tested to be in an align group \emph{and} in vertical mode it means
% ^^A % TeX hasn't found something to start a new cell and
% ^^A % then \cs{noalign} can be used.
% ^^A % \end{quotation}
% ^^A %
% ^^A %    \begin{macrocode}
% ^^A  %% \ifetex
% ^^A   \newcommand*{\killm@matf}[1]{%
% ^^A     \ifnum 6=\currentgrouptype
% ^^A       \ifvmode
% ^^A         \expandafter\expandafter\expandafter\@firstoftwo
% ^^A         \expandafter\expandafter\expandafter\noalign
% ^^A       \fi
% ^^A     \fi
% ^^A     \@firstofone
% ^^A     {\@namelet{#1-m@mfb}\relax
% ^^A      \@namelet{#1-m@mfe}\relax
% ^^A     }%
% ^^A   }
% ^^A  %% \fi
% ^^A 
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A %
% ^^A % \begin{macro}{\AtBeginFile}
% ^^A % \begin{macro}{\AtEndFile}
% ^^A % \cs{AtBeginFile}\marg{file}\marg{code} inserts \meta{code}
% ^^A % just before \meta{file} is input. Similarly \cs{AtEndFile} inserts
% ^^A % just after input.
% ^^A %    \begin{macrocode}
% ^^A   \newcommand{\AtBeginFile}[2]{\@ifundefined{#1-m@mfb}%
% ^^A     {\@namedef{#1-m@mfb}{#2}}%
% ^^A     {\expandafter\addtodef\csname #1-m@mfb\endcsname{}{#2}}}
% ^^A   \newcommand{\AtEndFile}[2]{\@ifundefined{#1-m@mfe}%
% ^^A     {\@namedef{#1-m@mfe}{#2}}%
% ^^A     {\expandafter\addtodef\csname #1-m@mfe\endcsname{}{#2}}}
% ^^A 
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A % \end{macro}
% ^^A %
% ^^A % \begin{macro}{\AtBeginPackage}
% ^^A % \begin{macro}{\AtEndPackage}
% ^^A % \begin{macro}{\RequireAtEndPackage}
% ^^A % \cs{AtBeginPackage}\marg{pack}\marg{code} inserts \meta{code} 
% ^^A % just before the \meta{pack} package is input, and \cs{AtEndPackage}
% ^^A % is the equivalent for after input. \cs{RequireAtEndPackage} inserts
% ^^A % \meta{code} either at the end of \meta{pack}, or immediately if
% ^^A % \meta{pack} has already been input.
% ^^A %    \begin{macrocode}
% ^^A   \newcommand{\AtBeginPackage}[2]{%
% ^^A     \AtBeginFile{#1.\@pkgextension}{#2}}
% ^^A   \newcommand{\AtEndPackage}[2]{%
% ^^A     \AtEndFile{#1.\@pkgextension}{#2}}
% ^^A   \newcommand{\RequireAtEndPackage}[2]{%
% ^^A     \@ifpackageloaded{#1}{#2}%
% ^^A     {\AtEndFile{#1.\@pkgextension}{#2}}}
% ^^A 
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A % \end{macro}
% ^^A % \end{macro}
% ^^A %
% ^^A % \begin{macro}{\AtBeginClass}
% ^^A % \begin{macro}{\AtEndClass}
% ^^A % \begin{macro}{\RequireAtEndClass}
% ^^A % \cs{AtBeginClass}\marg{class}\marg{code} and friends are the class
% ^^A % equivalents of \cs{AtBeginPackage} and friends.
% ^^A %    \begin{macrocode}
% ^^A   \newcommand{\AtBeginClass}[2]{%
% ^^A     \AtBeginFile{#1.\@clsextension}{#2}}
% ^^A   \newcommand{\AtEndClass}[2]{%
% ^^A     \AtEndFile{#1.\@clsextension}{#2}}
% ^^A   \newcommand{\RequireAtEndClass}[2]{%
% ^^A     \@ifclassloaded{#1}{#2}%
% ^^A     {\AtEndFile{#1.\@clsextension}{#2}}}
% ^^A 
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A % \end{macro}
% ^^A % \end{macro}
% ^^A %
% ^^A %    \begin{macrocode}
% ^^A 
% ^^A  % end of else part of format check
% ^^A } 
% ^^A 
% ^^A %    \end{macrocode}
% ^^A %
%
%
% \begin{macro}{\phantomsection}
%   Whenever \Lpack{hyperref} is used and one uses fx
%   \cs{addcontentsline} at a place that has to hypertarget (e.g. a
%   counter being stepped) one adds \cs{phantomsection}.
%    \begin{macrocode}
\newcommand{\phantomsection}{}

%    \end{macrocode}
% \end{macro}
%
% ^^A dlf note: kernal macro redefinition
% \begin{macro}{\nofiles}
% The kernel's \cs{nofiles}, which surprisingly may be called \emph{before} 
% the class is loaded, lets \cs{makeindex} to \cs{relax}. This could 
% cause problems\footnote{As reported by Heiko Oberdiek on 2005/07/09.}
% with my initial version of \cs{makeindex}.
% Here's the kernel \cs{nofiles} definition:
% \begin{verbatim}
% \def\nofiles{%
%   \@fileswfalse%  flag for suppressing \immediate \writes
%   \typeout{No auxiliary output files.^^J}%
%   \long\def\protected@write##1##2##3%
%     {\write\m@ne{}\if@nobreak\ifvmode\nobreak\fi\fi}%
%   \let\makeindex\relax
%   \let\makeglossary\relax}
% \end{verbatim}
% To get it to work for when \cs{makeindex}es optional argument is
% used I let \cs{makeindex} itself deal with \cs{nofiles} (and
% also \cs{makeglossary}).
% \changes{v1.618}{2005/09/25}{Modified the kernel's \cs{nofiles}}
%    \begin{macrocode}
 \renewcommand*{\nofiles}{%
   \@fileswfalse%  flag for suppressing \immediate \writes
   \typeout{No auxiliary output files.^^J}%
   \long\def\protected@write##1##2##3%
     {\write\m@ne{}\if@nobreak\ifvmode\nobreak\fi\fi}%
   }

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\memsetcounter}
% A wrapper round \cs{setcounter}. I want to use this in the \texttt{aux} file.
% \changes{v1.61803}{2008/01/30}{Added \cs{memsetcounter}}
%    \begin{macrocode}
\newcommand*{\memsetcounter}[2]{\setcounter{#1}{#2}}
\AtBeginDocument{\immediate\write\@mainaux{%
  \string\providecommand*{\string\memsetcounter}[2]{}}}

%    \end{macrocode}
% \end{macro}
%
% \subsection{For package documentation}
%
% Some macros that may be useful for documenting LaTeX code. These
% have principally come from \texttt{doc.dtx}.
%
% \begin{macro}{\bs}
% Prints \verb?\?
%    \begin{macrocode}
\def\bs{\texttt{\char`\\}}
%    \end{macrocode}
% \end{macro} 
%
% \begin{macro}{\l@nohyphenation}
% \begin{macro}{\meta}
% \begin{macro}{\meta@font@select}
% From \texttt{doc.dtx} \\
% \cs{meta}\marg{arg} prints \meta{arg}.
%    \begin{macrocode}
\ifx\l@nohyphenation\undefined
  \newlanguage\l@nohyphenation
\fi
\DeclareRobustCommand{\meta}[1]{%
  \ensuremath\langle
  \ifmmode \expandafter \nfss@text \fi
  {%
    \meta@font@select
    \edef\meta@hyphen@restore
      {\hyphenchar\the\font\the\hyphenchar\font}%
    \hyphenchar\font\m@ne
    \language\l@nohyphenation
    #1\/%
    \meta@hyphen@restore
  }\ensuremath\rangle
}
\def\meta@font@select{\itshape}

%    \end{macrocode}
% \end{macro} 
% \end{macro} 
% \end{macro} 
%
% \begin{macro}{\marg}
% \begin{macro}{\oarg}
% \begin{macro}{\parg}
% Robust versions of the \texttt{doc.dtx} macros. \\
% \cs{marg}\marg{arg} prints \marg{arg} \\
% \cs{oarg}\marg{arg} prints \oarg{arg} \\
% \cs{parg}\marg{arg} prints \parg{arg} \\
%    \begin{macrocode}
\DeclareRobustCommand{\marg}[1]{%
  {\ttfamily\char`\{}\meta{#1}{\ttfamily\char`\}}}
\DeclareRobustCommand{\oarg}[1]{%
  {\ttfamily\char`\[}\meta{#1}{\ttfamily\char`\]}}
\DeclareRobustCommand{\parg}[1]{%
  {\ttfamily\char`\(}\meta{#1}{\ttfamily\char`\)}}
%    \end{macrocode}
% \end{macro} 
% \end{macro} 
% \end{macro} 
%
% \begin{macro}{\cs}
% \verb?\cs{arg}? prints \cs{arg}.
%    \begin{macrocode}
\DeclareRobustCommand{\cs}[1]{\texttt{\char`\\#1}}
%    \end{macrocode}
% \end{macro} 
%
%
% \begin{macro}{\cmdprint}
% \begin{macro}{\cmd}
% From Heiko Oberdiek CTT 2001/05/26 (print and index a command) \\
% \verb?\cmdprint{\fred}? prints \verb?\fred? \\
% \verb?\cmd{\fred}? prints and indexes \verb?\fred?. NOTE It assumes that
% \verb!?! is the `actual' character for MakeIndex (it is normally \verb!@!
% but that is not much use if a command includes \verb!@! as part of its name).
%    \begin{macrocode}
\newcommand{\cmdprint}[1]{\texttt{\string#1}}
\newcommand{\cmd}[1]{\cmdprint{#1}%
  \index{\expandafter\@gobble\string#1?\string\cmdprint{\string#1}}}

%    \end{macrocode}
% \end{macro} 
% \end{macro} 
%
%
%
%
% \subsection{Checking the processor}
%
% As of November 2019, we load the \Lpack{iftex} package in order to
% the the various processor tests. The package was updated in 2019 to
% cover the functionality of the \Lpack{ifpdf}, \Lpack{ifetex},
% \Lpack{ifxetex} and \Lpack{ifluatex} packages. You can find details
% about its use in \cite{IFTEX}.
% \changes{v3.7i}{2019/11/11}{Changed
% ifX package loading to just loading the new \Lpack{iftex}
% package. At the request of the LaTeX Project Team.}
%    \begin{macrocode}
\RequirePackage{iftex}[2019/11/07] 
%    \end{macrocode}
% The \Lpack{iftex} provides the following tests
% (and several more):
% \begin{macro}{\ifpdf}
% True if the output mode is PDF. Useful if for example you are
% working in an environment where you need to provide explicit code
% for the LaTeX+dvips route.
% \end{macro}
% \begin{macro}{\ifxetex}
% True if the XeTeX engine is being used.
% \end{macro}
% \begin{macro}{\ifluatex}
% True if the LuaTeX engine is being used. Useful if you want to add
% code that only apply under the LuaTeX based engines.
% \end{macro}
%
%
%
% ^^A %     Prior to 2008/07/22 the \Lpack{hyperref} package was modified in such a 
% ^^A % way as to produce warnings about versions of the \Lpack{ifpdf} and 
% ^^A % \Lpack{ifxetex} packages when \Lpack{hyperref} was used with versions 
% ^^A % v1.618033, 
% ^^A % v1.61803, or v1.618 mempatch v4.9 of the class. 
% ^^A % \Lpack{hyperref}'s author refused to
% ^^A % make any changes to his package, insisting that emulating a package was 
% ^^A % `ugly hacking'. He did, though, provide an example code that could be 
% ^^A % added to memoir
% ^^A % to use a package if it was available. I have used it for the emulations
% ^^A % in this section. There will be no further changes to the class to accomodate
% ^^A % any further changes to \Lpack{hyperref} --- it's easy for a package to 
% ^^A % determine what class is being used and make arrangements accordingly, 
% ^^A % especially as there are not all that many classes. There are hundreds 
% ^^A % of packages that might be used with a particular class and it would be 
% ^^A % senseless for a class to attempt to take account of everything that might 
% ^^A % be used with it.
% ^^A %
% ^^A % Note (2016/05/16): Due to recent changes in Luatex, most notably the
% ^^A % removal of several \cs{pdf...} macro, several PDF tests fail with
% ^^A % LuaLaTeX. As a temporary measure the following is used to restore
% ^^A % the old functionality when a newer LuaLaTeX is used. Code courtesy
% ^^A % of David Carlisle. At some point we will include some of this into
% ^^A % the class.
% ^^A % \changes{v3.7f}{2016/05/16}{Temp measure to make the class work with
% ^^A % updated luatex}
% ^^A % \changes{v3.7g}{2018/03/09}{\Lpack{luatex85} removed again, now
% ^^A % relying on external \cs{if<engine>} packages and have rewritten the
% ^^A % macros that use \cs{pdf...}}
% ^^A % ^^A %    \begin{macrocode}
% ^^A % ^^A \ifx\pdfextension\@undefined\else
% ^^A % ^^A   \RequirePackage{luatex85}
% ^^A % ^^A \fi    
% ^^A % ^^A 
% ^^A % ^^A %    \end{macrocode}
% ^^A % 
% ^^A %
% ^^A % \begin{macro}{\ifpdf}
% ^^A % This can be used to check whether or not a document is being processed
% ^^A % by \LaTeX{} or pdf\LaTeX.  We will simply require the \Lpack{ifpdf} package.
% ^^A % \changes{v1.0}{2001/09/21}{Made checking of \cs{pdfouput} more robust}
% ^^A % \changes{v1.618}{2005/09/03}{Prohibit loading the ifpdf package (mempatch v3.9)}
% ^^A % \changes{v1.618033}{2008/06/02}{Further improved pdf checking}
% ^^A % \changes{v1.6180339}{2008/07/23}{Use ifpdf package if available}
% ^^A % \changes{v1.61803398d}{2009/12/01}{if \cs{ifpdf} is already
% ^^A % defined, e.g. using \cs{RequirePackage} before \cs{documentclass},
% ^^A % then using \cs{newif}\cs{ifpdf} will cause TeX to eat up a lot of
% ^^A % code. We fix this using a hint by Will Robertson.}
% ^^A % \changes{v3.7g}{2018/03/08}{As of 2018, we will no longer be
% ^^A % emulating \cs{if}\meta{engine} packages, you'll get an error if you
% ^^A % do not have them}
% ^^A %    \begin{macrocode}
% ^^A % \RequirePackage{ifpdf}[2017/03/15] 
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A %
% ^^A % \begin{macro}{\ifetex}
% ^^A % Check if \texttt{etex} is being used. We will simply require the \Lpack{ifetex} package.
% ^^A % \changes{v1.61803}{2008/01/30}{Added check for etex (mempatch v4.9)}
% ^^A % \changes{v1.618033}{2008/06/02}{Improved check for etex}
% ^^A % \changes{v1.6180339}{2008/07/23}{Use an ifetex package if available}
% ^^A % \changes{v1.6180339c}{2008/12/27}{Changed ifetex message from Warning to Info}
% ^^A % \changes{v3.7g}{2018/03/08}{As of 2018, we will no longer be
% ^^A % emulating \cs{if}\meta{engine} packages, you'll get an error if you
% ^^A % do not have them}
% ^^A %    \begin{macrocode}
% ^^A  % \RequirePackage{ifetex}
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A % Having supplied an \cs{ifpdf} to check if pdfLaTeX is being used,
% ^^A % here's one for XeTeX.
% ^^A %
% ^^A % \begin{macro}{\ifxetex}
% ^^A % Checks if XeTeX is being used. We will simply require the \Lpack{ifxetex} package.
% ^^A % \changes{v1.61803}{2008/01/30}{Added checks for XeTeX (mempatch v4.9)}
% ^^A % \changes{v1.6180339}{2008/07/23}{Use ifxetex package if available}
% ^^A % \changes{v1.61803398d}{2009/12/01}{if \cs{ifxetex} is already
% ^^A % defined, e.g. using \cs{RequirePackage} before \cs{documentclass},
% ^^A % then using \cs{newif}\cs{ifxetex} will cause TeX to eat up a lot of
% ^^A % code. We fix this using a hint by Will Robertson.}
% ^^A % \changes{v3.7g}{2018/03/08}{As of 2018, we will no longer be
% ^^A % emulating \cs{if}\meta{engine} packages, you'll get an error if you
% ^^A % do not have them}
% ^^A %    \begin{macrocode}
% ^^A  % \RequirePackage{ifxetex}[2010/09/12]
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A %
% ^^A % \begin{macro}{\ifluatex}
% ^^A % Check if \texttt{luatex} is being used.  We will simply require the \Lpack{ifluatex} package.
% ^^A % \changes{v1.61803}{2008/01/30}{Added check for luatex}
% ^^A % \changes{v1.6180339}{2008/07/23}{Use an ifluatex package if available}
% ^^A % \changes{v1.6180339c}{2008/12/31}{It seems that Heiko Oberdiek has created an
% ^^A %           ifluatex package.}
% ^^A % \changes{v1.61803398d}{2009/12/01}{if \cs{ifluatex} is already
% ^^A % defined, e.g. using \cs{RequirePackage} before \cs{documentclass},
% ^^A % then using \cs{newif}\cs{ifluatex} will cause TeX to eat up a lot of
% ^^A % code. We fix this using a hint by Will Robertson.}
% ^^A % \changes{v3.7g}{2018/03/08}{As of 2018, we will no longer be
% ^^A % emulating \cs{if}\meta{engine} packages, you'll get an error if you
% ^^A % do not have them}
% ^^A %    \begin{macrocode}
% ^^A  % \RequirePackage{ifluatex}[2016/05/16]
% ^^A  % 
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A %
%
%
%
% \subsection{Extending an existing macro}
%
%
% My usual technique for modifying the code of an existing macro was
% to use \cs{renewcommand}. However it slowly became apparent that
% many of such modifications merely consisted of adding some code at
% either the start or end of the existing definition. In June 2000 I
% posed a question on the \texttt{comp.text.tex} newsgroup about this,
% and Michael Downes and Heiko Oberdiek were kind enough to respond.
% The responses arrived almost simultaneously, both supplying methods
% for adding code at the end of a macro defined to take one
% argument. Michael Downes' response included a remark about it
% probably being too much effort to formulate a general way of doing
% this.  Heiko Oberdiek almost immediately replied with such a
% generalisation.
%
%    The following code, which I have extracted from a package that I
% wrote but which I did not submit to CTAN, incorporates the work of both
% Michael and Heiko. I have added a bit. All errors are my responsibility.
% Michael went on the write the \Lpack{patchcmd} package which is
% a generalisation of the facilities below and so there was no need for
% my more restricted package.
% \changes{v0.33}{2001/08/31}{Replaced \cs{appendiarg} with \cs{addtodef}
%                             and friends}
%
% \begin{macro}{\wo@dmacro}
%    Heiko Oberdiek suggested\footnote{Via email on 2000/07/12.} that
% \meta{macro} should be tested for being the name of a macro, rather than
% using the normal \LaTeX{} test against it being undefined. He supplied
% the code for performing the macro name test.
%
% \cs{wo@dmacro} is a helper for handling the string `macro:'.
%    \begin{macrocode}
\edef\wo@dmacro{%
  \string m\string a\string c\string r\string o\string :%
}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\wo@difmacro@begingroup}
% This seems to take two arguments: 
% \cs{wo@difmacro@begingroup}\marg{macro}\marg{code}, where 
% \meta{macro} should be the name of a defined macro and \meta{code}
% is code to be executed if and only if \meta{macro} \emph{is} a
% defined macro.
%    \begin{macrocode}
\def\wo@difmacro@begingroup#1{%
%    \end{macrocode}
% Start a group.
%    \begin{macrocode}
  \begingroup
%    \end{macrocode}
% Test if \verb?#1? is a defined macro; \cs{wo@dparsemacro} does most of the work.
%    \begin{macrocode}
    \edef\x{%
      \noexpand\wo@dparsemacro\meaning#1\wo@dmacro\string -%
    }%
    \x\@nil{#1}%
}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\wo@dparsemacro}
% This is called by \cs{wo@difmacro@begingroup}. If \meta{macro} is not
% a defined macro it prints a warning and closes the group begun by
% \cs{wo@difmacro@begingroup}. Otherwise it process the \meta{code} which
% \emph{must} close the group.
%    \begin{macrocode}
\begingroup
  \edef\x{\endgroup
    \def\noexpand\wo@dparsemacro##1\wo@dmacro##2\string -}%
\x#3\@nil#4{%
  \ifx\\#3\\%
    \endgroup
    \@memwarn{\string `\string #4\string ' is not a macro}%
    \expandafter\@gobble
  \else
    \expandafter\@firstofone
  \fi
}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\addtodef}
% \begin{macro}{\addtodef*}
% \begin{macro}{\wo@daddtodef}
% The command \cs{addtodef}\marg{macro}\marg{start-stuff}\marg{end-stuff}
% adds stuff at the start and/or end of an argumentless  macro. 
% Initially the code for appending was a reimplementation of the
% kernel \cs{g@addto@macro} command (from \file{ltclass.dtx}).
% Later, at Michael Downes' suggestion, I combined
% appending and prepending stuff into a single command. 
% Actually, there is no real need to have both
% \cs{addtodef} and \cs{addtodef*} as the body of the command
% being amended has no argument,
% but both versions are provided for consistency.
%
%    The kernel \cs{@star@or@long} and \cs{l@ngrel@x} commands 
% (in \file{ltdefns.dtx}) are used to handle 
% the potential \verb?*? after the command name.
% \changes{v3.8.3}{2024/02/01}{Marked \cs{addtodef(*)} as deprecated}
% \MarkedForDeprecation{\cs{addtodef(*)}}
%    \begin{macrocode}
\def\addtodef{%
   \MarkDeprecated{\addtodef}{in 2026, use instead \string\patchcmd,\MessageBreak%
   \string\pretocmd\space or \string\apptocmd\space from the etoolbox package\MessageBreak%
   (which is autoloaded by the class)}
  \@star@or@long\wo@daddtodef}
%    \end{macrocode}
% The \cs{@star@or@long} command dealt with a possible \verb?*? and now
% \cs{wo@daddtodef} does the work. It picks up the three arguments
% that the user thinks belong to \cs{addtodef}, namely \meta{macro},
% \meta{start-stuff} and \meta{end-stuff}.
%    \begin{macrocode}
\long\def\wo@daddtodef#1#2#3{%
%    \end{macrocode}
% Check if \meta{macro} has been defined. 
%    \begin{macrocode}
  \wo@difmacro@begingroup{#1}{%
%    \end{macrocode}
% If \meta{macro} is defined then store the tokens corresponding to the 
% body of \meta{macro} and the extra \meta{-stuff} in token registers.
%    \begin{macrocode}
    \@temptokena{#2}%
    \toks@\expandafter{#1#3}%
%    \end{macrocode}
% Do an expanded definition for \cs{x}, so that calling \cs{x}
% will \cs{def} a new version of \meta{macro}, whose body consists of the
% saved tokens (i.e., the orginal body plus the extra stuff). 
% As Michael Downes noted, single letter control sequences do not take any of
% \TeX's hash table space.
% \cs{l@ngrel@x}
% has been previously set to either \cs{long} or \cs{relax} by \cs{@star@or@long},
% and so may make the new definition of \meta{macro} to be \cs{long}. 
%    \begin{macrocode}
    \edef\x{\endgroup 
         \l@ngrel@x\def\noexpand#1{\the\@temptokena \the\toks@}}%
%    \end{macrocode}
% Finally, call \cs{x} to perform the new definition.
%    \begin{macrocode}
    \x
  }%
}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\addtoiargdef}
% \begin{macro}{\addtoiargdef*}
% \begin{macro}{\wo@daddtoiargdef}
%  This adds stuff at the start and/or end of a macro that takes one argument.
% It is a modification of Michael Downes' appending 
% code\footnote{Posted to \ctt{} on 15~June 2000,\\
% URL: \url{http://www.dejanews.com/getdoc.xp?AN=635057844}.}
% which was:
% \begin{small}\begin{verbatim}
% \def\appendef#1#2{%
%   \begingroup
%     \toks@\expandafter{#1{##1}#2}%
%     \edef\x{\endgroup \def\noexpand#1####1{\the\toks@}}%
%   \x}
% \end{verbatim}
% \par\end{small}
%
% \changes{v3.8.3}{2024/02/01}{Marked \cs{addtoiargdef(*)} as deprecated}
% \MarkedForDeprecation{\cs{addtoiargdef(*)}}
%    \begin{macrocode}
\def\addtoiargdef{%
   \MarkDeprecated{\addtoiargdef}{in 2026, use instead \string\patchcmd,\MessageBreak%
   \string\pretocmd\space or \string\apptocmd\space from the etoolbox package\MessageBreak%
   (which is autoloaded by the class)}
  \@star@or@long\wo@daddtoiargdef}
\long\def\wo@daddtoiargdef#1#2#3{%
  \wo@difmacro@begingroup{#1}{%
    \@temptokena{#2}%
    \toks@\expandafter{#1{##1}#3}%
    \edef\x{\endgroup 
       \l@ngrel@x\def\noexpand#1####1{\the\@temptokena \the\toks@}}%
    \x
  }%
}

%    \end{macrocode}
%    For the record, Heiko Oberdiek produced the following 
% version\footnote{Posted to \ctt{} on 16~June 2000,\\
% URL: \url{http://www.dejanews.com/getdoc.xp?AN=635095381}.}
% which avoids the use of a token register.
% \begin{small}\begin{verbatim}
% \newcommand{\appendiargdef}[2]{%
%   \long\expandafter\def\expandafter#1\expandafter
%   ##\expandafter1\expandafter{#1{##1}#2}}
% \end{verbatim}
% \par\end{small}
%
% \end{macro}
% \end{macro}
% \end{macro}
%
% Continuing the saga, Michael came up with a pretty general solution for
% modifying a macro with any number (up to 9) of arguments which he
% sent to me on 2000/07/13; this became
% the \Lpack{patchcmd} package which is on CTAN. I'm sure that Michael 
% would have given me permission to include it here if he had not tragically
% passed away in 2003. I miss his encouragement, advice, and skills.
%
% \begin{macro}{\patchcommand}
% \cs{patchcommand}\marg{macro}\marg{start-stuff}\marg{end-stuff} inserts
% \meta{start-stuff} at the beginning of the definition of \meta{macro}
% and \meta{end-stuff} at the end of the definition. \meta{macro}
% can have 0--9 arguments and be defined by \cs{newcommand} (and associates)
% or with \cs{DeclareRobustCommand}. For macros that use \cs{futurelet}
% (e.g., those with starred forms or optional arguments) only prepending
% works --- any non-empty \meta{end-stuff} will mess things up. \cs{patchcommand}
% does not work with macros that have delimited arguments.
% \changes{v1.618}{2005/09/05}{Added \cs{patchcmd}}
% \changes{v3.8.3}{2024/02/01}{Marked \cs{patchcommand} as deprecated}
% \MarkedForDeprecation{\cs{patchcommand}}
%    \begin{macrocode}
%%%%%%%%%%%%%%%% Michael Downes' patchcmd 2000/07/31 v1.03 %%%%%%%%
\newcommand{\patchcommand}[1]{%
  \MarkDeprecated{\patchcommand}{in 2026, use instead \string\patchcmd,\MessageBreak%
    \string\pretocmd\space or \string\apptocmd\space from the etoolbox package\MessageBreak%
    (which is autoloaded by the class)}
  \expandafter\patchcmd@a\meaning#1??->@\@nil#1%
}
%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\patchcmd@a}
%    \begin{macrocode}
\long\def\patchcmd@a#1#2#3->#4#5\@nil#6{%
  \ifx @#4\relax \patchcmdError#6#1%
    \expandafter\@gobbletwo % discard the other two arguments
  \else
    \if l#2\toks@{\patchcmd@e{}#6}% l in this position means \long
    \else \toks@{\patchcmd@e*#6}%   not \long
    \fi
    \patchcmd@b #3@#4#5 ? ? ? \@nil#6%
    \expandafter\the\expandafter\toks@
  \fi}
%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\patchcmd@b}
%    \begin{macrocode}
\def\patchcmd@b#1:#2@#3#4 #5#6 #7 #8\@nil#9{%
  \if \ifx @#7@\expandafter
      \ifx\csname #6\endcsname#9T\else F\fi\else F\fi T%
    \toks@\expandafter{\expandafter\patchcommand\csname #6 \endcsname}%
  \else
    \ifx @#2@% No arguments
      \toks@\expandafter{\the\toks@ 0}%
    \else
      \patchcmd@c 0#2{\string##}0%
    \fi
  \fi}
%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\patchcmd@c}
%    \begin{macrocode}
\def\patchcmd@c#1#2#3{%
  \if\string###2%      % yes it's a # token
    \ifodd 0#31 % and it's followed by a number
      \if 0#3\patchcmd@d#1\fi % number=0? then we're done
    \else \patchcmd@d D% # not a number: must be a delimited arg
    \fi
  \else \patchcmd@d D% not a # token: must be a delmited arg
  \fi
  \patchcmd@c#3}
%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\patchcmd@d}
%    \begin{macrocode}
\def\patchcmd@d#1{%
  \if D#1%
%%%    \PackageError{patchcmd}{Cannot change a macro that has
%%%      delimited arguments}\@ehd
    \@memerror{%
      Cannot change a macro that has delimited arguments}{\@ehd}
  \else
    \toks@\expandafter{\the\toks@ #1}%
  \fi
  \begingroup
  \aftergroup\@gobble
  \let\patchcmd@c\endgroup}
%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\patchcmd@e}
%    \begin{macrocode}
\def\patchcmd@e#1#2#3#4#5{%
  \begingroup
  \edef\@##1{%
    \@temptokena\noexpand\expandafter{%
      \noexpand#2%
        \ifnum#3>0 {####1}\ifnum#3>1 {####2}\ifnum#3>2 {####3}%
        \ifnum#3>3 {####4}\ifnum#3>4 {####5}\ifnum#3>5 {####6}%
        \ifnum#3>6 {####7}\ifnum#3>7 {####8}\ifnum#3>8 {####9}%
        \fi\fi\fi\fi\fi\fi\fi\fi\fi
      ##1%
    }%
  }
  \@{#5}%
  \edef\@##1{\endgroup
    \noexpand\renewcommand#1\noexpand#2\ifcase#3 \else [#3]\fi
    {##1\the\@temptokena}}%
  \@{#4}%
}
%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\patchcmdError}
%    \begin{macrocode}
\long\def\patchcmdError#1#2{%
  \begingroup
  \toks@{Not redefinable}%
  \ifcat\relax\noexpand#1% Is it a control sequence?
    \begingroup
    \let#1=?\ifx ?\relax % Is it "\relax"?
      \endgroup % accept current value of \toks@
    \else \endgroup
      \if\ifx\relax#1u\else #2\fi u%
        \toks@{Not defined}%
      \fi
    \fi
  \fi
  \edef\@{\endgroup
%%%    \noexpand\PackageError{patchcmd}{%
%%%      \the\toks@: \string#1}\noexpand\@ehd}%
    \noexpand\@memerror{%
      \the\toks@: \string#1}\noexpand\@ehd}%
  \@}

%%%%%%%%%%%%%%%%%%%%% end of patchcmd code %%%%%%%%%%%%%%%%%%%%%%%%%%%

%    \end{macrocode}
% \end{macro}
% 
% Prevent later loading of the original \Lpack{patchcmd} package.
%    \begin{macrocode}
%%\@memfakeusepackage{patchcmd}

%    \end{macrocode}
% 
% \changes{v1.61803398}{2009/07/18}{Added support for bidi}
% \subsection{Support for the bidi package (RTL typesetting)}
%
%   The \Lpack{bidi} package (system) enables bidirectional typesetting. 
% As part of
% being able to accomplish this it often needs to exchange, for example,
% \cs{leftskip} and \cs{rightskip} depending on whether it is setting
% left-to-right (LTR) or right-to-left (RTL). In the case of \Lpack{memoir}
% the initial \Lpack{bidi} system implementation used a \Lpack{bidimemoir} 
% class developed by Vafa Khalighi. Now, with Vafa's help, the necessary 
% changes have been incorporated in \Lpack{memoir}; the \Lpack{bidimemoir}
% class is no longer needed.
%
% \begin{macro}{\memRTLleftskip}
% \begin{macro}{\memRTLrightskip}
% \begin{macro}{\memRTLvleftskip}
% \begin{macro}{\memRTLvrightskip}
% \begin{macro}{\memRTLraggedright}
% \begin{macro}{\memRTLraggedleft}
% \begin{macro}{\memRTLmainraggedright}
% \begin{macro}{\memRTLmainraggedleft}
% These are the hooks required to support the \Lpack{bidi} package,
% plus some we added that \Lpack{bidi} can use. The idea behind the
% \cs{XmainraggedX} macros are documents fully in RTL mode, then it
% makes sense to have the raggedness of the header and footer
% reversed. By default they do what the normally do, but in main RTL
% mode, \Lpack{bidi} can redefine them to reverse the order of the
% headers, i.e. the `left' part of the header is typeset as the
% `right' part. 
% \changes{v3.6h}{2010/10/22}{Added \cs{mem@RTLmainraggedX} macros}
% \changes{v3.6k}{2011/06/24}{the \cs{mem@RTLvX} macros should point
% at \cs{vX} not \cs{X}}
%    \begin{macrocode}
\newcommand*{\memRTLleftskip}{\leftskip}
\newcommand*{\memRTLrightskip}{\rightskip}
\newcommand*{\memRTLvleftskip}{\vleftskip}
\newcommand*{\memRTLvrightskip}{\vrightskip}
\newcommand*{\memRTLraggedright}{\raggedright}
\newcommand*{\memRTLraggedleft}{\raggedleft}
\newcommand*{\memRTLmainraggedright}{\raggedright}
\newcommand*{\memRTLmainraggedleft}{\raggedleft}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% It is expected that the \Lpack{bidi} package will redefine these as:
% \begin{verbatim}
% \renewcommand*{\memRTLleftskip}{\if@RTL\rightskip\else\leftskip\fi}
% \renewcommand*{\memRTLrightskip}{\if@RTL\leftskip\else\rightskip\fi}
% \renewcommand*{\memRTLvleftskip}{\if@RTL\vrightskip\else\vleftskip\fi}
% \renewcommand*{\memRTLvrightskip}{\if@RTL\vleftskip\else\vrightskip\fi}
% \renewcommand*{\memRTLraggedright}{\if@RTL\raggedleft\else\raggedright\fi}
% \renewcommand*{\memRTLraggedleft}{\if@RTL\raggedright\else\raggedleft\fi}
% \renewcommand*{\memRTLmainraggedright}{\if@RTLmain\raggedleft\else\raggedright\fi}
% \renewcommand*{\memRTLmainraggedleft}{\if@RTLmain\raggedright\else\raggedleft\fi}
% \end{verbatim}
%
% \section{Declaration of Options} \label{sec:opt}
%
% \changes{v3.8}{2023/08/03}{Added secret option}
%    \begin{macrocode}
 % secret extra option for testing stuff in the wild
 % caution 1: patching inside \ifmem@devmode ... \fi requires that all
 % if statements in the patch are blanced
 % caution 2: pathing inside \mem@devmode@run{ ... }{} does not work
 % if the search pattern contains #<num>
 % thus added both variants
\newif\ifmem@devmode
\let\mem@devmode@run\@secondoftwo
\DeclareOption{dev-mode}{\let\mem@devmode@run\@firstoftwo\mem@devmodetrue}

%    \end{macrocode}
%
% \subsection{Setting Paper Sizes}
%
%    The variables \cs{paperheight} and \cs{paperwidth} should reflect the
%    physical paper size after trimming. 
%
%    Option \Lopt{letterpaper} will be the default.
%
% \begin{macro}{\stockheight}
% \begin{macro}{\stockwidth}
% \begin{macro}{\trimtop}
% \begin{macro}{\trimedge}
% The lengths \cs{stockheight} and \cs{stockwidth} should be the height and 
% width of the stock sheet before trimming. For example, this is the 
% physical size
% of a single sheet that might be laser-printed. The lengths \cs{trimtop}
% and \cs{trimedge} are the amount that will be trimmed off the top and fore
% edge of the physical sheet.
% For desk printer output the size of the trimmed sheet is often the
% same as the physical sheet. In other words the \cs{paper...} and \cs{stock...}
% sizes are the same and the trims are zero. This class assumes that this
% is the normal case.
% \changes{v3.7.19}{2022/10/28}{\cs{stockheight} and \cs{stockwidth}
% may now be defined in the kernel, so we test for that}
%    \begin{macrocode}
\@ifundefined{stockwidth}{\newdimen{\stockheight}}{}
\@ifundefined{stockwidth}{\newdimen{\stockwidth}}{}
\newlength{\trimtop}
\newlength{\trimedge}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% The class provides an extended range of stock sizes. It may be useful at some
% point to have macros for these.
%
% \begin{macro}{\stockdbill}
% \begin{macro}{\stockstatement}
% \begin{macro}{\stockexecutive}
% \begin{macro}{\stockletter}
% \begin{macro}{\stockold}
% \begin{macro}{\stocklegal}
% \begin{macro}{\stockledger}
% \begin{macro}{\stockbroadsheet}
% US stock sizes.
% \changes{v1.61803}{2008/01/30}{Major expansion of stock size options}
%    \begin{macrocode}
\newcommand*{\stockdbill}     {\stockheight=7in    \stockwidth=3in}
\newcommand*{\stockstatement} {\stockheight=8.5in  \stockwidth=5.5in}
\newcommand*{\stockexecutive} {\stockheight=10.5in \stockwidth=7.25in}
\newcommand*{\stockletter}    {\stockheight=11in   \stockwidth=8.5in}
\newcommand*{\stockold}       {\stockheight=12in   \stockwidth=9in}
\newcommand*{\stocklegal}     {\stockheight=14in   \stockwidth=8.5in}
\newcommand*{\stockledger}    {\stockheight=17in   \stockwidth=11in}
\newcommand*{\stockbroadsheet}{\stockheight=22in   \stockwidth=17in}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\stockpottvo}
% \begin{macro}{\stockfoolscapvo}
% \begin{macro}{\stockcrownvo}
% \begin{macro}{\stockpostvo}
% \begin{macro}{\stocklargecrownvo}
% \begin{macro}{\stocklargepostvo}
% \begin{macro}{\stocksmalldemyvo}
% Traditional British octavo sizes.
%    \begin{macrocode}
\newcommand*{\stockpottvo}      {\stockheight=6.25in \stockwidth=4in}
\newcommand*{\stockfoolscapvo}  {\stockheight=6.75in \stockwidth=4.25in}
\newcommand*{\stockcrownvo}     {\stockheight=7.5in  \stockwidth=5in}
\newcommand*{\stockpostvo}      {\stockheight=8in    \stockwidth=5in}
\newcommand*{\stocklargecrownvo}{\stockheight=8in    \stockwidth=5.25in}
\newcommand*{\stocklargepostvo} {\stockheight=8.25in \stockwidth=5.25in}
\newcommand*{\stocksmalldemyvo} {\stockheight=8.5in  \stockwidth=5.675in}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\stockdemyvo}
% \begin{macro}{\stockmediumvo}
% \begin{macro}{\stocksmallroyalvo}
% \begin{macro}{\stockroyalvo}
% \begin{macro}{\stocksuperroyalvo}
% \begin{macro}{\stockimperialvo}
%    \begin{macrocode}
\newcommand*{\stockdemyvo}      {\stockheight=8.75in  \stockwidth=5.675in}
\newcommand*{\stockmediumvo}    {\stockheight=9in     \stockwidth=5.75in}
\newcommand*{\stocksmallroyalvo}{\stockheight=9.25in  \stockwidth=6.175in}
\newcommand*{\stockroyalvo}     {\stockheight=10in    \stockwidth=6.25in}
\newcommand*{\stocksuperroyalvo}{\stockheight=10.25in \stockwidth=6.75in}
\newcommand*{\stockimperialvo}  {\stockheight=11in    \stockwidth=7.5in}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% 
% \begin{macro}{\stockmcrownvo}
% \begin{macro}{\stockmlargecrownvo}
% \begin{macro}{\stockmdemyvo}
% \begin{macro}{\stockmsmallroyalvo}
% Metric stock sizes.
%    \begin{macrocode}
\newcommand*{\stockmcrownvo}      {\stockheight=186mm \stockwidth=123mm}
\newcommand*{\stockmlargecrownvo} {\stockheight=198mm \stockwidth=129mm}
\newcommand*{\stockmdemyvo}       {\stockheight=216mm \stockwidth=138mm}
\newcommand*{\stockmsmallroyalvo} {\stockheight=234mm \stockwidth=156mm}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\stockao}
% \begin{macro}{\stockai}
% \begin{macro}{\stockaii}
% \begin{macro}{\stockaiii}
% \begin{macro}{\stockaiv}
% \begin{macro}{\stockav}
% \begin{macro}{\stockavi}
% \begin{macro}{\stockavii}
% The A series, A0 --- A7.
% \changes{v1.6180339c}{2008/12/26}{Extended the A and B stock/paper size
%     seies with A/B0 through A/B6}
% \changes{v3.7i}{2019/11/04}{Added A7 stock}
%    \begin{macrocode}
\newcommand*{\stockao}  {\stockheight=1189mm \stockwidth=841mm}
\newcommand*{\stockai}  {\stockheight=841mm \stockwidth=594mm}
\newcommand*{\stockaii} {\stockheight=594mm \stockwidth=420mm}
\newcommand*{\stockaiii}{\stockheight=420mm \stockwidth=297mm}
\newcommand*{\stockaiv} {\stockheight=297mm \stockwidth=210mm}
\newcommand*{\stockav}  {\stockheight=210mm \stockwidth=148mm}
\newcommand*{\stockavi} {\stockheight=148mm \stockwidth=105mm}
\newcommand*{\stockavii}{\stockheight=105mm \stockwidth=74mm}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\stockbo}
% \begin{macro}{\stockbi}
% \begin{macro}{\stockbii}
% \begin{macro}{\stockbiii}
% \begin{macro}{\stockbiv}
% \begin{macro}{\stockbv}
% \begin{macro}{\stockbvi}
% \begin{macro}{\stockbvii}
% The B series, B0 --- B7.
% \changes{v3.7i}{2019/11/04}{added B7 stock}
%    \begin{macrocode}
\newcommand*{\stockbo}  {\stockheight=1414mm \stockwidth=1000mm}
\newcommand*{\stockbi}  {\stockheight=1000mm \stockwidth=707mm}
\newcommand*{\stockbii} {\stockheight=707mm \stockwidth=500mm}
\newcommand*{\stockbiii}{\stockheight=500mm \stockwidth=353mm}
\newcommand*{\stockbiv} {\stockheight=353mm \stockwidth=250mm}
\newcommand*{\stockbv}  {\stockheight=250mm \stockwidth=176mm}
\newcommand*{\stockbvi} {\stockheight=176mm \stockwidth=125mm}
\newcommand*{\stockbvii}{\stockheight=125mm \stockwidth=88mm}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%    It will be useful also to provide macros that set the page sizes.
%
% \begin{macro}{\pagedbill}
% \begin{macro}{\pagestatement}
% \begin{macro}{\pageexecutive}
% \begin{macro}{\pageletter}
% \begin{macro}{\pageold}
% \begin{macro}{\pagelegal}
% \begin{macro}{\pageledger}
% \begin{macro}{\pagebroadsheet}
% \changes{v1.6180339c}{\cs{pageheight} and \cs{pagewidth} should be
%                       \cs{paperheight} and \cs{paperwidth}
%                       (courtesy Wilhelm Muller)}
% US page sizes.
%    \begin{macrocode}
\newcommand*{\pagedbill}     {\paperheight=7in    \paperwidth=3in}
\newcommand*{\pagestatement} {\paperheight=8.5in  \paperwidth=5.5in}
\newcommand*{\pageexecutive} {\paperheight=10.5in \paperwidth=7.25in}
\newcommand*{\pageletter}    {\paperheight=11in   \paperwidth=8.5in}
\newcommand*{\pageold}       {\paperheight=12in   \paperwidth=9in}
\newcommand*{\pagelegal}     {\paperheight=14in   \paperwidth=8.5in}
\newcommand*{\pageledger}    {\paperheight=17in   \paperwidth=11in}
\newcommand*{\pagebroadsheet}{\paperheight=22in   \paperwidth=17in}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% 
% \begin{macro}{\pagepottvo}
% \begin{macro}{\pagefoolscapvo}
% \begin{macro}{\pagecrownvo}
% \begin{macro}{\pagepostvo}
% \begin{macro}{\pagelargecrownvo}
% \begin{macro}{\pagelargepostvo}
% \begin{macro}{\pagesmalldemyvo}
% British traditional page sizes, octavo.
%    \begin{macrocode}
\newcommand*{\pagepottvo}      {\paperheight=6.25in \paperwidth=4in}
\newcommand*{\pagefoolscapvo}  {\paperheight=6.75in \paperwidth=4.25in}
\newcommand*{\pagecrownvo}     {\paperheight=7.5in  \paperwidth=5in}
\newcommand*{\pagepostvo}      {\paperheight=8in    \paperwidth=5in}
\newcommand*{\pagelargecrownvo}{\paperheight=8in    \paperwidth=5.25in}
\newcommand*{\pagelargepostvo} {\paperheight=8.25in \paperwidth=5.25in}
\newcommand*{\pagesmalldemyvo} {\paperheight=8.5in  \paperwidth=5.675in}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\pagedemyvo}
% \begin{macro}{\pagemediumvo}
% \begin{macro}{\pagesmallroyalvo}
% \begin{macro}{\pageroyalvo}
% \begin{macro}{\pagesuperroyalvo}
% \begin{macro}{\pageimperialvo}
%    \begin{macrocode}
\newcommand*{\pagedemyvo}      {\paperheight=8.75in  \paperwidth=5.675in}
\newcommand*{\pagemediumvo}    {\paperheight=9in     \paperwidth=5.75in}
\newcommand*{\pagesmallroyalvo}{\paperheight=9.25in  \paperwidth=6.175in}
\newcommand*{\pageroyalvo}     {\paperheight=10in    \paperwidth=6.25in}
\newcommand*{\pagesuperroyalvo}{\paperheight=10.25in \paperwidth=6.75in}
\newcommand*{\pageimperialvo}  {\paperheight=11in    \paperwidth=7.5in}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% 
% \begin{macro}{\pagemcrownvo}
% \begin{macro}{\pagemlargecrownvo}
% \begin{macro}{\pagemdemyvo}
% \begin{macro}{\pagemsmallroyalvo}
% Metric sizes.
%    \begin{macrocode}
\newcommand*{\pagemcrownvo}      {\paperheight=186mm \paperwidth=123mm}
\newcommand*{\pagemlargecrownvo} {\paperheight=198mm \paperwidth=129mm}
\newcommand*{\pagemdemyvo}       {\paperheight=216mm \paperwidth=138mm}
\newcommand*{\pagemsmallroyalvo} {\paperheight=234mm \paperwidth=156mm}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\pageao}
% \begin{macro}{\pageai}
% \begin{macro}{\pageaii}
% \begin{macro}{\pageaiii}
% \begin{macro}{\pageaiv}
% \begin{macro}{\pageav}
% \begin{macro}{\pageavi}
% \begin{macro}{\pageavii}
% The A series, A0 --- A7.
% \changes{v3.7i}{2019/11/04}{added A7 paper}
%    \begin{macrocode}
\newcommand*{\pageao}  {\paperheight=1189mm \paperwidth=841mm}
\newcommand*{\pageai}  {\paperheight=841mm \paperwidth=594mm}
\newcommand*{\pageaii} {\paperheight=594mm \paperwidth=420mm}
\newcommand*{\pageaiii}{\paperheight=420mm \paperwidth=297mm}
\newcommand*{\pageaiv} {\paperheight=297mm \paperwidth=210mm}
\newcommand*{\pageav}  {\paperheight=210mm \paperwidth=148mm}
\newcommand*{\pageavi} {\paperheight=148mm \paperwidth=105mm}
\newcommand*{\pageavii}{\paperheight=105mm \paperwidth=74mm}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\pagebo}
% \begin{macro}{\pagebi}
% \begin{macro}{\pagebii}
% \begin{macro}{\pagebiii}
% \begin{macro}{\pagebiv}
% \begin{macro}{\pagebv}
% \begin{macro}{\pagebvi}
% \begin{macro}{\pagebvii}
% The B series, B0 --- B7.
% \changes{v3.7i}{2019/11/04}{Added B7 paper}
%    \begin{macrocode}
\newcommand*{\pagebo}  {\paperheight=1414mm \paperwidth=1000mm}
\newcommand*{\pagebi}  {\paperheight=1000mm \paperwidth=707mm}
\newcommand*{\pagebii} {\paperheight=707mm \paperwidth=500mm}
\newcommand*{\pagebiii}{\paperheight=500mm \paperwidth=353mm}
\newcommand*{\pagebiv} {\paperheight=353mm \paperwidth=250mm}
\newcommand*{\pagebv}  {\paperheight=250mm \paperwidth=176mm}
\newcommand*{\pagebvi} {\paperheight=176mm \paperwidth=125mm}
\newcommand*{\pagebvii}{\paperheight=125mm \paperwidth=88mm}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%    Declare the stock size options.
%
% Metric paper stock sizes.
% \changes{v1.6180339c}{2008/12/26}{Extended class options to include stock
%                       sizes A0, A1, A2, B0, B1 and B2}
% \changes{v3.7i}{2019/11/04}{Added a7paper and b7paper options}
%    \begin{macrocode}
\DeclareOption{a0paper}{\stockao}
\DeclareOption{a1paper}{\stockai}
\DeclareOption{a2paper}{\stockaii}
\DeclareOption{a3paper}{\stockaiii}
\DeclareOption{a4paper}{\stockaiv}
\DeclareOption{a5paper}{\stockav}
\DeclareOption{a6paper}{\stockavi}
\DeclareOption{a7paper}{\stockavii}
\DeclareOption{b0paper}{\stockbo}
\DeclareOption{b1paper}{\stockbi}
\DeclareOption{b2paper}{\stockbii}
\DeclareOption{b3paper}{\stockbiii}
\DeclareOption{b4paper}{\stockbiv}
\DeclareOption{b5paper}{\stockbv}
\DeclareOption{b6paper}{\stockbvi}
\DeclareOption{b7paper}{\stockbvii}
\DeclareOption{mcrownvopaper}{\stockmcrownvo}
\DeclareOption{mlargecrownvopaper}{\stockmlargecrownvo}
\DeclareOption{mdemyvopaper}{\stockmdemyvo}
\DeclareOption{msmallroyalvopaper}{\stockmsmallroyalvo}

%    \end{macrocode}
% US paper stock sizes.
%    \begin{macrocode}
\DeclareOption{dbillpaper}{\stockdbill}
\DeclareOption{statementpaper}{\stockstatement}
\DeclareOption{executivepaper}{\stockexecutive}
\DeclareOption{letterpaper}{\stockletter}
\DeclareOption{oldpaper}{\stockold}
\DeclareOption{legalpaper}{\stocklegal}
\DeclareOption{ledgerpaper}{\stockledger}
\DeclareOption{broadsheetpaper}{\stockbroadsheet}

%    \end{macrocode}
% British octavo stock paper sizes.
%    \begin{macrocode}
\DeclareOption{pottvopaper}{\stockpottvo}
\DeclareOption{foolscapvopaper}{\stockfoolscapvo}
\DeclareOption{crownvopaper}{\stockcrownvo}
\DeclareOption{postvopaper}{\stockpostvo}
\DeclareOption{largecrownvopaper}{\stocklargecrownvo}
\DeclareOption{largepostvopaper}{\stocklargepostvo}
\DeclareOption{smalldemyvopaper}{\stocksmalldemyvo}
\DeclareOption{demyvopaper}{\stockdemyvo}
\DeclareOption{mediumvopaper}{\stockmediumvo}
\DeclareOption{smallroyalvopaper}{\stocksmallroyalvo}
\DeclareOption{royalvopaper}{\stockroyalvo}
\DeclareOption{superroyalvopaper}{\stocksuperroyalvo}
\DeclareOption{imperialvopaper}{\stockimperialvo}

%    \end{macrocode}
% Ebook.
%    \begin{macrocode}
\DeclareOption{ebook}
   {\setlength\stockheight {9in}%
    \setlength\stockwidth  {6in}}

%    \end{macrocode}
%
%    The \Lopt{landscape} option switches the values of the height and width,
% assuming that the dimensions were originally given for portrait 
% orientation. (At the suggestion of Wilhelm M\"{u}ller made this independent
% of the option sequence).
% \changes{v1.6180339c}{2008/12/26}{`Stabilised' the landscape option and
%                      added a portrait option}.
% \begin{macro}{\ifmemlandscape}
% \begin{macro}{\memlandscapetrue}
% \begin{macro}{\memlandscapefalse}
%    \begin{macrocode}
\newif\ifmemlandscape
  \memlandscapefalse
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
%    \begin{macrocode}
\DeclareOption{landscape}{\memlandscapetrue}
\DeclareOption{portrait}{\memlandscapefalse}

%    \end{macrocode}
%
%
% \subsection{Choosing the type size}
%
%    The type size options are handled by defining \cs{@ptsize} to contain
%    the last digit of the size in question and branching on \cs{ifcase}
%    statements. This is done for historical reasons to stay compatible
%    with other packages that use the \cs{@ptsize} variable to select
%    special actions. It makes the declarations of size options less
%    than 10pt or more than 20pt difficult. In this class \texttt{9} is used 
%    for the \Lopt{9pt} option, assuming that the class will never define a 
%    \Lopt{19pt} option. For larger options the full complement of digits 
%    are used.
%
%    In any event, \cs{@memptsize} holds the complete size.
%
%    Option \Lopt{10pt} will be the default.
% \changes{v1.2}{2002/07/07}{Added 17pt option}
% \changes{v1.61803}{2008/01/30}{Added pt options 20 to 60.}
% \changes{v1.61803}{2008/01/30}{Used \cs{@memptsize}}
%    \begin{macrocode}
\renewcommand*{\@ptsize}{0}
\renewcommand*{\@memptsize}{10}
\DeclareOption{9pt}{\renewcommand*{\@ptsize}{9}\renewcommand*{\@memptsize}{9}}
\DeclareOption{10pt}{\renewcommand*{\@ptsize}{0}\renewcommand*{\@memptsize}{10}}
\DeclareOption{11pt}{\renewcommand*{\@ptsize}{1}\renewcommand*{\@memptsize}{11}}
\DeclareOption{12pt}{\renewcommand*{\@ptsize}{2}\renewcommand*{\@memptsize}{12}}
\DeclareOption{14pt}{\renewcommand*{\@ptsize}{4}\renewcommand*{\@memptsize}{14}}
\DeclareOption{17pt}{\renewcommand*{\@ptsize}{7}\renewcommand*{\@memptsize}{17}}
\DeclareOption{20pt}{\renewcommand*{\@ptsize}{20}\renewcommand*{\@memptsize}{20}}
\DeclareOption{25pt}{\renewcommand*{\@ptsize}{25}\renewcommand*{\@memptsize}{25}}
\DeclareOption{30pt}{\renewcommand*{\@ptsize}{30}\renewcommand*{\@memptsize}{30}}
\DeclareOption{36pt}{\renewcommand*{\@ptsize}{36}\renewcommand*{\@memptsize}{36}}
\DeclareOption{48pt}{\renewcommand*{\@ptsize}{48}\renewcommand*{\@memptsize}{48}}
\DeclareOption{60pt}{\renewcommand*{\@ptsize}{60}\renewcommand*{\@memptsize}{60}}

%    \end{macrocode}
%
% \begin{macro}{\if@nyptsizeopt}
% \begin{macro}{\@nyptsizeopttrue}
% \begin{macro}{\@nyptsizeoptfalse}
% \begin{macro}{\anyptfilebase}
% \begin{macro}{\anyptsize}
%   For any point size:
% \changes{v1.61803}{2008/02/29}{Added *pt option}
%    \begin{macrocode}
\newif\if@nyptsizeopt
  \@nyptsizeoptfalse
\providecommand*{\anyptfilebase}{mem}
\providecommand*{\anyptsize}{10}
\DeclareOption{*pt}{\@nyptsizeopttrue}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
%  \subsection{Two-side or one-side printing}
%
%    For two-sided printing we use the switch \cs{if@twoside}. In
%    addition we have to set the \cs{if@mparswitch} to get any margin
%    paragraphs into the outside margin. The default is \Lopt{twoside}.
% \begin{macro}{\if@twoside}
% \begin{macro}{\if@mparswitch}
%    \begin{macrocode}
\DeclareOption{twoside}{\@twosidetrue  \@mparswitchtrue}
\DeclareOption{oneside}{\@twosidefalse \@mparswitchfalse}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
%  \subsection{Two column printing}
%
%    Two-column and one-column printing is again realized via a switch
%    which is defined in the kernel. The default is single column printing.
%
% \begin{macro}{\if@twocolumn}
%    \begin{macrocode}
\DeclareOption{onecolumn}{\@twocolumnfalse}
\DeclareOption{twocolumn}{\@twocolumntrue}
%    \end{macrocode}
% \end{macro}
%
%
%  \subsection{The \Lopt{draft} option}
%
%    If the user requests \Lopt{draft} we show any overfull boxes,
%    marginal notes are allowed, and any copyright notices are not
%    printed. For symmetry, we also define a \Lopt{final} option
%    which is the default.
%
%    The user can use the \cs{ifdraftdoc} flag to add additional effects: \\
% \verb?\ifdraftdoc <additional code> \fi?
% \begin{macro}{\ifdraftdoc}
%    \begin{macrocode}
\newif\ifdraftdoc\draftdocfalse
\setlength{\overfullrule}{\z@}
\DeclareOption{final}{\setlength{\overfullrule}{\z@}
                      \draftdocfalse
                      \msdocfalse}
\DeclareOption{draft}{\setlength\overfullrule{5pt}%
                      \draftdoctrue
                      \msdocfalse}
%    \end{macrocode}
% \end{macro}
%
% \subsection{The \Lopt{ms} option}
%
% \begin{macro}{\ifmsdoc}
%    The \Lopt{ms} option makes the document look as though it was produced
% on a typewriter. We use a flag for remembering this. The user may also
% use the flag for specifying \Lopt{ms} effects.
%    \begin{macrocode}
\newif\ifmsdoc
  \msdocfalse
\DeclareOption{ms}{%
  \msdoctrue
  \draftdocfalse
  \setlength\overfullrule{\z@}
}

%    \end{macrocode}
% \end{macro}
%
% \subsection{The \Lopt{showtrims} option}
%
%    The \Lopt{showtrims} option will display crosses at the corners
% of the logical pages showing where the stock should be trimmed.
%
% \begin{macro}{\ifshowtrims}
%    \begin{macrocode}
\newif\ifshowtrims
  \showtrimsfalse
\DeclareOption{showtrims}{\showtrimstrue}

%    \end{macrocode}
% \end{macro}
%
% \subsection{The \Lopt{article} option}
%
%    The \Lopt{article} option typesets as a simulation of the
% \Lpack{article} class.
% \changes{v0.3}{2001/07/09}{Added article option}
% \begin{macro}{\ifartopt}
% \cs{ifartopt} is a flag (TRUE) if the \Lopt{article} option is called.
%    \begin{macrocode}
\newif\ifartopt
  \artoptfalse
\DeclareOption{article}{\artopttrue}

%    \end{macrocode}
% \end{macro}
%
% \subsection{The \Lopt{subfigure} option}
%
% The \Lopt{subfigure} option has been made a no-op since version 1.1
% and finally removed in version 1.61803. It was:
% \changes{v0.3}{2001/07/09}{Added subfigure option}
% \changes{v1.1}{2002/03/10}{Effectively removed subfigure option}
% \changes{v1.61803}{2008/01/30}{Removed subfigure option}
% \begin{verbatim}
% \DeclareOption{subfigure}{%
%   \ClassWarningNoLine{memoir}{The subfigure option is not required}}
% \end{verbatim}
%
% \subsection{The openright, openleft and openany options}
%
%    The \Lopt{openright} option specifies that Chapters must begin on 
% recto pages. The \Lopt{openleft} option specifies that Chapters
% must begin on verso pages and the \Lopt{openany} option lets Chapters 
% start on any page.
% \changes{v1.0}{2001/10/24}{Added the openleft option}
%    \begin{macrocode}
\DeclareOption{openright}{\@openrighttrue}
\DeclareOption{openany}{\@openrightfalse}
\DeclareOption{openleft}{\@openlefttrue}
%    \end{macrocode}
%
% \begin{macro}{\openright}
% \begin{macro}{\openany}
% \begin{macro}{\openleft}
% Commands that can be used to change the option in the middle of the 
% document\footnote{Openleft provided to meet a request by 
% Vladimir G.~Ivanovic  in September 2001.}.
%    \begin{macrocode}
\newcommand{\openright}{\@openrighttrue\@openleftfalse%
  \gdef\clearforchapter{\cleartorecto}}
\newcommand{\openany}{\@openrightfalse\@openleftfalse%
  \gdef\clearforchapter{\clearpage}}
\newcommand{\openleft}{\@openlefttrue
  \gdef\clearforchapter{\cleartoverso}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \subsection{Equation numbering on the left}
%
% The \Lopt{leqno} option prints equation numbers on the left. This
% is implemented via an external class option file.
%    \begin{macrocode}
\DeclareOption{leqno}{\input{leqno.clo}}
%    \end{macrocode}
%
% \subsection{Flush left math displays}
%
% The \Lopt{fleqn} option redefines the displayed math environments
% so that they are left adjusted with an indent of \cs{mathindent}
% from the current left margin. This
% is implemented via an external class option file.
%    \begin{macrocode}
\DeclareOption{fleqn}{\input{fleqn.clo}}
%    \end{macrocode}
%
% \subsection{Open bibliography}
%
% The \Lopt{openbib} option redefines the \verb?thebibliography? so that each
% block starts on a new line, and succeeding lines in a block are
% indented by \cs{bibindent}.
% \changes{v1.0a}{2001/11/28}{Replaced \cs{AtEndOfPackage} with \cs{AtEndOfClass}}
%    \begin{macrocode}
\DeclareOption{openbib}{%
  \AtEndOfClass{%
    \renewcommand\@openbib@code{%
      \advance\leftmargin\bibindent
      \itemindent -\bibindent
      \listparindent \itemindent
      \parsep \z@
     }%
    \renewcommand\newblock{\par}}}

%    \end{macrocode}
%
% \subsection{Old font commands}
%
% The \Lopt{oldfontcommands} option enables commands like \cs{bf} and friends.
% \changes{v1.0a}{2002/01/29}{Added the oldfontcommands option}
%    \begin{macrocode}
\DeclareOption{oldfontcommands}{\@memoldfonttrue}
%    \end{macrocode}
%
% \subsection{Extra font sizes}
%
% The \Lopt{extrafontsizes} options indicates that extended font sizes (above 25pt)
% are available.
% \changes{v1.61803}{2008/01/30}{Added extrafontsizes option.}
%    \begin{macrocode}
\DeclareOption{extrafontsizes}{\extrafontsizestrue}

%    \end{macrocode}
%
% \subsection{The \Lopt{fullptlayout} option}
% \changes{v3.7g}{2018/03/09}{Added the \Lopt{fullptlayout} option}
% \begin{macro}{\mem@settopoint}
% By default the class will truncate some layout lengths to a whole
% number of points.\footnote{Presumably because it looks better when
% the layout is written to the log.} This might not be desirable, so the
% \Lopt{fullptlayout} class option disables this truncation.
%    \begin{macrocode}
\newcommand\mem@settopoint[1]{\@settopoint{#1}}
\DeclareOption{fullptlayout}{\renewcommand\mem@settopoint{\@gobble}}

%    \end{macrocode}
% \end{macro}
%
%
%
% \section{Executing Options} \label{sec:xopt}
%
%    Here we execute the default options to initialize certain
%    variables. 
%    \begin{macrocode}
\ExecuteOptions{final,letterpaper,10pt,onecolumn,openright,twoside,
                portrait}
%    \end{macrocode}
%
%    The \cs{ProcessOptions} command causes the execution of the code
%    for every option \Lopt{foo}
%    which is declared and for which the user typed
%    the \Lopt{foo} option in his
%    \cs{documentclass} command.  For every option \Lopt{bar} he typed,
%    which is not declared, the option is assumed to be a global option.
%    All options will be passed as document options to any
%    \cs{usepackage} command in the document preamble.
%
% \cs{ProcessOptions*} processes the options in the order they are given
% in the \cs{documentclass} command, instead of the definition order.
% \changes{v1.6180339c}{2008/12/26}{Change \cs{ProcessOptions} to
%                       \cs{ProcessOptions*} and handle landscape/portrait 
%                       option after \cs{ProcessOptions*}}
%    \begin{macrocode}
\ProcessOptions*

%    \end{macrocode}
% Execute the delayed landscape switch if given
%    \begin{macrocode}
\ifmemlandscape
  \setlength\@tempdima  {\stockheight}
  \setlength\stockheight{\stockwidth}
  \setlength\stockwidth {\@tempdima}
\fi

%    \end{macrocode}

% \begin{macro}{\memoirpostopthook}
% A user could define this \emph{before} the \cs{documentclass} command
% to do something at this point. For example, to set up a new stock size: \\
% \verb?\def\memoirpostopthook{\stockheight=44in \stockwidth=34in}?
% \changes{v1.618033}{2008/06/02}{Added \cs{memoirpostopthook}}
%    \begin{macrocode}
\providecommand*{\memoirpostopthook}{}
  \memoirpostopthook

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\cleartorecto}
% A repeat of \cs{cleardoublepage}; clears to a recto (odd-numbered) page.
%    \begin{macrocode}
\def\cleartorecto{\clearpage\if@twoside \ifodd\c@page\else
  \hbox{}\thispagestyle{cleared}%
  \newpage\if@twocolumn\hbox{}\newpage\fi\fi\fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\cleartoverso}
% Clears to a verso (even-numbered) page.
%    \begin{macrocode}
\def\cleartoverso{\clearpage\if@twoside 
  \ifodd\c@page\hbox{}\thispagestyle{cleared}%
  \newpage\if@twocolumn\hbox{}\newpage\fi\fi\fi}

%    \end{macrocode}
% \end{macro}
%

%    Set the macro \cs{clearforchapter} according to the options (via
%    \cs{openleft}, \cs{openright} or \cs{openany} defined
%    earlier)
%    \begin{macrocode}
\if@openleft
  \openleft
\else
  \if@openright
    \openright
  \else
    \openany
  \fi
\fi

%    \end{macrocode}
%
% \begin{macro}{\@ivpt}
% \begin{macro}{\@xxxpt}
% \begin{macro}{\@xxxvipt}
% \begin{macro}{\@xlviiipt}
% \begin{macro}{\@lxpt}
% \begin{macro}{\@lxxiipt}
% \begin{macro}{\@lxxxivpt}
% \begin{macro}{\@xcvipt}
% \begin{macro}{\@cviiipt}
% \begin{macro}{\@cxxpt}
% \begin{macro}{\@cxxxiipt}
% \changes{v1.61803}{2008/01/30}{Added a bunch of \cs{@...pt} macros}
%    \begin{macrocode}
\newcommand*{\@ivpt}{4}
\newcommand*{\@xxxpt}{30}
\newcommand*{\@xxxvipt}{36}
\newcommand*{\@xlviiipt}{48}
\newcommand*{\@lxpt}{60}
\newcommand*{\@lxxiipt}{72}
\newcommand*{\@lxxxivpt}{84}
\newcommand*{\@xcvipt}{96}
\newcommand*{\@cviiipt}{108}
\newcommand*{\@cxxpt}{120}
\newcommand*{\@cxxxiipt}{132}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%  Now that all the options have been executed we can load the
%  chosen class option file that contains all size dependent code. The 
% larger sizes are only made available for the \Lopt{extrafontsizes} option.
%
% \begin{macro}{\memfontfamily}
% \begin{macro}{\memfontenc}
% \begin{macro}{\memfontpack}
%  The default font and coding as set by the kernel is \texttt{cmr} and
% \texttt{OT1} respectively, giving Knuth's original Computer Modern Roman
% font at a set of fixed sizes (maximum of 24.88pt). If we are to have
% any size font we have to go to a scaleable font. As the Latin Modern font
% is a scaleable version of Computer Modern, and all modern LaTeX distributions
% include it, I am using this by default. 
%
% By defining these three macros \emph{before}
% the \cs{documentclass} any other font and package can be used.
%    \begin{macrocode}
\providecommand*{\memfontfamily}{lmr}
\providecommand*{\memfontenc}{T1}
\providecommand*{\memfontpack}{lmodern}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% Deal with the `anyptsize' (\Lopt{*pt}) option first. In this case the macros
% \cs{anyptfilebase} and \cs{anyptsize} should have been defined by the
% author \emph{before} the \cs{documentclass} command, and a file \\
% \verb?\anyptfilebase\anyptsize.clo? should exist (if not the file will
% default to \verb?mem10.clo?).
% \changes{v1.61803}{2008/01/30}{Extended the loading of \texttt{.clo} files.}
%    \begin{macrocode}
\if@nyptsizeopt
  \newcommand*{\@nyptclofile}{\anyptfilebase\anyptsize.clo}
  \IfFileExists{\@nyptclofile}{\def\@memptsize{\anyptsize}}{%
    \@memerror{You have used the `*pt' option but \MessageBreak 
               file \@nyptclofile\space can't be found}%
              {I'll use mem10.clo instead}
    \renewcommand*{\@nyptclofile}{mem10.clo}%
    \def\@memptsize{10}%
  }
  \renewcommand*{\@ptsize}{\@memptsize}
  \usefont{\memfontenc}{\memfontfamily}{m}{n}
  \input{\@nyptclofile}
%    \end{macrocode}
% Packages in a class should be loaded via \cs{RequirePackage}. Also
% don't load \Lpack{fontenc} under Xe- or LuaLaTeX.
% \changes{v3.8.3}{2024/08/30}{Changed}
%    \begin{macrocode}
  \RequirePackage{\memfontpack}
  \iftutex\else
    \RequirePackage[\memfontenc]{fontenc}
  \fi
\else
%    \end{macrocode}
% Now for the fixed pt size options.
%    \begin{macrocode}
  \ifextrafontsizes
    \usefont{\memfontenc}{\memfontfamily}{m}{n}
    \input{mem\@memptsize.clo}
%    \end{macrocode}
% Packages in a class should be loaded via \cs{RequirePackage}. Also
% don't load \Lpack{fontenc} under Xe- or LuaLaTeX.
% \changes{v3.8.3}{2024/08/30}{Changed}
%    \begin{macrocode}
    \RequirePackage{\memfontpack}
    \iftutex\else
      \RequirePackage[\memfontenc]{fontenc}
    \fi
  \else
    \ifnum\@memptsize > 17\relax
      \@memerror{The `extrafontsizes' option is required to use \MessageBreak
                 the `\@memptsize pt' option}%
                {The 17pt option will be used instead}
      \input{mem17.clo}
    \else
      \ifnum\@ptsize = 9\relax
        \input{mem\@ptsize.clo}
      \else
        \input{mem1\@ptsize.clo}
      \fi
    \fi
  \fi
\fi

%</class>
%    \end{macrocode}
%
%
% \section{Fonts and spaces} \label{sec:docl}
% \label{sec:maincode}
%
%  In this section we deal with most of the aspects that are related
% to font sizes, and spacing that is related to the size of the body font.
%
% \subsection{Fonts}
%
%    \LaTeX\ offers the user commands to change the size of the font,
%    relative to the `main' size. Each relative size changing command
%    \cs{size} executes the command
%    \verb?\@setfontsize\size? \meta{font-size} \meta{baselineskip} where:
%
%    \begin{description}
%    \item[\meta{font-size}] The absolute size of the font to use from
%        now on.
%
%    \item[\meta{baselineskip}] The normal value of \cs{baselineskip}
%        for the size of the font selected. (The actual value will be
%        \cs{baselinestretch} * \meta{baselineskip}.)
%    \end{description}
%
%    A number of commands, defined in the \LaTeX\ kernel, shorten the
%    following  definitions and are used throughout. They are listed in 
% the first part of Table~\ref{tab:sh}. Those in the second part are introduced
% by the class.
%
% \begin{table}
% \centering
% \caption{Shorthand font point size commands}\label{tab:sh}
% \begin{tabular}{ll@{\qquad}ll@{\qquad}ll} \hline
%            &   &            &   & \cs{@ivpt}   & 4 \\
%  \cs{@vpt} & 5 & \cs{@vipt} & 6 & \cs{@viipt} & 7 \\
%  \cs{@viiipt} & 8 & \cs{@ixpt} & 9 & \cs{@xpt} & 10 \\
%  \cs{@xipt} & 10.95 & \cs{@xiipt} & 12 & \cs{@xivpt} & 14.4\\
%  \cs{@xviipt} & 17.28 & \cs{@xxpt} & 20.74 & \cs{@xxvpt} & 24.88\\ \hline
%  \cs{@xxxpt}  & 30    & \cs{@xxxvipt} & 36 & \cs{@xlviiipt} & 48 \\
%  \cs{@lxpt} & 60 & \cs{@lxxiipt} & 72 & \cs{@lxxxivpt} & 84 \\ 
%  \cs{@xcvipt} & 96 & \cs{@cviiipt} & 108 & \cs{@cxxpt} & 120 \\
%  \cs{@cxxxiipt} & 132 \\ \hline
%  \end{tabular}
%  \end{table}
%
% \begin{macro}{\normalsize}
% \begin{macro}{\@normalsize}
%
%    The user level command for the main size is \cs{normalsize}.
%    Internally \LaTeX\ uses \cs{@normalsize} when it refers to the
%    main size. \cs{@normalsize} will be defined to work like
%    \cs{normalsize} if the latter is redefined from its default
%    definition (that just issues an error message). Otherwise, in the standard
% classes \cs{@normalsize} simply selects a 10pt/12pt size, but here
% it selects among the wider range.
%
%    The \cs{normalsize} macro also sets new values for\\
%    \cs{abovedisplayskip}, \cs{abovedisplayshortskip} and
%    \cs{belowdisplayshortskip}.
%
% For the larger sizes I have set \cs{abovedisplayskip} to the font size
% and \cs{belowdisplayshortskip} to 0.5\cs{onelineskip}.
%
%    \begin{macrocode}
%<*9pt|10pt|11pt|12pt|14pt|17pt|20pt|25pt|30pt|36pt|48pt|60pt>
%    \end{macrocode}
% \changes{v0.11 (mem14.clo)}{2001/10/30}{Changed baseline skip from 17.28pt to 17.5pt}
% \changes{v1.61803}{2008/01/30}{Added files mem20.clo through mem60.clo}
% \changes{v1.61803}{2008/01/30}{Changed .clo files to accomodate \cs{extrafontsizes}}
%    \begin{macrocode}
\renewcommand{\normalsize}{%
%<*9pt>
   \@setfontsize\normalsize\@ixpt\@xpt
   \abovedisplayskip 9\p@ \@plus 2\p@ \@minus 4.5\p@
   \abovedisplayshortskip \z@ \@plus 3\p@
   \belowdisplayshortskip 5.5\p@ \@plus 2.5\p@ \@minus 3\p@
%</9pt>
%<*10pt>
   \@setfontsize\normalsize\@xpt\@xiipt
   \abovedisplayskip 10\p@ \@plus2\p@ \@minus5\p@
   \abovedisplayshortskip \z@ \@plus3\p@
   \belowdisplayshortskip 6\p@ \@plus3\p@ \@minus3\p@
%</10pt>
%<*11pt>
   \@setfontsize\normalsize\@xipt{13.6}%
   \abovedisplayskip 11\p@ \@plus3\p@ \@minus6\p@
   \abovedisplayshortskip \z@ \@plus3\p@
   \belowdisplayshortskip 6.5\p@ \@plus3.5\p@ \@minus3\p@
%</11pt>
%<*12pt>
   \@setfontsize\normalsize\@xiipt{14.5}%
   \abovedisplayskip 12\p@ \@plus3\p@ \@minus7\p@
   \abovedisplayshortskip \z@ \@plus3\p@
   \belowdisplayshortskip 6.5\p@ \@plus3.5\p@ \@minus3\p@
%</12pt>
%<*14pt>
   \@setfontsize\normalsize\@xivpt{17.5}%
   \abovedisplayskip 14\p@ \@plus3\p@ \@minus8\p@
   \abovedisplayshortskip \z@ \@plus3\p@
   \belowdisplayshortskip 7\p@ \@plus3.5\p@ \@minus3\p@
%</14pt>
%<*17pt>
   \@setfontsize\normalsize\@xviipt{22}%
   \abovedisplayskip 15\p@ \@plus4\p@ \@minus8\p@
   \abovedisplayshortskip \z@ \@plus4\p@
   \belowdisplayshortskip 8\p@ \@plus4\p@ \@minus3\p@
%</17pt>
%<*20pt>
   \@setfontsize\normalsize\@xxpt{25}%
   \abovedisplayskip 20\p@ \@plus5\p@ \@minus9\p@
   \abovedisplayshortskip \z@ \@plus5\p@
   \belowdisplayshortskip 12.5\p@ \@plus6\p@ \@minus3\p@
%</20pt>
%<*25pt>
   \@setfontsize\normalsize\@xxvpt{30}%
   \abovedisplayskip 25\p@ \@plus6\p@ \@minus10\p@
   \abovedisplayshortskip \z@ \@plus6\p@
   \belowdisplayshortskip 15\p@ \@plus7.5\p@ \@minus4\p@
%</25pt>
%<*30pt>
   \@setfontsize\normalsize\@xxxpt{37}%
   \abovedisplayskip 30\p@ \@plus7\p@ \@minus11\p@
   \abovedisplayshortskip \z@ \@plus7\p@
   \belowdisplayshortskip 18\p@ \@plus9\p@ \@minus4\p@
%</30pt>
%<*36pt>
   \@setfontsize\normalsize\@xxxvipt{45}%
   \abovedisplayskip 36\p@ \@plus8\p@ \@minus12\p@
   \abovedisplayshortskip \z@ \@plus8\p@
   \belowdisplayshortskip 22\p@ \@plus11\p@ \@minus5\p@
%</36pt>
%<*48pt>
   \@setfontsize\normalsize\@xlviiipt{60}%
   \abovedisplayskip 48\p@ \@plus9\p@ \@minus13\p@
   \abovedisplayshortskip \z@ \@plus9\p@
   \belowdisplayshortskip 30\p@ \@plus15\p@ \@minus7\p@
%</48pt>
%<*60pt>
   \@setfontsize\normalsize\@lxpt{72}%
   \abovedisplayskip 60\p@ \@plus10\p@ \@minus14\p@
   \abovedisplayshortskip \z@ \@plus10\p@
   \belowdisplayshortskip 36\p@ \@plus18\p@ \@minus9\p@
%</60pt>
%    \end{macrocode}
%    The \cs{belowdisplayskip} is always equal to the
%    \cs{abovedisplayskip}. The parameters of the first level list are
%    always given by \cs{@listI}.
%    \begin{macrocode}
   \belowdisplayskip \abovedisplayskip
   \let\@listi\@listI}
%    \end{macrocode}
%
%    We initially choose the normalsize font.
%    \begin{macrocode}
\normalsize
%    \end{macrocode}
% \changes{v3.7r}{2022/07/26}{Make \cs{normalsize} robust in the same
% manner as in \file{size10.clo}}
%    \begin{macrocode}
\ifx\MakeRobust\@undefined \else
    \MakeRobust\normalsize
\fi
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\small}
%    This code is similar to that for \cs{normalsize}.
% (Robert Schlicht via email on 2004/03/11
% noted that in some cases \% signs were missing after \verb?\@setfontsize?).
%
% For the larger sizes I have set \cs{topsep} to 2/3\cs{onelineskip}
% and \cs{parsep} to 1/2\cs{topsep}.
% \changes{v1.61}{2004/03/12}{Added missing percent signs to some uses of
%                             \cs{@setfontsize}}
% \changes{v3.7r}{2022/07/26}{Make robust}
%    \begin{macrocode}
\DeclareRobustCommand{\small}{%
%<*9pt>
    \@setfontsize\small\@viiipt{9.5}%
    \abovedisplayskip 6\p@ \@plus 2\p@ \@minus 4\p@
    \abovedisplayshortskip \z@ \@plus 2\p@
    \belowdisplayshortskip 4\p@ \@plus 2\p@ \@minus 2\p@
    \def\@listi{\leftmargin\leftmargini
                \topsep 2\p@ \@plus 2\p@ \@minus 2\p@
                \parsep 1\p@ \@plus\p@ \@minus\p@
                \itemsep \parsep
%%                \itemindent\z@
                }%
%</9pt>
%<*10pt>
   \@setfontsize\small\@ixpt{11}%
   \abovedisplayskip 8.5\p@ \@plus3\p@ \@minus4\p@
   \abovedisplayshortskip \z@ \@plus2\p@
   \belowdisplayshortskip 4\p@ \@plus2\p@ \@minus2\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 4\p@ \@plus2\p@ \@minus2\p@
               \parsep 2\p@ \@plus\p@ \@minus\p@
               \itemsep \parsep
%%               \itemindent\z@
              }%
%</10pt>
%<*11pt>
   \@setfontsize\small\@xpt\@xiipt
   \abovedisplayskip 10\p@ \@plus2\p@ \@minus5\p@
   \abovedisplayshortskip \z@ \@plus3\p@
   \belowdisplayshortskip 6\p@ \@plus3\p@ \@minus3\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 6\p@ \@plus2\p@ \@minus2\p@
               \parsep 3\p@ \@plus2\p@ \@minus\p@
               \itemsep \parsep
%%               \itemindent\z@
              }%
%</11pt>
%<*12pt>
   \@setfontsize\small\@xipt{13.6}%
   \abovedisplayskip 11\p@ \@plus3\p@ \@minus6\p@
   \abovedisplayshortskip \z@ \@plus3\p@
   \belowdisplayshortskip 6.5\p@ \@plus3.5\p@ \@minus3\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 9\p@ \@plus3\p@ \@minus5\p@
               \parsep 4.5\p@ \@plus2\p@ \@minus\p@
               \itemsep \parsep
%%               \itemindent\z@
              }%
%</12pt>
%<*14pt>
   \@setfontsize\small\@xiipt{14.5}%
   \abovedisplayskip 12\p@ \@plus3\p@ \@minus7\p@
   \abovedisplayshortskip \z@ \@plus3\p@
   \belowdisplayshortskip 6.5\p@ \@plus3.5\p@ \@minus3\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 11\p@ \@plus4\p@ \@minus6\p@
               \parsep 6\p@ \@plus3\p@ \@minus\p@
               \itemsep \parsep
%%               \itemindent\z@
              }%
%</14pt>
%<*17pt>
   \@setfontsize\small\@xivpt{17}%
   \abovedisplayskip 12\p@ \@plus3\p@ \@minus7\p@
   \abovedisplayshortskip \z@ \@plus3\p@
   \belowdisplayshortskip 7\p@ \@plus4\p@ \@minus3\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 11\p@ \@plus4\p@ \@minus6\p@
               \parsep 6\p@ \@plus3\p@ \@minus\p@
               \itemsep \parsep
%%               \itemindent\z@
              }%
%</17pt>
%<*20pt>
   \@setfontsize\small\@xviipt{22}%
   \abovedisplayskip 17\p@ \@plus4\p@ \@minus8\p@
   \abovedisplayshortskip \z@ \@plus4\p@
   \belowdisplayshortskip 11\p@ \@plus4\p@ \@minus3\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 14\p@ \@plus5\p@ \@minus7\p@
               \parsep 7\p@ \@plus2\p@ \@minus3\p@
               \itemsep \parsep}%
%</20pt>
%<*25pt>
   \@setfontsize\small\@xxpt{25}%
   \abovedisplayskip 20\p@ \@plus5\p@ \@minus9\p@
   \abovedisplayshortskip \z@ \@plus5\p@
   \belowdisplayshortskip 12.5\p@ \@plus6\p@ \@minus3\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 16\p@ \@plus5\p@ \@minus8\p@
               \parsep 8\p@ \@plus3\p@ \@minus4\p@
               \itemsep \parsep}%
%</25pt>
%<*30pt>
   \@setfontsize\small\@xxvpt{30}%
   \abovedisplayskip 25\p@ \@plus6\p@ \@minus10\p@
   \abovedisplayshortskip \z@ \@plus6\p@
   \belowdisplayshortskip 15\p@ \@plus7.5\p@ \@minus4\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 20\p@ \@plus7\p@ \@minus10\p@
               \parsep 10\p@ \@plus4\p@ \@minus5\p@
               \itemsep \parsep}%
%</30pt>
%<*36pt>
   \@setfontsize\small\@xxxpt{37}%
   \abovedisplayskip 30\p@ \@plus7\p@ \@minus11\p@
   \abovedisplayshortskip \z@ \@plus7\p@
   \belowdisplayshortskip 18\p@ \@plus9\p@ \@minus4\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 24\p@ \@plus8\p@ \@minus12\p@
               \parsep 12\p@ \@plus4\p@ \@minus6\p@
               \itemsep \parsep}%
%</36pt>
%<*48pt>
   \@setfontsize\small\@xxxvipt{45}%
   \abovedisplayskip 36\p@ \@plus8\p@ \@minus12\p@
   \abovedisplayshortskip \z@ \@plus8\p@
   \belowdisplayshortskip 22\p@ \@plus11\p@ \@minus5\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 30\p@ \@plus10\p@ \@minus15\p@
               \parsep 15\p@ \@plus5\p@ \@minus7\p@
               \itemsep \parsep}%
%</48pt>
%<*60pt>
   \@setfontsize\small\@xlviiipt{60}%
   \abovedisplayskip 48\p@ \@plus9\p@ \@minus13\p@
   \abovedisplayshortskip \z@ \@plus9\p@
   \belowdisplayshortskip 30\p@ \@plus15\p@ \@minus7\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 40\p@ \@plus13\p@ \@minus20\p@
               \parsep 20\p@ \@plus6\p@ \@minus10\p@
               \itemsep \parsep}%
%</60pt>
   \belowdisplayskip \abovedisplayskip
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\footnotesize}
%    This code is similar to that for \cs{small}.
% \changes{v3.7r}{2022/07/26}{Make robust}
%    \begin{macrocode}
\DeclareRobustCommand{\footnotesize}{%
%<*9pt>
    \@setfontsize\footnotesize\@viipt{8}%
    \abovedisplayskip 6\p@ \@plus 2\p@ \@minus 4\p@
    \abovedisplayshortskip \z@ \@plus 2\p@
    \belowdisplayshortskip 4\p@ \@plus 2\p@ \@minus 2\p@
    \def\@listi{\leftmargin\leftmargini
                \topsep 2\p@ \@plus 2\p@ \@minus 2\p@
                \parsep 1\p@ \@plus\p@ \@minus\p@
                \itemsep \parsep
%%                \itemindent\z@
               }%
%</9pt>
%<*10pt>
   \@setfontsize\footnotesize\@viiipt{9.5}%
   \abovedisplayskip 6\p@ \@plus2\p@ \@minus4\p@
   \abovedisplayshortskip \z@ \@plus\p@
   \belowdisplayshortskip 3\p@ \@plus\p@ \@minus2\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 3\p@ \@plus\p@ \@minus\p@
               \parsep 2\p@ \@plus\p@ \@minus\p@
               \itemsep \parsep
%%               \itemindent\z@
              }%
%</10pt>
%<*11pt>
   \@setfontsize\footnotesize\@ixpt{11}%
   \abovedisplayskip 8\p@ \@plus2\p@ \@minus4\p@
   \abovedisplayshortskip \z@ \@plus\p@
   \belowdisplayshortskip 4\p@ \@plus2\p@ \@minus2\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 4\p@ \@plus2\p@ \@minus2\p@
               \parsep 2\p@ \@plus\p@ \@minus\p@
               \itemsep \parsep
%%               \itemindent\z@
              }%
%</11pt>
%<*12pt>
   \@setfontsize\footnotesize\@xpt\@xiipt
   \abovedisplayskip 10\p@ \@plus2\p@ \@minus5\p@
   \abovedisplayshortskip \z@ \@plus3\p@
   \belowdisplayshortskip 6\p@ \@plus3\p@ \@minus3\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 6\p@ \@plus2\p@ \@minus2\p@
               \parsep 3\p@ \@plus2\p@ \@minus\p@
               \itemsep \parsep
%%               \itemindent\z@
              }%
%</12pt>
%<*14pt>
   \@setfontsize\footnotesize\@xipt{13.6}%
   \abovedisplayskip 11\p@ \@plus3\p@ \@minus6\p@
   \abovedisplayshortskip \z@ \@plus3\p@
   \belowdisplayshortskip 6.5\p@ \@plus3.5\p@ \@minus3\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 6.5\p@ \@plus3.5\p@ \@minus3\p@
               \parsep 4\p@ \@plus3\p@ \@minus\p@
               \itemsep \parsep
%%               \itemindent\z@
              }%
%</14pt>
%<*17pt>
   \@setfontsize\footnotesize\@xiipt{14}%
   \abovedisplayskip 12\p@ \@plus3\p@ \@minus7\p@
   \abovedisplayshortskip \z@ \@plus3\p@
   \belowdisplayshortskip 6.5\p@ \@plus3.5\p@ \@minus3\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 6.5\p@ \@plus3.5\p@ \@minus3\p@
               \parsep 4\p@ \@plus3\p@ \@minus\p@
               \itemsep \parsep
%%               \itemindent\z@
              }%
%</17pt>
%<*20pt>
   \@setfontsize\footnotesize\@xivpt{17.5}%
   \abovedisplayskip 14\p@ \@plus3\p@ \@minus8\p@
   \abovedisplayshortskip \z@ \@plus3\p@
   \belowdisplayshortskip 7\p@ \@plus3.5\p@ \@minus3\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 12\p@ \@plus4\p@ \@minus6\p@
               \parsep 6\p@ \@plus2\p@ \@minus3\p@
               \itemsep \parsep}%
%</20pt>
%<*25pt>
   \@setfontsize\footnotesize\@xviipt{22}%
   \abovedisplayskip 17\p@ \@plus4\p@ \@minus8\p@
   \abovedisplayshortskip \z@ \@plus4\p@
   \belowdisplayshortskip 11\p@ \@plus4\p@ \@minus3\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 14\p@ \@plus5\p@ \@minus7\p@
               \parsep 7\p@ \@plus2\p@ \@minus3\p@
               \itemsep \parsep}%
%</25pt>
%<*30pt>
   \@setfontsize\footnotesize\@xxpt{25}%
   \abovedisplayskip 20\p@ \@plus5\p@ \@minus9\p@
   \abovedisplayshortskip \z@ \@plus5\p@
   \belowdisplayshortskip 12.5\p@ \@plus6\p@ \@minus3\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 16\p@ \@plus5\p@ \@minus8\p@
               \parsep 8\p@ \@plus3\p@ \@minus4\p@
               \itemsep \parsep}%
%</30pt>
%<*36pt>
   \@setfontsize\footnotesize\@xxvpt{30}%
   \abovedisplayskip 25\p@ \@plus6\p@ \@minus10\p@
   \abovedisplayshortskip \z@ \@plus6\p@
   \belowdisplayshortskip 15\p@ \@plus7.5\p@ \@minus4\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 20\p@ \@plus7\p@ \@minus10\p@
               \parsep 10\p@ \@plus4\p@ \@minus5\p@
               \itemsep \parsep}%
%</36pt>
%<*48pt>
   \@setfontsize\footnotesize\@xxxpt{37}%
   \abovedisplayskip 30\p@ \@plus7\p@ \@minus11\p@
   \abovedisplayshortskip \z@ \@plus7\p@
   \belowdisplayshortskip 18\p@ \@plus9\p@ \@minus4\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 24\p@ \@plus8\p@ \@minus12\p@
               \parsep 12\p@ \@plus4\p@ \@minus6\p@
               \itemsep \parsep}%
%</48pt>
%<*60pt>
   \@setfontsize\footnotesize\@xxxvipt{45}%
   \abovedisplayskip 36\p@ \@plus8\p@ \@minus12\p@
   \abovedisplayshortskip \z@ \@plus8\p@
   \belowdisplayshortskip 22\p@ \@plus11\p@ \@minus5\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 30\p@ \@plus10\p@ \@minus15\p@
               \parsep 15\p@ \@plus5\p@ \@minus7\p@
               \itemsep \parsep}%
%</60pt>
   \belowdisplayskip \abovedisplayskip
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\miniscule}
% \begin{macro}{\scriptsize}
% \begin{macro}{\tiny}
% \begin{macro}{\large}
% \begin{macro}{\Large}
% \begin{macro}{\LARGE}
% \begin{macro}{\huge}
% \begin{macro}{\Huge}
% \begin{macro}{\HUGE}
%    These are all much simpler than the previous macros, they just
%    select a new fontsize, but leave the parameters for displays and
%    lists alone. The class provides two additional sizes, \cs{miniscule}
% and \cs{HUGE}, with respect to the usual set. For the larger sizes (e.g.,
% 72pt and above) I have
% made the \cs{baselineskip} approximately 20 precent larger than the pt size.
% \changes{v1.2}{2002/07/27}{Added \cs{miniscule} and \cs{HUGE} font sizes}
% \changes{v1.2}{2002/07/27}{Twiddled some font sizes to get regular steps}
% \changes{v1.2a}{2002/08/27}{Fixed 12pt scriptsize bug}
% \changes{v3.7r}{2022/07/26}{Make robust}
%    \begin{macrocode}
%<*9pt>
\ifextrafontsizes
  \DeclareRobustCommand{\miniscule}{\@setfontsize\miniscule\@ivpt{5}}
\else
  \DeclareRobustCommand{\miniscule}{\@setfontsize\miniscule\@vpt{6}}
\fi
\DeclareRobustCommand{\tiny}{\@setfontsize\tiny\@vpt{6}}
\DeclareRobustCommand{\scriptsize}{\@setfontsize\scriptsize\@vipt{7}}
\DeclareRobustCommand{\large}{\@setfontsize\large\@xpt{12}}
\DeclareRobustCommand{\Large}{\@setfontsize\Large\@xipt{13.6}}
\DeclareRobustCommand{\LARGE}{\@setfontsize\LARGE\@xiipt{14.5}}
\DeclareRobustCommand{\huge}{\@setfontsize\huge\@xivpt{18}}
\DeclareRobustCommand{\Huge}{\@setfontsize\Huge\@xviipt{22}}
\DeclareRobustCommand{\HUGE}{\@setfontsize\HUGE\@xxpt{25}}
%</9pt>
%<*10pt>
\DeclareRobustCommand{\miniscule}{\@setfontsize\miniscule\@vpt{6}}
\DeclareRobustCommand{\tiny}{\@setfontsize\tiny\@vipt{7}}
\DeclareRobustCommand{\scriptsize}{\@setfontsize\scriptsize\@viipt{8}}
\DeclareRobustCommand{\large}{\@setfontsize\large\@xipt{13.6}}
\DeclareRobustCommand{\Large}{\@setfontsize\Large\@xiipt{14.5}}
\DeclareRobustCommand{\LARGE}{\@setfontsize\LARGE\@xivpt{18}}
\DeclareRobustCommand{\huge}{\@setfontsize\huge\@xviipt{22}}
\DeclareRobustCommand{\Huge}{\@setfontsize\Huge\@xxpt{25}}
\DeclareRobustCommand{\HUGE}{\@setfontsize\HUGE\@xxvpt{30}}
%</10pt>
%<*11pt>
\DeclareRobustCommand{\miniscule}{\@setfontsize\miniscule\@vipt{7}}
\DeclareRobustCommand{\tiny}{\@setfontsize\tiny\@viipt{8}}
\DeclareRobustCommand{\scriptsize}{\@setfontsize\scriptsize\@viiipt{9.5}}
\DeclareRobustCommand{\large}{\@setfontsize\large\@xiipt{14.5}}
\DeclareRobustCommand{\Large}{\@setfontsize\Large\@xivpt{18}}
\DeclareRobustCommand{\LARGE}{\@setfontsize\LARGE\@xviipt{22}}
\DeclareRobustCommand{\huge}{\@setfontsize\huge\@xxpt{25}}
\DeclareRobustCommand{\Huge}{\@setfontsize\Huge\@xxvpt{30}}
\ifextrafontsizes
  \DeclareRobustCommand{\HUGE}{\@setfontsize\HUGE\@xxxpt{37}}
\else
  \let\HUGE=\Huge
\fi
%</11pt>
%<*12pt>
\DeclareRobustCommand{\miniscule}{\@setfontsize\miniscule\@viipt{8}}
\DeclareRobustCommand{\tiny}{\@setfontsize\tiny\@viiipt{9.5}}
\DeclareRobustCommand{\scriptsize}{\@setfontsize\scriptsize\@ixpt\@xpt}
\DeclareRobustCommand{\large}{\@setfontsize\large\@xivpt{18}}
\DeclareRobustCommand{\Large}{\@setfontsize\Large\@xviipt{22}}
\DeclareRobustCommand{\LARGE}{\@setfontsize\LARGE\@xxpt{25}}
\DeclareRobustCommand{\huge}{\@setfontsize\huge\@xxvpt{30}}
\ifextrafontsizes
  \DeclareRobustCommand{\Huge}{\@setfontsize\Huge\@xxxpt{37}}
  \DeclareRobustCommand{\HUGE}{\@setfontsize\HUGE\@xxxvipt{45}}
\else
  \let\Huge=\huge
  \let\HUGE=\huge
\fi
%</12pt>
%<*14pt>
\DeclareRobustCommand{\miniscule}{\@setfontsize\miniscule\@viiipt{9.5}}
\DeclareRobustCommand{\tiny}{\@setfontsize\tiny\@ixpt{10}}
\DeclareRobustCommand{\scriptsize}{\@setfontsize\scriptsize\@xpt{12}}
\DeclareRobustCommand{\large}{\@setfontsize\large\@xviipt{22}}
\DeclareRobustCommand{\Large}{\@setfontsize\Large\@xxpt{25}}
\DeclareRobustCommand{\LARGE}{\@setfontsize\LARGE\@xxvpt{30}}
\ifextrafontsizes
  \DeclareRobustCommand{\huge}{\@setfontsize\Huge\@xxxpt{37}}
  \DeclareRobustCommand{\Huge}{\@setfontsize\Huge\@xxxvipt{45}}
  \DeclareRobustCommand{\HUGE}{\@setfontsize\HUGE\@xlviiipt{60}}
\else
  \let\huge=\LARGE
  \let\Huge=\LARGE
  \let\HUGE=\LARGE
\fi
%</14pt>
%<*17pt>
\DeclareRobustCommand{\miniscule}{\@setfontsize\miniscule\@ixpt{10}}
\DeclareRobustCommand{\tiny}{\@setfontsize\tiny\@xpt{12}}
\DeclareRobustCommand{\scriptsize}{\@setfontsize\scriptsize\@xipt{13.6}}
\DeclareRobustCommand{\large}{\@setfontsize\large\@xxpt{25}}
\DeclareRobustCommand{\Large}{\@setfontsize\Large\@xxvpt{30}}
\ifextrafontsizes
  \DeclareRobustCommand{\LARGE}{\@setfontsize\LARGE\@xxxpt{37}}
  \DeclareRobustCommand{\huge}{\@setfontsize\huge\@xxxvipt{45}}
  \DeclareRobustCommand{\Huge}{\@setfontsize\Huge\@xlviiipt{60}}
  \DeclareRobustCommand{\HUGE}{\@setfontsize\HUGE\@lxpt{72}}
\else
  \let\LARGE=\Large
  \let\huge=\Large
  \let\Huge=\Large
  \let\HUGE=\Large
\fi
%</17pt>
%<*20pt>
\DeclareRobustCommand{\miniscule}{\@setfontsize\miniscule\@xpt{12}}
\DeclareRobustCommand{\tiny}{\@setfontsize\tiny\@xipt{13.6}}
\DeclareRobustCommand{\scriptsize}{\@setfontsize\scriptsize\@xiipt{14.5}}
\DeclareRobustCommand{\large}{\@setfontsize\large\@xxvpt{30}}
\DeclareRobustCommand{\Large}{\@setfontsize\Large\@xxxpt{37}}
\DeclareRobustCommand{\LARGE}{\@setfontsize\LARGE\@xxxvipt{45}}
\DeclareRobustCommand{\huge}{\@setfontsize\huge\@xlviiipt{60}}
\DeclareRobustCommand{\Huge}{\@setfontsize\Huge\@lxpt{72}}
\DeclareRobustCommand{\HUGE}{\@setfontsize\HUGE\@lxxiipt{86}}
%</20pt>
%<*25pt>
\DeclareRobustCommand{\miniscule}{\@setfontsize\miniscule\@xipt{13.6}}
\DeclareRobustCommand{\tiny}{\@setfontsize\tiny\@xiipt{14.5}}
\DeclareRobustCommand{\scriptsize}{\@setfontsize\scriptsize\@xivpt{17.5}}
\DeclareRobustCommand{\large}{\@setfontsize\large\@xxxpt{37}}
\DeclareRobustCommand{\Large}{\@setfontsize\Large\@xxxvipt{45}}
\DeclareRobustCommand{\LARGE}{\@setfontsize\LARGE\@xlviiipt{60}}
\DeclareRobustCommand{\huge}{\@setfontsize\huge\@lxpt{72}}
\DeclareRobustCommand{\Huge}{\@setfontsize\Huge\@lxxiipt{86}}
\DeclareRobustCommand{\HUGE}{\@setfontsize\HUGE\@lxxxivpt{100}}
%</25pt>
%<*30pt>
\DeclareRobustCommand{\miniscule}{\@setfontsize\miniscule\@xiipt{14.5}}
\DeclareRobustCommand{\tiny}{\@setfontsize\tiny\@xivpt{17.5}}
\DeclareRobustCommand{\scriptsize}{\@setfontsize\scriptsize\@xviipt{22}}
\DeclareRobustCommand{\large}{\@setfontsize\large\@xxxvipt{45}}
\DeclareRobustCommand{\Large}{\@setfontsize\Large\@xlviiipt{60}}
\DeclareRobustCommand{\LARGE}{\@setfontsize\LARGE\@lxpt{72}}
\DeclareRobustCommand{\huge}{\@setfontsize\huge\@lxxiipt{86}}
\DeclareRobustCommand{\Huge}{\@setfontsize\Huge\@lxxxivpt{100}}
\DeclareRobustCommand{\HUGE}{\@setfontsize\HUGE\@xcvipt{116}}
%</30pt>
%<*36pt>
\DeclareRobustCommand{\miniscule}{\@setfontsize\miniscule\@xivpt{17.5}}
\DeclareRobustCommand{\tiny}{\@setfontsize\tiny\@xviipt{22}}
\DeclareRobustCommand{\scriptsize}{\@setfontsize\scriptsize\@xxpt{25}}
\DeclareRobustCommand{\large}{\@setfontsize\large\@xlviiipt{60}}
\DeclareRobustCommand{\Large}{\@setfontsize\Large\@lxpt{72}}
\DeclareRobustCommand{\LARGE}{\@setfontsize\LARGE\@lxxiipt{86}}
\DeclareRobustCommand{\huge}{\@setfontsize\huge\@lxxxivpt{100}}
\DeclareRobustCommand{\Huge}{\@setfontsize\Huge\@xcvipt{116}}
\DeclareRobustCommand{\HUGE}{\@setfontsize\HUGE\@cviiipt{132}}
%</36pt>
%<*48pt>
\DeclareRobustCommand{\miniscule}{\@setfontsize\miniscule\@xviipt{22}}
\DeclareRobustCommand{\tiny}{\@setfontsize\tiny\@xxpt{25}}
\DeclareRobustCommand{\scriptsize}{\@setfontsize\scriptsize\@xxvpt{30}}
\DeclareRobustCommand{\large}{\@setfontsize\large\@lxpt{72}}
\DeclareRobustCommand{\Large}{\@setfontsize\Large\@lxxiipt{86}}
\DeclareRobustCommand{\LARGE}{\@setfontsize\LARGE\@lxxxivpt{100}}
\DeclareRobustCommand{\huge}{\@setfontsize\huge\@xcvipt{116}}
\DeclareRobustCommand{\Huge}{\@setfontsize\Huge\@cviiipt{132}}
\DeclareRobustCommand{\HUGE}{\@setfontsize\HUGE\@cxxpt{144}}
%</48pt>
%<*60pt>
\DeclareRobustCommand{\miniscule}{\@setfontsize\miniscule\@xxpt{25}}
\DeclareRobustCommand{\tiny}{\@setfontsize\tiny\@xxvpt{30}}
\DeclareRobustCommand{\scriptsize}{\@setfontsize\scriptsize\@xxxpt{37}}
\DeclareRobustCommand{\large}{\@setfontsize\large\@lxxiipt{86}}
\DeclareRobustCommand{\Large}{\@setfontsize\Large\@lxxxivpt{100}}
\DeclareRobustCommand{\LARGE}{\@setfontsize\LARGE\@xcvipt{116}}
\DeclareRobustCommand{\huge}{\@setfontsize\huge\@cviiipt{132}}
\DeclareRobustCommand{\Huge}{\@setfontsize\Huge\@cxxpt{144}}
\DeclareRobustCommand{\HUGE}{\@setfontsize\HUGE\@cxxxiipt{162}}
%</60pt>
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
%    \begin{macrocode}
%</9pt|10pt|11pt|12pt|14pt|17pt|20pt|25pt|30pt|36pt|48pt|60pt>
%<*class>
%    \end{macrocode}
%
% \begin{macro}{\captionsize}
%  This internal command holds the font size for captions. 
%    \begin{macrocode}
\newcommand{\captionsize}{\normalsize}
%    \end{macrocode}
% \end{macro}
%
% \subsection{Paragraphing}
%
% \begin{macro}{\lineskip}
% \begin{macro}{\normallineskip}
%    These parameters control \TeX's behaviour when two lines tend to
%    come too close together.
%    \begin{macrocode}
\setlength\lineskip{1\p@}
\setlength\normallineskip{1\p@}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\baselinestretch}
%    This is used as a multiplier for \cs{baselineskip}. The default is
%    to \emph{not} stretch the baselines.
%    \begin{macrocode}
\renewcommand{\baselinestretch}{}
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\parskip}
% \begin{macro}{\onelineskip}
%
% \cs{parskip} is additional vertical space between paragraphs;  default
% is zero.
%
%
%    \cs{onelineskip} is the default space between baselines.
% \changes{v0.11 (mem14.clo)}{2001/10/30}{Changed \cs{onelineskip} from 17.28pt to 17.5pt}
%    \begin{macrocode}
\setlength\parskip{0\p@ \@plus \p@}
%</class>
%<*9pt|10pt|11pt|12pt|14pt|17pt|20pt|25pt|30pt|36pt|48pt|60pt>
%<9pt>\setlength{\onelineskip}{\@xpt\p@}
%<10pt>\setlength{\onelineskip}{\@xiipt\p@}
%<11pt>\setlength{\onelineskip}{13.6\p@}
%<12pt>\setlength{\onelineskip}{14.5\p@}
%<14pt>\setlength{\onelineskip}{17.5\p@}
%<17pt>\setlength{\onelineskip}{22\p@}
%<20pt>\setlength{\onelineskip}{25\p@}
%<25pt>\setlength{\onelineskip}{30\p@}
%<30pt>\setlength{\onelineskip}{37\p@}
%<36pt>\setlength{\onelineskip}{45\p@}
%<48pt>\setlength{\onelineskip}{60\p@}
%<60pt>\setlength{\onelineskip}{72\p@}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\parindent}
%    \cs{parskip} gives extra vertical space between paragraphs and
%    \cs{parindent} is the width of the paragraph indentation. 
%    \begin{macrocode}
\if@twocolumn
  \setlength\parindent{1em}
\else
%<9pt>  \setlength\parindent{12\p@}
%<10pt>  \setlength\parindent{15\p@}
%<11pt>  \setlength\parindent{17\p@}
%<12pt>  \setlength\parindent{1.5em}
%<14pt>  \setlength\parindent{1.5em}
%<17pt>  \setlength\parindent{1.5em}
%<20pt>  \setlength\parindent{1.5em}
%<25pt>  \setlength\parindent{1.5em}
%<30pt>  \setlength\parindent{1.5em}
%<36pt>  \setlength\parindent{1.5em}
%<48pt>  \setlength\parindent{1.5em}
%<60pt>  \setlength\parindent{1.5em}
\fi
%</9pt|10pt|11pt|12pt|14pt|17pt|20pt|25pt|30pt|36pt|48pt|60pt>
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\smallskipamount}
% \begin{macro}{\medskipamount}
% \begin{macro}{\bigskipamount}
% The values for these three parameters are set in the LaTeX kernel.
% Historically they have been size invariant, but I have changed them for
% the larger sizes (\cs{smallskipamount} is 1/4 the fontsize, and the others
% each double up on the next lower).
% \changes{v1.61803}{2008/01/30}{(small/med/big)skips not invraiant for larger font sizes.}
% \changes{v1.61803}{2008/01/30}{Changed (small/med/big)skips for 17pt}
%    \begin{macrocode}
%<*9pt|10pt|11pt|12pt|14pt>
\setlength\smallskipamount{3\p@ \@plus 1\p@ \@minus 1\p@}
\setlength\medskipamount{6\p@ \@plus 2\p@ \@minus 2\p@}
\setlength\bigskipamount{12\p@ \@plus 4\p@ \@minus 4\p@}
%</9pt|10pt|11pt|12pt|14pt>
%<*17pt|20pt|25pt|30pt|36pt|48pt|60pt>
%<*17pt>
\setlength\smallskipamount{4\p@ \@plus1\p@ \@minus1\p@}
\setlength\medskipamount{8\p@ \@plus2\p@ \@minus2\p@}
\setlength\bigskipamount{17\p@ \@plus4\p@ \@minus4\p@}
%</17pt>
%<*20pt>
\setlength\smallskipamount{5\p@ \@plus1\p@ \@minus1\p@}
\setlength\medskipamount{10\p@ \@plus2\p@ \@minus2\p@}
\setlength\bigskipamount{20\p@ \@plus4\p@ \@minus4\p@}
%</20pt>
%<*25pt>
\setlength\smallskipamount{6\p@ \@plus1\p@ \@minus1\p@}
\setlength\medskipamount{12\p@ \@plus2\p@ \@minus2\p@}
\setlength\bigskipamount{24\p@ \@plus4\p@ \@minus4\p@}
%</25pt>
%<*30pt>
\setlength\smallskipamount{5\p@ \@plus1\p@ \@minus1\p@}
\setlength\medskipamount{10\p@ \@plus2\p@ \@minus2\p@}
\setlength\bigskipamount{20\p@ \@plus4\p@ \@minus4\p@}
%</30pt>
%<*36pt>
\setlength\smallskipamount{9\p@ \@plus2\p@ \@minus2\p@}
\setlength\medskipamount{18\p@ \@plus4\p@ \@minus4\p@}
\setlength\bigskipamount{36\p@ \@plus8\p@ \@minus8\p@}
%</36pt>
%<*48pt>
\setlength\smallskipamount{12\p@ \@plus3\p@ \@minus3\p@}
\setlength\medskipamount{24\p@ \@plus6\p@ \@minus6\p@}
\setlength\bigskipamount{48\p@ \@plus12\p@ \@minus12\p@}
%</48pt>
%<*60pt>
\setlength\smallskipamount{15\p@ \@plus4\p@ \@minus4\p@}
\setlength\medskipamount{30\p@ \@plus8\p@ \@minus8\p@}
\setlength\bigskipamount{60\p@ \@plus16\p@ \@minus16\p@}
%</60pt>
%</17pt|20pt|25pt|30pt|36pt|48pt|60pt>
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\@lowpenalty}
% \begin{macro}{\@medpenalty}
% \begin{macro}{\@highpenalty}%
%    The commands \cs{nopagebreak} and \cs{nolinebreak} put in penalties
%    to discourage these breaks at the point they are put in.
%    They use \cs{@lowpenalty}, \cs{@medpenalty} or \cs{@highpenalty},
%    dependent on their argument.
%    \begin{macrocode}
%<*class>
\@lowpenalty   51
\@medpenalty  151
\@highpenalty 301
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\clubpenalty}
% \begin{macro}{\widowpenalty}
%    These penalties are used to discourage club and widow lines.
%    The default values are 150 each, but we want stronger discouragement.
%    \begin{macrocode}
\clubpenalty  1000
\widowpenalty 1000
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\displaywidowpenalty}
% \begin{macro}{\predisplaypenalty}
% \begin{macro}{\postdisplaypenalty}
%    Discourage, but do not prevent, widows in front of a math display
%    and forbid breaking directly in front of a display. Allow break
%    after a display without a penalty. The default values are
%    used, therefore we only show them here.
%    \begin{macrocode}
% \displaywidowpenalty 50
% \predisplaypenalty   10000
% \postdisplaypenalty  0
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\interlinepenalty}
%    Allow the breaking of a page in the middle of a paragraph. Using
%    the kernel default and here just showing it.
%    \begin{macrocode}
% \interlinepenalty 0
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\brokenpenalty}
%    We allow the breaking of a page after a hyphenated line. Using
%    the kernel default and here just showing it.
%    \begin{macrocode}
% \brokenpenalty 100
%    \end{macrocode}
% \end{macro}
%
% 
%
%
% \subsection{Vertical spacing}
%
% \begin{macro}{\headheight}
% \begin{macro}{\headsep}
% \begin{macro}{\topskip}
% \begin{macro}{\footskip}
%   The \cs{headheight} is the height of the box that will contain the
%   running head. In this class it is point size dependent ---
%   \cs{onelineskip} (normally it is a constant 12pt).
%
%   The \cs{headsep} is the distance between the bottom of the running
%   head and the top of the text. For the larger sizes this is 1.8
%   times the fontsize.
%
%   The \cs{topskip} is the \cs{baselineskip} for the first line on a
%   page; \LaTeX's output routine will not work properly if it has the
%   value 0pt, so do not do that! For the larger sizes this is the
%   font size.
%
%   The distance from the baseline of the box which contains the
%   running footer to the baseline of last line of text is controlled
%   by the \cs{footskip}. For the larger sizes this is 2.5 times the
%   font size.
% \changes{v0.11 (mem14.clo)}{2001/10/30}{Changed \cs{headheight} from 16pt to 17.5pt}
% \changes{v0.11 (mem11.clo)}{2002/03/10}{Changed \cs{headheight} from 13pt to 13.6pt}
% \changes{v0.4b (mem12.clo)}{2010/10/19}{Changed \cs{headheight} from 14pt to 14.5pt}
%    \begin{macrocode}
%</class>
%<*9pt|10pt|11pt|12pt|14pt|17pt|20pt|25pt|30pt|36pt|48pt|60pt>
%<*9pt>
\setlength\headheight{11\p@}
\setlength\headsep{.225in}
\setlength\topskip{9\p@}
\setlength\footskip{.33in}
%</9pt>
%<*10pt>
\setlength\headheight{12\p@}
\setlength\headsep{.25in}
\setlength\topskip{10\p@}
\setlength\footskip{.35in}
%</10pt>
%<*11pt>
\setlength\headheight{13.6\p@}
\setlength\headsep{.275in}
\setlength\topskip{11\p@}
\setlength\footskip{.38in}
%</11pt>
%<*12pt>
\setlength\headheight{14.5\p@}
\setlength\headsep{.275in}
\setlength\topskip{12\p@}
\setlength\footskip{30\p@}
%</12pt>
%<*14pt>
\setlength\headheight{17.5\p@}
\setlength\headsep{.30in}
\setlength\topskip{14.4\p@}
\setlength\footskip{.4in}
%</14pt>
%<*17pt>
\setlength\headheight{22\p@}
\setlength\headsep{.30in}
\setlength\topskip{14.4\p@}
\setlength\footskip{.4in}
%</17pt>
%<*20pt>
\setlength\headheight{25\p@}
\setlength\headsep{36\p@}
\setlength\topskip{20\p@}
\setlength\footskip{50\p@}
%</20pt>
%<*25pt>
\setlength\headheight{30\p@}
\setlength\headsep{45\p@}
\setlength\topskip{25\p@}
\setlength\footskip{62\p@}
%</25pt>
%<*30pt>
\setlength\headheight{37\p@}
\setlength\headsep{54\p@}
\setlength\topskip{30\p@}
\setlength\footskip{75\p@}
%</30pt>
%<*36pt>
\setlength\headheight{45\p@}
\setlength\headsep{65\p@}
\setlength\topskip{36\p@}
\setlength\footskip{90\p@}
%</36pt>
%<*48pt>
\setlength\headheight{60\p@}
\setlength\headsep{86\p@}
\setlength\topskip{48\p@}
\setlength\footskip{120\p@}
%</48pt>
%<*60pt>
\setlength\headheight{72\p@}
\setlength\headsep{108\p@}
\setlength\topskip{60\p@}
\setlength\footskip{150\p@}
%</60pt>
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\maxdepth}
% \begin{macro}{\@maxdepth}
%    The \TeX\ primitive register \cs{maxdepth} has a function that is
%    similar to that of \cs{topskip}. The register \cs{@maxdepth} should
%    always contain a copy of \cs{maxdepth}. In both plain \TeX\ and
%    \LaTeX~2.09 \cs{maxdepth} had a fixed value of \texttt{4pt}; in
%    native \LaTeX 2e mode we let the value depend on the typesize. We
%    set it so that \cs{maxdepth} $+$ \cs{topskip} $=$ typesize $\times
%    1.5$. As it happens, in these classes \cs{topskip} is equal to the
%    typesize, therefor we set \cs{maxdepth} to half the value of
%    \cs{topskip}.
%    \begin{macrocode}
\setlength\maxdepth{.5\topskip}
\setlength\@maxdepth\maxdepth
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
%
% \subsection{Footnotes}
%
% \begin{macro}{\footnotesep}
%    \cs{footnotesep} is the height of the strut placed at the beginning
%    of every footnote. It equals the height of a normal \cs{footnotesize}
% strut, so no extra space appears between footnotes.
% \changes{v1.61803}{2007/01/30}{Changed nearly all \cs{footnotesep}}
%    \begin{macrocode}
%<9pt>\setlength\footnotesep{5.6\p@}
%<10pt>\setlength\footnotesep{6.65\p@}
%<11pt>\setlength\footnotesep{7.7\p@}
%<12pt>\setlength\footnotesep{8.4\p@}
%<14pt>\setlength\footnotesep{9.5\p@} 
%<17pt>\setlength\footnotesep{10.15\p@}
%<20pt>\setlength\footnotesep{12.6\p@}
%<25pt>\setlength\footnotesep{15.4\p@}
%<30pt>\setlength\footnotesep{17.5\p@}
%<36pt>\setlength\footnotesep{21\p@}
%<48pt>\setlength\footnotesep{25.9\p@}
%<60pt>\setlength\footnotesep{31.5\p@}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\footins}
%    \verb?\skip\footins? is the space between the last line of the main
%    text and the top of the first footnote.
%    \begin{macrocode}
%<9pt>\setlength{\skip\footins}{8\p@ \@plus 2\p@ \@minus 2\p@}
%<10pt>\setlength{\skip\footins}{9\p@ \@plus 4\p@ \@minus 2\p@}
%<11pt>\setlength{\skip\footins}{10\p@ \@plus 4\p@ \@minus 2\p@}
%<12pt>\setlength{\skip\footins}{10.8\p@ \@plus 4\p@ \@minus 2\p@}
%<14pt>\setlength{\skip\footins}{13\p@ \@plus 4\p@ \@minus 2\p@}
%<17pt>\setlength{\skip\footins}{16\p@ \@plus 5\p@ \@minus 3\p@}
%<20pt>\setlength{\skip\footins}{19\p@ \@plus 7\p@ \@minus 3\p@}
%<25pt>\setlength{\skip\footins}{24\p@ \@plus 8\p@ \@minus 4\p@}
%<30pt>\setlength{\skip\footins}{29\p@ \@plus 10\p@ \@minus 5\p@}
%<36pt>\setlength{\skip\footins}{35\p@ \@plus 12\p@ \@minus 6\p@}
%<48pt>\setlength{\skip\footins}{47\p@ \@plus 16\p@ \@minus 8\p@}
%<60pt>\setlength{\skip\footins}{59\p@ \@plus 20\p@ \@minus 10\p@}
%    \end{macrocode}
% \end{macro}
%
% \subsection{Floats}
%
% \paragraph{Floats on a text page}
%
% \begin{macro}{\floatsep}
% \begin{macro}{\textfloatsep}
% \begin{macro}{\intextsep}
%    When a floating object is placed on a page with text, these
%    parameters control the separation between the float and the other
%    objects on the page. These parameters are used for both
%    one-column mode and single-column floats in two-column mode.
%
%    \cs{floatsep} is the space between adjacent floats that are moved
%    to the top or bottom of the text page. For the larger sizes this is 
% \cs{bigskip}.
%
%    \cs{textfloatsep} is the space between the main text and floats
%    at the top or bottom of the page. For the larger sizes this is
% 1.45\cs{onelineskip}.
%
%    \cs{intextsep} is the space between in-text floats and the text.
%    \begin{macrocode}
%<*9pt>
\setlength\floatsep    {12\p@ \@plus 2\p@ \@minus 2\p@}
\setlength\textfloatsep{20\p@ \@plus 2\p@ \@minus 4\p@}
\setlength\intextsep   {12\p@ \@plus 2\p@ \@minus 2\p@}
%</9pt>
%<*10pt>
\setlength\floatsep    {12\p@ \@plus 2\p@ \@minus 2\p@}
\setlength\textfloatsep{20\p@ \@plus 2\p@ \@minus 4\p@}
\setlength\intextsep   {12\p@ \@plus 2\p@ \@minus 2\p@}
%</10pt>
%<*11pt>
\setlength\floatsep    {12\p@ \@plus 2\p@ \@minus 2\p@}
\setlength\textfloatsep{20\p@ \@plus 2\p@ \@minus 4\p@}
\setlength\intextsep   {12\p@ \@plus 2\p@ \@minus 2\p@}
%</11pt>
%<*12pt>
\setlength\floatsep    {12\p@ \@plus 2\p@ \@minus 2\p@}
\setlength\textfloatsep{20\p@ \@plus 2\p@ \@minus 4\p@}
\setlength\intextsep   {14\p@ \@plus 4\p@ \@minus 4\p@}
%</12pt>
%<*14pt>
\setlength\floatsep    {14\p@ \@plus 4\p@ \@minus 4\p@}
\setlength\textfloatsep{20\p@ \@plus 4\p@ \@minus 4\p@}
\setlength\intextsep   {14\p@ \@plus 4\p@ \@minus 4\p@}
%</14pt>
%<*17pt>
\setlength\floatsep    {15\p@ \@plus 4\p@ \@minus 4\p@}
\setlength\textfloatsep{25\p@ \@plus 4\p@ \@minus 5\p@}
\intextsep \floatsep
%</17pt>
%<*20pt>
\setlength\floatsep    {20\p@ \@plus 4\p@ \@minus 4\p@}
\setlength\textfloatsep{36\p@ \@plus 4\p@ \@minus 8\p@}
\intextsep \floatsep
%</20pt>
%<*25pt>
\setlength\floatsep    {24\p@ \@plus 4\p@ \@minus 4\p@}
\setlength\textfloatsep{43\p@ \@plus 4\p@ \@minus 8\p@}
\intextsep \floatsep
%</25pt>
%<*30pt>
\setlength\floatsep    {30\p@ \@plus 6\p@ \@minus 6\p@}
\setlength\textfloatsep{54\p@ \@plus 6\p@ \@minus 12\p@}
\intextsep \floatsep
%</30pt>
%<*36pt>
\setlength\floatsep    {36\p@ \@plus 8\p@ \@minus 8\p@}
\setlength\textfloatsep{65\p@ \@plus 8\p@ \@minus 16\p@}
\intextsep \floatsep
%</36pt>
%<*48pt>
\setlength\floatsep    {48\p@ \@plus 12\p@ \@minus 12\p@}
\setlength\textfloatsep{87\p@ \@plus 12\p@ \@minus 24\p@}
\intextsep \floatsep
%</48pt>
%<*60pt>
\setlength\floatsep    {60\p@ \@plus 16\p@ \@minus 16\p@}
\setlength\textfloatsep{104\p@ \@plus 16\p@ \@minus 32\p@}
\intextsep \floatsep
%</60pt>
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\dblfloatsep}
% \begin{macro}{\dbltextfloatsep}
%    When floating objects that span the whole \cs{textwidth} are placed
%    on a text page and \LaTeX{} is in twocolumn mode the separation
%    between the float and the text is controlled by \cs{dblfloatsep}
%    and \cs{dbltextfloatsep}.
%
%    \cs{dblfloatsep} is the space between adjacent floats that are moved
%    to the top or bottom of the text page.
%
%    \cs{dbltextfloatsep} is the space between the main text and floats
%    at the top or bottom of the page.
%
%    \begin{macrocode}
%<*9pt>
\setlength\dblfloatsep    {12\p@ \@plus 2\p@ \@minus 2\p@}
\setlength\dbltextfloatsep{20\p@ \@plus 2\p@ \@minus 4\p@}
%</9pt>
%<*10pt>
\setlength\dblfloatsep    {12\p@ \@plus 2\p@ \@minus 2\p@}
\setlength\dbltextfloatsep{20\p@ \@plus 2\p@ \@minus 4\p@}
%</10pt>
%<*11pt>
\setlength\dblfloatsep    {12\p@ \@plus 2\p@ \@minus 2\p@}
\setlength\dbltextfloatsep{20\p@ \@plus 2\p@ \@minus 4\p@}
%</11pt>
%<*12pt>
\setlength\dblfloatsep    {14\p@ \@plus 2\p@ \@minus 4\p@}
\setlength\dbltextfloatsep{20\p@ \@plus 2\p@ \@minus 4\p@}
%</12pt>
%<*14pt>
\setlength\dblfloatsep    {14\p@ \@plus 2\p@ \@minus 4\p@}
\setlength\dbltextfloatsep{20\p@ \@plus 2\p@ \@minus 4\p@}
%</14pt>
%<*17pt>
\setlength\dblfloatsep    {15\p@ \@plus 4\p@ \@minus 4\p@}
\setlength\dbltextfloatsep{25\p@ \@plus 5\p@ \@minus 5\p@}
%</17pt>
%<*20pt>
\dblfloatsep \floatsep
\dbltextfloatsep \textfloatsep
%</20pt>
%<*25pt>
\dblfloatsep \floatsep
\dbltextfloatsep \textfloatsep
%</25pt>
%<*30pt>
\dblfloatsep \floatsep
\dbltextfloatsep \textfloatsep
%</30pt>
%<*36pt>
\dblfloatsep \floatsep
\dbltextfloatsep \textfloatsep
%</36pt>
%<*48pt>
\dblfloatsep \floatsep
\dbltextfloatsep \textfloatsep
%</48pt>
%<*60pt>
\dblfloatsep \floatsep
\dbltextfloatsep \textfloatsep
%</60pt>
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \paragraph{Floats on their own page or column}
%
% \begin{macro}{\@fptop}
% \begin{macro}{\@fpsep}
% \begin{macro}{\@fpbot}
%    When floating objects are placed on separate pages the layout of
%    such pages is controlled by these parameters. At the top of the
%    page \cs{@fptop} amount of stretchable whitespace is inserted, at
%    the bottom of the page we get an \cs{@fpbot} amount of stretchable
%    whitespace. Between adjacent floats the \cs{@fpsep} is inserted.
% For the larger sizes \cs{@fpsep} is .7\cs{onelineskip}.
%
%    These parameters are used for the placement of floating objects
%    in one column mode, or in single column floats in two column
%    mode.
%
%    Note that at least one of the two parameters \cs{@fptop} and
%    \cs{@fpbot} should contain a \verb?plus ...fil? to allow filling the
%    remaining empty space.
%    \begin{macrocode}
%<*9pt>
\setlength\@fptop{0\p@ \@plus 1fil}
\setlength\@fpsep{9\p@ \@plus 2fil}
\setlength\@fpbot{0\p@ \@plus 1fil}
%</9pt>
%<*10pt>
\setlength\@fptop{0\p@ \@plus 1fil}
\setlength\@fpsep{8\p@ \@plus 2fil}
\setlength\@fpbot{0\p@ \@plus 1fil}
%</10pt>
%<*11pt>
\setlength\@fptop{0\p@ \@plus 1fil}
\setlength\@fpsep{8\p@ \@plus 2fil}
\setlength\@fpbot{0\p@ \@plus 1fil}
%</11pt>
%<*12pt>
\setlength\@fptop{0\p@ \@plus 1fil}
\setlength\@fpsep{10\p@ \@plus 2fil}
\setlength\@fpbot{0\p@ \@plus 1fil}
%</12pt>
%<*14pt>
\setlength\@fptop{0\p@ \@plus 1fil}
\setlength\@fpsep{10\p@ \@plus 2fil}
\setlength\@fpbot{0\p@ \@plus 1fil}
%</14pt>
%<*17pt>
\setlength\@fptop{0\p@ \@plus 1fil}
\setlength\@fpsep{12\p@ \@plus 2fil}
\setlength\@fpbot{0\p@ \@plus 1fil}
%</17pt>
%<*20pt>
\setlength\@fptop{0\p@ \@plus 1fil}
\setlength\@fpsep{17\p@ \@plus 2fil}
\@fpbot \@fptop
%</20pt>
%<*25pt>
\setlength\@fptop{0\p@ \@plus 1fil}
\setlength\@fpsep{21\p@ \@plus 2fil}
\@fpbot \@fptop
%</25pt>
%<*30pt>
\setlength\@fptop{0\p@ \@plus 1fil}
\setlength\@fpsep{26\p@ \@plus 2fil}
\@fpbot \@fptop
%</30pt>
%<*36pt>
\setlength\@fptop{0\p@ \@plus 1fil}
\setlength\@fpsep{31\p@ \@plus 2fil}
\@fpbot \@fptop
%</36pt>
%<*48pt>
\setlength\@fptop{0\p@ \@plus 1fil}
\setlength\@fpsep{42\p@ \@plus 2fil}
\@fpbot \@fptop
%</48pt>
%<*60pt>
\setlength\@fptop{0\p@ \@plus 1fil}
\setlength\@fpsep{50\p@ \@plus 2fil}
\@fpbot \@fptop
%</60pt>
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@dblfptop}
% \begin{macro}{\@dblfpsep}
% \begin{macro}{\@dblfpbot}
%    Double column floats in two column mode are handled with similar
%    parameters.
%    \begin{macrocode}
%<*9pt>
\setlength\@dblfptop{0\p@ \@plus 1fil}
\setlength\@dblfpsep{7\p@ \@plus 2fil}
\setlength\@dblfpbot{0\p@ \@plus 1fil}
%</9pt>
%<*10pt>
\setlength\@dblfptop{0\p@ \@plus 1fil}
\setlength\@dblfpsep{8\p@ \@plus 2fil}
\setlength\@dblfpbot{0\p@ \@plus 1fil}
%</10pt>
%<*11pt>
\setlength\@dblfptop{0\p@ \@plus 1fil}
\setlength\@dblfpsep{8\p@ \@plus 2fil}
\setlength\@dblfpbot{0\p@ \@plus 1fil}
%</11pt>
%<*12pt>
\setlength\@dblfptop{0\p@ \@plus 1fil}
\setlength\@dblfpsep{10\p@ \@plus 2fil}
\setlength\@dblfpbot{0\p@ \@plus 1fil}
%</12pt>
%<*14pt>
\setlength\@dblfptop{0\p@ \@plus 1fil}
\setlength\@dblfpsep{12\p@ \@plus 2fil}
\setlength\@dblfpbot{0\p@ \@plus 1fil}
%</14pt>
%<*17pt>
\setlength\@dblfptop{0\p@ \@plus 1fil}
\setlength\@dblfpsep{12\p@ \@plus 2fil}
\setlength\@dblfpbot{0\p@ \@plus 1fil}
%</17pt>
%<*20pt>
\@dblfptop \@fptop
\@dblfpsep \@fpsep
\@dblfpbot \@dblfptop
%</20pt>
%<*25pt>
\@dblfptop \@fptop
\@dblfpsep \@fpsep
\@dblfpbot \@dblfptop
%</25pt>
%<*30pt>
\@dblfptop \@fptop
\@dblfpsep \@fpsep
\@dblfpbot \@dblfptop
%</30pt>
%<*36pt>
\@dblfptop \@fptop
\@dblfpsep \@fpsep
\@dblfpbot \@dblfptop
%</36pt>
%<*48pt>
\@dblfptop \@fptop
\@dblfpsep \@fpsep
\@dblfpbot \@dblfptop
%</48pt>
%<*60pt>
\@dblfptop \@fptop
\@dblfpsep \@fpsep
\@dblfpbot \@dblfptop
%</60pt>
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \subsection{The measure}
%
% The width of a line of text (and therefore the text block) is termed
% the \emph{measure}.
%
% \begin{macro}{\lxvchars}
% The length \cs{lxvchars} is the approximate length of a normal
% text line containing 65 characters (a typesetters rule of thumb is
% that there should be about 60--70 characters per line).
%    \begin{macrocode}
%<9pt>\setlength\lxvchars{276\p@}  %
%<10pt>\setlength\lxvchars{300\p@} % standard 345pt
%<11pt>\setlength\lxvchars{324\p@} % standard 360pt
%<12pt>\setlength\lxvchars{336\p@} % standard 390pt
%<14pt>\setlength\lxvchars{408\p@} %
%<17pt>\setlength\lxvchars{444\p@} %
%<20pt>\setlength\lxvchars{528\p@} %
%<25pt>\setlength\lxvchars{626\p@} %
%<30pt>\setlength\lxvchars{748\p@} %
%<36pt>\setlength\lxvchars{891\p@} %
%<48pt>\setlength\lxvchars{1177\p@} %
%<60pt>\setlength\lxvchars{1463\p@} %
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\xlvchars}
% The length \cs{xlvchars} is the approximate length of a normal
% double column text line containing 45 characters 
% (a typesetters rule of thumb is
% that there should be about 40--50 characters per column line).
%    \begin{macrocode}
%<9pt>\setlength\xlvchars{192\p@}  %
%<10pt>\setlength\xlvchars{204\p@} % 
%<11pt>\setlength\xlvchars{216\p@} % 
%<12pt>\setlength\xlvchars{240\p@} % 
%<14pt>\setlength\xlvchars{288\p@} %
%<17pt>\setlength\xlvchars{312\p@} %
%<20pt>\setlength\xlvchars{365\p@} %
%<25pt>\setlength\xlvchars{438\p@} %
%<30pt>\setlength\xlvchars{518\p@} %
%<36pt>\setlength\xlvchars{617\p@} %
%<48pt>\setlength\xlvchars{815\p@} %
%<60pt>\setlength\xlvchars{1014\p@} %
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\marginparsep}
% \begin{macro}{\marginparpush}
% \cs{marginparsep} is the horizontal space between the text block and 
% marginal notes, while \cs{marginparpush} is the minimum vertical
% separation between the notes.
%    \begin{macrocode}
\if@twocolumn
%<*9pt|10pt|11pt|12pt|14pt>
  \setlength\marginparsep{10\p@}
%</9pt|10pt|11pt|12pt|14pt>
%<*17pt|20pt|25pt|30pt|36pt|48pt|60pt>
  \setlength\marginparsep{1em}
%</17pt|20pt|25pt|30pt|36pt|48pt|60pt>
\else
%<*9pt|10pt|11pt|12pt|14pt>
  \setlength\marginparsep{7\p@}
%</9pt|10pt|11pt|12pt|14pt>
%<*17pt|20pt|25pt|30pt|36pt|48pt|60pt>
  \setlength\marginparsep{0.7em}
%</17pt|20pt|25pt|30pt|36pt|48pt|60pt>
\fi
%<9pt|10pt|11pt>\setlength{\marginparpush}{5\p@}
%<12pt|14pt>\setlength{\marginparpush}{7\p@}
%<*17pt|20pt|25pt|30pt|36pt|48pt|60pt>
  \setlength\marginparpush{0.5em}
%</17pt|20pt|25pt|30pt|36pt|48pt|60pt>
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%    \begin{macrocode}
%</9pt|10pt|11pt|12pt|14pt|17pt|20pt|25pt|30pt|36pt|48pt|60pt>
%<*class>
%    \end{macrocode}
%
% \section{Page Layout}
%
%
% \subsection{The typeblock and margins}
%
%    All margin dimensions are measured from a point one inch from the
%    top and lefthand side of the page.
%
% \begin{macro}{\setlxvchars}
% \begin{macro}{\setxlvchars}
% These were suggested and supplied by Morten H{\o}gholm (18 May 2003).
%
% \cs{setlxvchars}\oarg{fontspec} sets \cs{lxvchars} to the length of a line
% containing 65 characters in the \meta{fontspec}. 
%
% Similarly
% \cs{setxlvchars}\oarg{fontspec} sets \cs{xlvchars} for 45 characters.
% \changes{v1.4}{2003/11/22}{Added \cs{setlxvchars} and \cs{setxlvchars}
%                              (from patch v1.6)}
%    \begin{macrocode}
\newcommand*{\setlxvchars}[1][\normalfont]{\begingroup
  #1
  \settowidth{\lxvchars}{abcdefghijklmnopqrstuvwxyz}%
  \setlength{\lxvchars}{2.042\lxvchars}%
  \addtolength{\lxvchars}{33.41pt}%
  \global\lxvchars=\lxvchars
  \endgroup}
\newcommand*{\setxlvchars}[1][\normalfont]{\begingroup
  #1
  \settowidth{\xlvchars}{abcdefghijklmnopqrstuvwxyz}%
  \setlength{\xlvchars}{1.415\xlvchars}%
  \addtolength{\xlvchars}{23.03pt}%
  \global\xlvchars=\xlvchars
  \endgroup}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\setrectanglesize}
%  The macro \cs{setrectanglesize}\marg{H}\marg{W}\marg{r}
% calculates the height and width of a rectangle given any two out of
% the three arguments. An unvalued argument is denoted by \verb?*?.
%
% Table~\ref{tab:setrect} shows the argument combinations and the result
% for each combination.
% \begin{table}
% \centering
% \caption{Arguments and results for \cs{setrectanglesize}}\label{tab:setrect}
% \begin{tabular}{ccc|l} \hline
%  H & W & r & Result  \\ \hline
%  * & W & r & $H = rW$  \\{}
%  * & W & * & $H = W$   \\{}
%  * & * & r & ambiguous   \\{}
%  * & * & * & ambiguous   \\{}
%  H & W & r & $H, W$  \\
%  H & W & * & $H, W$   \\
%  H & * & r & $W = rH$  \\
%  H & * & * & $W = H$   \\
%  \hline
% \end{tabular}
% \end{table}
%
% The
% calculated height and width are stored in \cs{@tempdima} and \cs{@tempdimb}
% respectively. Both lengths are set to zero if there is an error.
% \changes{v1.61803}{2008/01/30}{Used \cs{setlength} instead of TeX syntax so that the calc package 
%          can be used with page layout (Morten H{\o}gholm mempatch v4.5)}
%    \begin{macrocode}
\newcommand*{\setrectanglesize}[3]{%
  \nametest{#1}{*}%
  \ifsamename                           % H = *
    \nametest{#2}{*}%
    \ifsamename                         % W = *
      \@memerror{%
        The combination of argument values is ambiguous.\MessageBreak
        The lengths will be set to zero}{\@ehd}%
      \setlength{\@tempdima}{0pt}%
      \setlength{\@tempdimb}{0pt}%
    \else                               % W
      \nametest{#3}{*}%
      \ifsamename                       % r = *
        \setlength{\@tempdimb}{#2}%
        \setlength{\@tempdima}{\@tempdimb}%
      \else                             % r
        \setlength{\@tempdimb}{#2}%
        \setlength{\@tempdima}{#3\@tempdimb}%
      \fi
    \fi
  \else                                 % H
    \nametest{#2}{*}%
    \ifsamename                         % W = *
      \nametest{#3}{*}%
      \ifsamename                       % r = *
        \setlength{\@tempdima}{#1}%
        \setlength{\@tempdimb}{\@tempdima}%
      \else                             % r
        \setlength{\@tempdima}{#1}%
        \setlength{\@tempdimb}{#3\@tempdima}%
      \fi
    \else                               % W
      \setlength{\@tempdima}{#1}%
      \setlength{\@tempdimb}{#2}%
    \fi
  \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\setfillsize}
% Consider a set of 4 lengths, $T$, $L$, $C$, and $R$, such that
% $T = L + C + R$, where $T$ is a fixed size and normally $C$ is also fixed.
% Also $L$ and $R$ may be specified independently of each other or as a
% ratio (i.e., $L = rR$ or $R = rL$).
%  The macro 
% \cs{setfillsize}\marg{T}\marg{C}\marg{L}\marg{R}\marg{r}
% maintains these constraints among the variables, where an unvalued 
% argument is denoted by \verb?*?.
%
% Table~\ref{tab:setfill} shows the argument combinations and the result
% for each combination.
% \begin{table}
% \centering
% \caption{Arguments and results for \cs{setfillsize}}\label{tab:setfill}
% \begin{tabular}{cccc|ll} \hline
%  C & L & R & r & Result                     &   \\ \hline
%  * & * & R & r & $L = rR$,                  & $C = T - L - R$ \\{}
%  * & * & R & * & $L = R$,                   & $C = T - L - R$ \\{}
%  * & * & * & r & ambigous                   & \\{}
%  * & * & * & * & ambiguous                  & \\{}
%  * & L & R & r & $L$, $R$,                  & $C = T - L - R$ \\{}
%  * & L & R & * & $L$, $R$,                  & $C = T - L - R$ \\{}
%  * & L & * & r & $R = rL$,                  & $C = T - L - R$ \\{}
%  * & L & * & * & $R = L$,                   & $C = T - L - R$ \\{}
%  C & * & R & r & $L = T - C - R$            & $C$ \\
%  C & * & R & * & $L = T - C - R$,           & $C$ \\
%  C & * & * & r & $L + R = T - C$, $R = rL$, & $C$ \\
%  C & * & * & * & $L + R = T - C$, $R = L$,  & $C$ \\
%  C & L & R & r & ambiguous                  & $C$ \\
%  C & L & R & * & ambiguous                  & $C$ \\ 
%  C & L & * & r & $R = T - C - L$,           & $C$ \\
%  C & L & * & * & $R = T - C - L$,           & $C$ \\
%  \hline
% \end{tabular}
% ^^A \MakeShortVerb{\|}
% \end{table}
%
%
% The
% calculated values of \texttt{C}, \texttt{L} and \texttt{R} are stored 
% \cs{@tempdimc}, 
% \cs{@tempdima} and \cs{@tempdimb} respectively. If there is an error
% the lengths are set to zero.
%    \begin{macrocode}
\newcommand*{\setfillsize}[5]{%
  \nametest{#2}{*}%
  \ifsamename                                % C = *
    \nametest{#3}{*}%
    \ifsamename                              % L = *
      \nametest{#4}{*}%
      \ifsamename                            % R = *
        \@memerror{%
          The combination of argument values is ambiguous.\MessageBreak
          The lengths will be set to zero}{\@ehd}
        \setlength{\@tempdima}{0pt}%
        \setlength{\@tempdimb}{0pt}%
        \setlength{\@tempdimc}{0pt}%
      \else                                  % R 
        \nametest{#5}{*}%
        \ifsamename                          % r = *
          \setlength{\@tempdimb}{#4}%
          \setlength{\@tempdima}{\@tempdimb}%
          \setlength{\@tempdimc}{#1}%
          \advance\@tempdimc -\@tempdima
          \advance\@tempdimc -\@tempdimb
        \else                                % r 
          \setlength{\@tempdimb}{#4}%
          \setlength{\@tempdima}{#5\@tempdimb}%
          \setlength{\@tempdimc}{#1}%
          \advance\@tempdimc -\@tempdima
          \advance\@tempdimc -\@tempdimb
        \fi
      \fi
    \else                                    % L 
      \nametest{#4}{*}%
      \ifsamename                            % R = *
        \nametest{#5}{*}%
        \ifsamename                          % r = *
          \setlength{\@tempdima}{#3}%
          \setlength{\@tempdimb}{\@tempdima}
          \setlength{\@tempdimc}{#1}%
          \advance\@tempdimc -\@tempdima
          \advance\@tempdimc -\@tempdimb
        \else                                % r 
          \setlength{\@tempdima}{#3}%
          \setlength{\@tempdimb}{#5\@tempdima}
          \setlength{\@tempdimc}{#1}%
          \advance\@tempdimc -\@tempdima
          \advance\@tempdimc -\@tempdimb
        \fi
      \else                                  % R
        \setlength{\@tempdima}{#3}%
        \setlength{\@tempdimb}{#4}%
        \setlength{\@tempdimc}{#1}%
        \advance\@tempdimc -\@tempdima
        \advance\@tempdimc -\@tempdimb
      \fi
    \fi
  \else                                      % C is valued
    \nametest{#3}{*}%
    \ifsamename                              % L = *
      \nametest{#4}{*}%
      \ifsamename                            % R = *
        \nametest{#5}{*}%
        \ifsamename                          % r = *
          \setlength{\@tempdimc}{#2}%
          \setlength{\@tempdima}{#1}%
          \advance\@tempdima -\@tempdimc
          \@tempdima = 0.5\@tempdima
          \@tempdimb = \@tempdima
        \else                                % r (CODE PERHAPS FIXED)
          \setlength{\@tempdimc}{#2}         % C
          \setlength{\@tempdimb}{#1}         % T
          \advance\@tempdimb -\@tempdimc % T - C
          \@tempdima = 1000sp
          \setlength{\@tempdima}{#5\@tempdima}        % 1000r sp
          \advance\@tempdima by 1000sp   % 1000(1+r)sp
          \@tempcnta = \@tempdima        % 1000(1+r)
          \@tempdima = \@tempdimb        % T - C
          \divide\@tempdima by \@tempcnta  % (T-C)/1000(1+r) pts
          \@tempdima = 1000\@tempdima      % (T-C)/(1+r)  pts = L
          \advance\@tempdimb by -\@tempdima % = R
        \fi
      \else                                  % R 
        \setlength{\@tempdimc}{#2}%
        \setlength{\@tempdimb}{#4}%
        \setlength{\@tempdima}{#1}%
        \advance\@tempdima -\@tempdimc
        \advance\@tempdima -\@tempdimb
      \fi
    \else                                    % L 
      \nametest{#4}{*}%
      \ifsamename                            % R = *
        \setlength{\@tempdimc}{#2}%
        \setlength{\@tempdima}{#3}%
        \setlength{\@tempdimb}{#1}%
        \advance\@tempdimb -\@tempdimc
        \advance\@tempdimb -\@tempdima
      \else                                  % R
        \@memerror{%
          The combination of argument values is ambiguous.\MessageBreak
          The lengths will be set to zero}{\@ehd}%
        \setlength{\@tempdima}{0pt}%
        \setlength{\@tempdimb}{0pt}%
        \setlength{\@tempdimc}{#2}%
      \fi
    \fi
  \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\setstocksize}
% \begin{macro}{\settrims}
% \begin{macro}{\settrimmedsize}
% \cs{setstocksize}\marg{height}\marg{width} sets the height
% and width of the stock material and 
% \cs{settrims}\marg{top}\marg{edge} sets the trim lengths
% for the top and side (fore edge) of the stock.
% The macro \cs{settrimmedsize}\marg{height}\marg{width}\marg{ratio}
% sets the size for the trimmed page, based on \cs{setrectanglesize}.
%    \begin{macrocode}
\newcommand{\setstocksize}[2]{%
  \setlength{\stockheight}{#1}%
  \setlength{\stockwidth}{#2}}
\newcommand{\settrims}[2]{%
  \setlength{\trimtop}{#1}%
  \setlength{\trimedge}{#2}}
\newcommand{\settrimmedsize}[3]{%
  \setrectanglesize{#1}{#2}{#3}%
  \setlength{\paperheight}{\@tempdima}%
  \setlength{\paperwidth}{\@tempdimb}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\settypeblocksize}
% \cs{settypeblocksize}\marg{height}\marg{width}\marg{ratio}
% calulates the \cs{textheight} and \cs{textwidth} from two out of the
% three arguments. 
% \changes{v3.6k}{2013/05/14}{Marked \cs{settypeblocksize} as being used}
%    \begin{macrocode}
\newcommand{\settypeblocksize}[3]{%
  \memsetmacroused\settypeblocksize%
  \setrectanglesize{#1}{#2}{#3}%
  \setlength{\textheight}{\@tempdima}%
  \setlength{\textwidth}{\@tempdimb}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\binding}
% \begin{macro}{\setbinding}
% The length \cs{binding} is an allowance on the spine margin for
% binding. \cs{setbinding}\marg{length} sets the \cs{binding}.
% \changes{v1.6180339c}{2008/12/29}{Added binding offset code to the
% layout functions}
%    \begin{macrocode}
\newlength{\binding}
\newcommand*{\setbinding}[1]{\setlength{\binding}{#1}}
  \setbinding{0pt}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\spinemargin}
% \begin{macro}{\foremargin}
% \begin{macro}{\setlrmargins}
% \cs{setlrmargins}\marg{L}\marg{R}\marg{r} sets the Left (spine)
% and Right (fore edge) margins with constant typeblock.
% \changes{v1.6180339c}{2008/12/29}{Added binding to \cs{setlrmargins}}
% \changes{v3.6k}{2013/05/14}{Marked \cs{setlrmargins} as being used}
%    \begin{macrocode}
\newlength{\spinemargin}
\newlength{\foremargin}
\newcommand{\setlrmargins}[3]{%
  \memsetmacroused\setlrmargins%
  \advance\paperwidth -\binding
  \setfillsize{\paperwidth}{\textwidth}{#1}{#2}{#3}%
  \setlength{\textwidth}{\@tempdimc}%
  \setlength{\spinemargin}{\@tempdima}%
  \setlength{\foremargin}{\@tempdimb}%
  \advance\paperwidth \binding
  \advance\spinemargin \binding}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\setlrmarginsandblock}
% \cs{setlrmarginsandblock}\marg{L}\marg{R}\marg{r} sets the Left (spine)
% and Right (fore edge) margins with variable typeblock.
% \changes{v1.6180339c}{2008/12/29}{Added binding to \cs{setlrmarginsandblock}}
%    \begin{macrocode}
\newcommand{\setlrmarginsandblock}[3]{%
  \advance\paperwidth -\binding
  \setfillsize{\paperwidth}{*}{#1}{#2}{#3}%
  \setlength{\textwidth}{\@tempdimc}%
  \setlength{\spinemargin}{\@tempdima}%
  \setlength{\foremargin}{\@tempdimb}%
  \advance\paperwidth \binding
  \advance\spinemargin \binding}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\uppermargin}
% \begin{macro}{\lowermargin}
% \begin{macro}{\setulmargins}
% \cs{setulmargins}\marg{L}\marg{R}\marg{r} sets the Left (upper)
% and Right (lower) margins with constant typeblock.
% \changes{v3.6k}{2013/05/14}{Marked \cs{setulmargins} as being used}
%    \begin{macrocode}
\newlength{\uppermargin}
\newlength{\lowermargin}
\newcommand{\setulmargins}[3]{%
  \memsetmacroused\setulmargins%
  \setfillsize{\paperheight}{\textheight}{#1}{#2}{#3}%
  \setlength{\textheight}{\@tempdimc}%
  \setlength{\uppermargin}{\@tempdima}%
  \setlength{\lowermargin}{\@tempdimb}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\setulmarginsandblock}
% \cs{setulmarginsandblock}\marg{L}\marg{R}\marg{r} sets the Left (upper)
% and Right (lower) margins with variable typeblock.
%    \begin{macrocode}
\newcommand{\setulmarginsandblock}[3]{%
  \setfillsize{\paperheight}{*}{#1}{#2}{#3}%
  \setlength{\textheight}{\@tempdimc}%
  \setlength{\uppermargin}{\@tempdima}%
  \setlength{\lowermargin}{\@tempdimb}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\headdrop}
% \begin{macro}{\setheaderspaces}
% \cs{setheaderspaces}\marg{L}\marg{R}\marg{r} sets the Left (head margin)
% and Right (headsep) spacing with constant headheight.
%    \begin{macrocode}
\newlength{\headdrop}
\newcommand{\setheaderspaces}[3]{%
  \setfillsize{\uppermargin}{\headheight}{#1}{#2}{#3}%
  \setlength{\headheight}{\@tempdimc}%
  \setlength{\headdrop}{\@tempdima}%
  \setlength{\headsep}{\@tempdimb}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\setheadfoot}
% \cs{setheadfoot}\marg{headheight}\marg{footskip}
% sets the headheight and the footskip.
%    \begin{macrocode}
\newcommand{\setheadfoot}[2]{%
  \setlength{\headheight}{#1}%
  \setlength{\footskip}{#2}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\setcolsepandrule}
% \cs{setcolsepandrule}\marg{colsep}\marg{thickness}
% sets the column separation and the rule thickness.
% \changes{v1.0}{2001/09/20}{Changed \cs{setcolseprule} to 
% \cs{setcolsepandrule} to match the documentation.}
%    \begin{macrocode}
\newcommand{\setcolsepandrule}[2]{%
  \setlength{\columnsep}{#1}%
  \setlength{\columnseprule}{#2}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\setmarginnotes}
% \cs{setmarginnotes}\marg{sep}\marg{width}\marg{push}
% sets the marginpar parameters.
% \changes{v3.6k}{2013/05/14}{Marked \cs{setmarginnotes} as being used}
%    \begin{macrocode}
\newcommand{\setmarginnotes}[3]{%
  \memsetmacroused\setmarginnotes%
  \setlength{\marginparsep}{#1}%
  \setlength{\marginparwidth}{#2}%
  \setlength{\marginparpush}{#3}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\setfootins}
%   \cs{setfootins}\marg{length}\marg{length} sets
%   \cs{skip}\cs{footins} and its minipage counterpart. It will also
%   set \cs{skip}\cs{footinsv@r} and similar for minipages to the same
%   values. These are used by for example \cs{twocolumnfootnotes}.
%    \begin{macrocode}
\newcommand\setfootins[2]{
  \setlength{\skip\footins}{#1}
  \setlength{\skip\footinsv@r}{#1}
  \setlength{\skip\@mpfootins}{#2}
  % not explicitly used 
  \setlength{\skip\@mpfootinsv@r}{#2}
}

%    \end{macrocode}
%   
% \end{macro}
%
%
%    Initialise the paper size and trimming to their default values.
%    \begin{macrocode}
\settrimmedsize{\stockheight}{\stockwidth}{*}
\settrims{\z@}{\z@}

%    \end{macrocode}
%
%    What now follows is the standard class's method for setting up
% the dimensions.
%
%    Set \cs{@tempdimb} to size-dependent initial line length and
% set \cs{@tempdima} to the maximum textwidth for the paper width, 
% an inch margin on either side. In the standard classes the initial
% line length is about 14\% greater than \cs{lxvchars}.
%    \begin{macrocode}
\setlength{\@tempdimb}{1.14\lxvchars}
\setlength\@tempdima{\paperwidth}
  \addtolength\@tempdima{-2in}
%    \end{macrocode}
%
% \begin{macro}{\textwidth}
% Now set the \cs{textwidth} depending on the number of columns. In twocolumn
% mode each column should be no wider than \cs{@tempdimb}.
%    \begin{macrocode}
\if@twocolumn
  \ifdim\@tempdima>2\@tempdimb\relax
    \setlength\textwidth{2\@tempdimb}
  \else
    \setlength\textwidth{\@tempdima}
  \fi
%    \end{macrocode}
% In onecolumn
% the text should not be wider than the minumum of the paperwidth (less
% 2in for the margins) and the maximum length of the character line.
%    \begin{macrocode}
\else
  \ifdim\@tempdima>\@tempdimb\relax
    \setlength\textwidth{\@tempdimb}
  \else
    \setlength\textwidth{\@tempdima}
  \fi
\fi
%    \end{macrocode}
% Adjust the width to be a whole number of points.
% \changes{v3.7g}{2018/03/09}{Switch to private truncating macro so we
% can disable truncation via class option}
%    \begin{macrocode}
\mem@settopoint\textwidth

%    \end{macrocode}
% \end{macro}
%  
% \begin{macro}{\textheight}
%    The \cs{textheight} is the height of the text block, excluding
% headers and footers. This is set according to the \cs{paperheight},
% to an integral number of lines, and allowing a 1in margin at the
% top and bottom and a further 1.5in for headers and footers.
%    \begin{macrocode}
\setlength\@tempdima{\paperheight}
  \addtolength\@tempdima{-3.5in}
%    \end{macrocode}
% Divide this height by the \cs{baselineskip} to get the number of lines.
% Then (re)calculate the \cs{textheight} and finally add the \cs{topskip}.
%    \begin{macrocode}
  \divide\@tempdima\baselineskip
\@tempcnta=\@tempdima
\setlength\textheight{\@tempcnta\baselineskip}
  \addtolength\textheight{\topskip}

%    \end{macrocode}
% \end{macro}
%
%    The margins are calculated. 
%
% \begin{macro}{\oddsidemargin}
% \begin{macro}{\marginparwidth}
% \begin{macro}{\evensidemargin}
%    The margins depend on the paper size, also for two sided
% printing the inner margin is made smaller than the outer.
%    \begin{macrocode}
\if@twoside
  \setlength\@tempdima       {\paperwidth}
  \addtolength\@tempdima     {-\textwidth}
  \setlength\oddsidemargin   {.4\@tempdima}
  \addtolength\oddsidemargin {-1in}
  \setlength\marginparwidth  {.6\@tempdima}
  \addtolength\marginparwidth{-\marginparsep}
  \addtolength\marginparwidth{-0.4in}
\else
  \setlength\@tempdima       {\paperwidth}
  \addtolength\@tempdima     {-\textwidth}
  \setlength\oddsidemargin   {.5\@tempdima}
  \addtolength\oddsidemargin {-1in}
  \setlength\marginparwidth  {.5\@tempdima}
  \addtolength\marginparwidth{-\marginparsep}
  \addtolength\marginparwidth{-0.8in} % don't know why this isn't .4
\fi
\ifdim\marginparwidth>2in
  \setlength\marginparwidth{2in}%
\fi
%    \end{macrocode}
% Set these values to integer numbers of points, and afterwards calculate the
% \cs{evensidemargin}.
% Jonathon Stickel  on 2008/05/30 noted that
% \cs{marginparwidth} had to be positive for the initial setting of the sidebar
% geometry through \cs{setsidebars}.
% \changes{v1.618033}{2008/06/02}{Ensured initial value of \cs{marginparwidth}
%  was positive}
% \changes{v3.7g}{2018/03/09}{Switch to private truncating macro so we
% can disable truncation via class option}
%    \begin{macrocode}
\mem@settopoint\oddsidemargin
\mem@settopoint\marginparwidth
\ifdim\marginparwidth<1pt \setlength\marginparwidth{1pt}\fi

\setlength\evensidemargin  {\paperwidth}
\addtolength\evensidemargin{-2in}
\addtolength\evensidemargin{-\textwidth}
\addtolength\evensidemargin{-\oddsidemargin}
\mem@settopoint\evensidemargin
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\topmargin}
%    The \cs{topmargin} is the distance below the top of the printable
% area (1in below the top of the paper) and the top of the box
% containing the running head.
% \changes{v3.7g}{2018/03/09}{Switch to private truncating macro so we
% can disable truncation via class option}
%    \begin{macrocode}
\setlength\topmargin  {\paperheight}
\addtolength\topmargin{-2in}
\addtolength\topmargin{-\headheight}
\addtolength\topmargin{-\headsep}
\addtolength\topmargin{-\textheight}
\addtolength\topmargin{-\footskip}
\addtolength\topmargin{-.5\topmargin}
\mem@settopoint\topmargin

%    \end{macrocode}
% \end{macro}
%
% That is the end of the classical algorithm. Now calculate the 
% user-friendly dimensions. The calculations are simpler than in
% the general case as the \cs{paperwidth} and \cs{paperheight} is the 
% same as the \cs{stockwidth} and \cs{stockheight}. 
%
%    We can get the spine 
% and edge margins from the \cs{oddsidemargin}.
%    \begin{macrocode}
\setlength{\spinemargin}{\oddsidemargin}
\addtolength{\spinemargin}{1in}
\setlrmargins{\spinemargin}{*}{*}

%    \end{macrocode}
%
%    Similarly we can get the upper and lower margins from the
% \cs{topmargin}, \cs{headheight} and \cs{headskip}.
%    \begin{macrocode}
\setlength{\uppermargin}{\topmargin}
\addtolength{\uppermargin}{1in}
\addtolength{\uppermargin}{\headheight}
\addtolength{\uppermargin}{\headsep}
\setulmargins{\uppermargin}{*}{*}

%    \end{macrocode}
%
% \begin{macro}{\@memznegtest}
% DA suggested this in a private email (2003/002/13) to make error
% checking and reporting a bit more (space) efficient. Use like \\
% \verb?\@memznegtest{\marginparsep}? instead of \\
% \begin{verbatim}
% \ifdim\marginparsep>\z@\else
%    \@memerror{\protect\marginparsep\space is zero or negative}{\@ehd}%
% \fi
% \end{verbatim}
% If its length variable argument is zero or less it reports an error.
% 
% \changes{v1.4}{2003/02/27}{Added \cs{@memznegtest}}
% \changes{v1.618033}{2008/06/02}{Changed \cs{@memznegtest} and 
%         \cs{@memnegtest} to issue warnings instead of errors}
%
%    \begin{macrocode}
\newcommand*{\@memznegtest}[1]{%
  \ifdim#1>\z@\else
    \@memwarn{\protect#1\space is zero or negative}%
  \fi}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@memnegtest}
% Reports an error if its length variable argument is negative.
% \changes{v1.4}{2003/02/27}{Added \cs{@memnegtest}}
%    \begin{macrocode}
\newcommand*{\@memnegtest}[1]{%
  \ifdim#1<\z@
    \@memwarn{\protect#1\space is negative}%
  \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@mclassicht}
% The classic adjustment of the \cs{textheight} to get an integral number 
% of lines (given an integral number of baselineskips returns a height
% giving one more line in the block).
% \changes{v1.61803}{2008/01/30}{Added \cs{m@mclassicht}, \cs{m@mlinesht}
%             and \cs{m@mnearestht} (mempatch v4.5)}
%    \begin{macrocode}
\newcommand*{\m@mclassicht}{%
  \setlength{\@tempdima}{\textheight}%
  \divide\@tempdima \baselineskip
  \@tempcnta=\@tempdima
  \setlength{\textheight}{\@tempcnta\baselineskip}%
  \addtolength{\textheight}{\topskip}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@mlinesht}
% The adjustment of the \cs{textheight} to get an integral number 
% of lines (given an inegral number of baselineskips returns a height
% giving that number of lines).
%    \begin{macrocode}
\newcommand*{\m@mlinesht}{%
  \setlength{\@tempdima}{\textheight}%
  \advance\@tempdima -\baselineskip
  \divide\@tempdima \baselineskip
  \@tempcnta=\@tempdima
  \setlength{\textheight}{\@tempcnta\baselineskip}%
  \addtolength{\textheight}{\topskip}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@mnearestht}
% The adjustment of the \cs{textheight} to get an integral number 
% of lines with the calculated height being as the closest to the given 
% height. Algorithm supplied by Lars Madsen and Morten H{\o}gholm on
% 2006/07/27.
%    \begin{macrocode}
\newcommand*{\m@mnearestht}{%
  \setlength{\@tempdima}{\textheight}%
  \advance\@tempdima -\topskip
  \advance\@tempdima 0.5\baselineskip
  \divide\@tempdima \baselineskip
  \@tempcnta=\@tempdima
  \setlength{\textheight}{\@tempcnta\baselineskip}%
  \addtolength{\textheight}{\topskip}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\mem@autoadjust@marginparwidth}
% This macro implements an algorithm, to automatically adjust
% \cs{marginparwidth} to the current values of \cs{spinemargin} and
% \cs{foremargin} (i.e., the inner and outer margins). It may be used
% within \cs{fixthelayout} in case the user has not changed 
% \cs{marginparwidth} using \cs{setmarginnotes}.
%    \begin{macrocode}
\newcommand\mem@autoadjust@marginparwidth{%
  \if@twocolumn
    \memsetlengthmin\marginparwidth\spinemargin\foremargin
  \else
    \if@twoside
      \ifcase\m@mmpar@margin\relax% 0 - left
        \memsetlengthmin\marginparwidth\spinemargin\foremargin
      \or% 1 - right
        \memsetlengthmin\marginparwidth\spinemargin\foremargin
      \or% 2 - outer
        \setlength\marginparwidth{\foremargin}
      \or% 3 - inner
        \setlength\marginparwidth{\spinemargin}
      \fi
    \else % oneside
      \ifnum\m@mmpar@margin=0% left
        \setlength\marginparwidth{\spinemargin}
      \else% right
        \setlength\marginparwidth{\foremargin}
      \fi
    \fi
  \fi
  \addtolength\marginparwidth{-2\marginparsep}
  \ifdim\marginparwidth<1pt\setlength\marginparwidth{1pt}\fi%
}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\mem@reset@used@macros}
%   This macro is used to unset used macros. It is a manually
%   maintained macro. A better version would have been to let
%   \cs{memsetmacroused} record its use in a list, and then loop over
%   this list. Maybe some other time.
%    \begin{macrocode}
\newcommand\mem@reset@used@macros{%
  \memsetmacrounused\setmarginnotes
  \memsetmacrounused\settypeblocksize
  \memsetmacrounused\setulmargins
  \memsetmacrounused\setlrmargins
}

%    \end{macrocode}
%   
% \end{macro}
%
% \begin{macro}{\checkthelayout}
% \cs{checkthelayout}\oarg{text} is the user level macro for
% checking the layout. The \meta{text} argument controls which
% algorithm should be used to calculate the \cs{textheight}.
% \changes{v1.61803}{2008/01/30}{Extended \cs{checkthelayout} to include a choice
%          of algorithms (mempatch v4.5)}
% \changes{v1.61803}{2008/01/30}{Changed some page layout tests to negative from zero or negative 
%                   (mempatch v4.5)}
%    \begin{macrocode}
\newcommand*{\checkthelayout}[1][classic]{%
%    \end{macrocode}
% First check the dimensions are not (zero or) negative.
%    \begin{macrocode}
  \@memnegtest{\trimedge}
  \@memnegtest{\trimtop}
  \@memznegtest{\stockwidth}
  \@memznegtest{\paperwidth}
  \@memznegtest{\textwidth}
  \@memnegtest{\spinemargin}
  \@memnegtest{\foremargin}
  \@memznegtest{\marginparsep}
  \@memznegtest{\marginparwidth}
  \@memznegtest{\stockheight}
  \@memznegtest{\paperheight}
  \@memznegtest{\textheight}
  \@memnegtest{\uppermargin}
  \@memnegtest{\lowermargin}
  \@memnegtest{\headheight}
  \@memnegtest{\headsep}
  \@memnegtest{\footskip}
%    \end{macrocode}
%
%    Carry on regardless. We may need to adjust the \cs{textheight} 
% to get an integral number of lines.
%    \begin{macrocode}
  \nametest{#1}{classic}%
  \ifsamename
    \m@mclassicht
  \else
    \nametest{#1}{lines}%
    \ifsamename
      \m@mlinesht
    \else
      \nametest{#1}{nearest}%
      \ifsamename
        \m@mnearestht
      \else
        \nametest{#1}{fixed}
        \ifsamename
        \else%    not classic, lines, nearest, or fixed
          \@memerror{Optional argument is not one of:\MessageBreak
                     classic, fixed, lines, or nearest. \MessageBreak
                     I will assume the default}%
                    {\@ehc}%
        \fi
      \fi
    \fi
  \fi
  \setulmargins{\uppermargin}{*}{*}
%    \end{macrocode}
%
% Check that all the sums add up correctly, or
% at least to within a small (\cs{@tempdimb}) error.
% \changes{v1.618033}{2008/06/02}{Added more information about problematic
%  layout values}
%    \begin{macrocode}
  \@tempdimb = -1pt  
  \@tempdima=\stockwidth
  \advance\@tempdima -\trimedge
  \advance\@tempdima -\paperwidth
  \ifdim\@tempdima<\@tempdimb
    \@tempdima = -\@tempdima
    \@memerror{\protect\paperwidth\space (\the\paperwidth) and/or 
                        \protect\trimedge\space (\the\trimedge)
                        are too large for \protect\stockwidth\space (\the\stockwidth)
                        by \the\@tempdima}%
                       {\@ehd}
  \fi
  \@tempdima = \paperwidth
  \advance\@tempdima -\foremargin
  \advance\@tempdima -\textwidth
  \advance\@tempdima -\spinemargin
  \ifdim\@tempdima<\@tempdimb
    \@tempdima = -\@tempdima
    \@memerror{\protect\spinemargin\space (\the\spinemargin) and/or 
                        \protect\textwidth\space (\the\textwidth) and/or
                        \protect\foremargin\space (\the\foremargin)
                        are too large for \protect\paperwidth\space (\the\paperwidth)
                        by \the\@tempdima}%
                       {\@ehd}
  \fi
  \@tempdima = \stockheight
  \advance\@tempdima -\trimtop
  \advance\@tempdima -\paperheight
  \ifdim\@tempdima<\@tempdimb
    \@tempdima = -\@tempdima
    \@memerror{\protect\paperheight\space (\the\paperheight) and/or 
                        \protect\trimtop\space (\the\trimtop)
                        are too large for \protect\stockheight\space (\the\stockheight)
                        by \the\@tempdima}%
                       {\@ehd}
  \fi
  \@tempdima = \paperheight
  \advance\@tempdima -\uppermargin
  \advance\@tempdima -\textheight
  \advance\@tempdima -\lowermargin
  \ifdim\@tempdima<\@tempdimb
    \@tempdima = -\@tempdima
    \@memerror{\protect\uppermargin\space (\the\uppermargin) and/or 
                        \protect\textheight\space (\the\textheight) and/or 
                        \protect\lowermargin\space (\the\lowermargin)
                        are too large for \protect\paperheight\space (\the\paperheight)
                        by \the\@tempdima}%
                       {\@ehd}
  \fi
  \@tempdima = \uppermargin
  \advance\@tempdima -\headheight
  \advance\@tempdima -\headsep
  \ifdim\@tempdima<\@tempdimb
    \@tempdima = -\@tempdima
    \@memerror{\protect\headheight\space (\the\headheight) and/or 
                        \protect\headsep\space (\the\headsep)
                        are too large for \protect\uppermargin\space (\the\uppermargin)
                        by \the\@tempdima}%
                       {\@ehd}
  \fi
  \@tempdima = \lowermargin
  \advance\@tempdima -\footskip
  \ifdim\@tempdima<\z@
    \@tempdima = -\@tempdima
    \@memerror{\protect\footskip\space (\the\footskip)
                        is too large for \protect\lowermargin\space (\the\lowermargin)
                        by \the\@tempdima}%
                       {\@ehd}
  \fi}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\fixthelayout}
%   Calculate the normal
% \LaTeX{} page layout parameter values. We'll do the heights first
% as they are independent of the number of columns and the side printing.
% \changes{v1.0a}{2002/01/18}{Added \cs{fixthelayout}}
%    \begin{macrocode}
\newcommand*{\fixthelayout}{%
  \topmargin = \trimtop
    \advance\topmargin \uppermargin
    \advance\topmargin -\headsep
    \advance\topmargin -\headheight
    \advance\topmargin -1in\relax
%    \end{macrocode}
%
%    Now the \cs{oddsidemargin}.
%    \begin{macrocode}
  \oddsidemargin = \stockwidth
    \advance\oddsidemargin -\trimedge
    \advance\oddsidemargin -\paperwidth
    \advance\oddsidemargin \spinemargin
    \advance\oddsidemargin -1in\relax
%    \end{macrocode}
%
%    And the \cs{evensidemargin}.
%    \begin{macrocode}
  \evensidemargin = \trimedge
    \advance\evensidemargin \foremargin
    \advance\evensidemargin -1in\relax
%    \end{macrocode}
%
%
%    Set the values to the nearest whole point.
% \changes{v3.7g}{2018/03/09}{Switch to private truncating macro so we
% can disable truncation via class option}
%    \begin{macrocode}
  \mem@settopoint\textwidth
  \mem@settopoint\oddsidemargin
  \mem@settopoint\evensidemargin
%    \end{macrocode}
% Fix standard page layouts after possible change of \cs{textwidth}.
% \changes{v1.6180339f}{2009/03/16}{Added \cs{fixheaderwidths} to \cs{fixthelayout}}
%    \begin{macrocode}
  \fixheaderwidths
%    \end{macrocode}
% Autoadjust \cs{marginparwidth} unless the user have used
% \cs{setmarginnotes}. Plus add a reset of the recordedmacros, just in
% case \cs{fixthelayout} is being used several times.
% \changes{v3.6k}{2013/05/15}{Added autoadjust}
%    \begin{macrocode}
  \memifmacroused\setmarginnotes{}{\mem@autoadjust@marginparwidth}
  \mem@reset@used@macros
}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\typeoutlayout}
% \begin{macro}{\settypeoutlayoutunit}
% \begin{macro}{\mem@typeouttwolengths}
% \begin{macro}{\mem@typeoutonelength}
% Why not type out the calculated versions of the designed values?
% \changes{v1.0a}{2002/01/18}{Added \cs{typeoutlayout}}
% \changes{v1.0a}{2002/01/25}{Added column info to \cs{typeoutlayout}}
% \changes{v1.61803}{2008/01/30}{Added sidecap and sidebar data to \cs{typeoutlayout}
%                   (mempatch v4.6)}
% \changes{v1.61803398d}{2010/02/04}{Added information about side feet}
% \changes{v3.6g}{2010/09/17}{Added feature such that user can change
% the unit used by \cs{typeoutlayout}, requested by Rasmus Villemoes}
% Using the macro \cs{settypeoutlayoutunit}\marg{unit} before
% \cs{typeoutlayout} (or more often \cs{checkandfixthelayout}), the
% user can choose the unit in which the list is typeset. The code is
% inspired by the \texttt{printlen} package.
% \changes{v3.8.3}{2024/01/31}{A lot easier to implement \cs{settypeoutlayoutunit} via expl3}
%    \begin{macrocode}
\ExplSyntaxOn
\newcommand\settypeoutlayoutunit[1]{
  \def\mem@tl@unit{#1}
  \str_case_e:nnF{#1}{
    {pt}{ \def\mem@tl@unitperpt{1.0}       }
    {pc}{ \def\mem@tl@unitperpt{0.083333}  }
    {in}{ \def\mem@tl@unitperpt{0.013837}  }
    {mm}{ \def\mem@tl@unitperpt{0.351459}  }
    {cm}{ \def\mem@tl@unitperpt{0.0351459} }
    {bp}{ \def\mem@tl@unitperpt{0.996264}  }
    {dd}{ \def\mem@tl@unitperpt{0.9345718} }
    {cc}{ \def\mem@tl@unitperpt{0.0778809} }
  }{ % or error
    \@memerror{Unknown~unit~'#1'~not~suitable~for~layout\MessageBreak listing}{}
  }
}
\ExplSyntaxOff

 %\newcommand\settypeoutlayoutunit[1]{
 %  \nametest{#1}{pt}
 %  \ifsamename
 %    \def\mem@tl@unit{#1}
 %    \def\mem@tl@unitperpt{1.0}
 %  \else 
 %    \nametest{#1}{pc}
 %    \ifsamename
 %      \def\mem@tl@unit{#1}
 %      \def\mem@tl@unitperpt{0.083333}
 %    \else
 %      \nametest{#1}{in}
 %      \ifsamename
 %        \def\mem@tl@unit{#1}
 %        \def\mem@tl@unitperpt{0.013837}
 %      \else
 %        \nametest{#1}{mm}
 %        \ifsamename
 %          \def\mem@tl@unit{#1}
 %          \def\mem@tl@unitperpt{0.351459}
 %        \else
 %          \nametest{#1}{cm}
 %          \ifsamename
 %            \def\mem@tl@unit{#1}
 %            \def\mem@tl@unitperpt{0.0351459}
 %          \else
 %            \nametest{#1}{bp}
 %            \ifsamename
 %              \def\mem@tl@unit{#1}
 %              \def\mem@tl@unitperpt{0.996264}
 %            \else
 %              \nametest{#1}{dd}
 %              \ifsamename
 %                \def\mem@tl@unit{#1}
 %                \def\mem@tl@unitperpt{0.9345718}
 %              \else
 %                \nametest{#1}{cc}
 %                \ifsamename
 %                  \def\mem@tl@unit{#1}
 %                  \def\mem@tl@unitperpt{0.0778809}
 %                \else
 %                  \@memerror{Unknown unit '#1' not suitable for layout listing}{}
 %                \fi
 %              \fi
 %            \fi
 %          \fi
 %        \fi
 %      \fi
 %    \fi
 %  \fi
 %}
%    \end{macrocode}
% Default value is \texttt{pt}, other supported are \texttt{mm},
% \texttt{cm}, \texttt{in}, \texttt{bp}, \texttt{dd} and \texttt{cc}.
%    \begin{macrocode}
\settypeoutlayoutunit{pt}
%    \end{macrocode}
% To help with the typesetting, we need to helper macros:
%    \begin{macrocode}
\newcommand\mem@typeouttwolengths[4]{
  % #1 = text before
  % #2 = first length
  % #3 = text between
  % #4 = second length
  \setlength\@tempdimc{\mem@tl@unitperpt #2}
  \edef\l@first{\strip@pt\@tempdimc}% 
  \setlength\@tempdimc{\mem@tl@unitperpt #4}
  \edef\l@second{\strip@pt\@tempdimc}% 
  \typeout{#1: \l@first\mem@tl@unit\space#3\space\l@second\mem@tl@unit}
}
\newcommand\mem@typeoutonelength[2]{
  % #1 = text before
  % #2 = first length
  \setlength\@tempdimc{\mem@tl@unitperpt #2}
  \edef\l@first{\strip@pt\@tempdimc}% 
  \typeout{#1: \l@first\mem@tl@unit}
}
%    \end{macrocode}
% Thirdly \cs{typeoutlayout} need to be rewritten to take care of the
% extra convertions
%    \begin{macrocode}
\newcommand*{\typeoutlayout}{%
  \typeout{}
  \typeout{******************************************************}
 %   \typeout{Stock height and width: 
 %                  \the\stockheight\space by \the\stockwidth}
 %   \typeout{Top and edge trims: 
 %                  \the\trimtop\space and \the\trimedge}
 %   \typeout{Page height and width: 
 %                  \the\paperheight\space by \the\paperwidth}
 %   \typeout{Text height and width: 
 %                  \the\textheight\space by \the\textwidth}
 %   \typeout{Spine and edge margins: 
 %                  \the\spinemargin\space and \the\foremargin}
 %   \typeout{Upper and lower margins: 
 %                  \the\uppermargin\space and \the\lowermargin}
 %   \typeout{Headheight and headsep: 
 %                  \the\headheight\space and \the\headsep}
 %   \typeout{Footskip: 
 %                  \the\footskip}
 %   \typeout{Columnsep and columnseprule: 
 %                  \the\columnsep\space and \the\columnseprule}
 %   \typeout{Marginparsep and marginparwidth: 
 %                  \the\marginparsep\space and \the\marginparwidth}
 %   \typeout{Sidecapsep and sidecapwidth:
 %                   \the\sidecapsep\space and \the\sidecapwidth}
 %   \typeout{Sidebarhsep and sidebarwidth:
 %                   \the\sidebarhsep\space and \the\sidebarwidth}
 %   \typeout{Sidebarvsep and sidebartopsep:
 %                   \the\sidebarvsep\space and \the\sidebartopsep}
 %   \typeout{Sidebarheight:
 %                   \the\dimen\sideins}
 %   \typeout{Sidefoothsep and sidefootwidth:
 %                   \the\sidefoothsep\space and \the\sidefootwidth}
 %   \typeout{Sidefootvsep and sidefootheight:
 %                   \the\sidefootvsep\space and \the\sidefootheight}
  \mem@typeouttwolengths{Stock height and width}{\stockheight}{by}{\stockwidth}
  \mem@typeouttwolengths{Top and edge trims}{\trimtop}{and}{\trimedge}
  \mem@typeouttwolengths{Page height and width}{\paperheight}{by}{\paperwidth}
  \mem@typeouttwolengths{Text height and width}{\textheight}{by}{\textwidth}
  \mem@typeouttwolengths{Spine and edge margins}{\spinemargin}{and}{\foremargin}
  \mem@typeouttwolengths{Upper and lower margins}{\uppermargin}{and}{\lowermargin}
  \mem@typeouttwolengths{Headheight and headsep}{\headheight}{and}{\headsep}
  \mem@typeoutonelength{Footskip}{\footskip}
  \mem@typeouttwolengths{Columnsep and columnseprule}{\columnsep}{and}{\columnseprule}
  \mem@typeouttwolengths{Marginparsep and marginparwidth}{\marginparsep}{and}{\marginparwidth}
  \mem@typeouttwolengths{Sidecapsep and sidecapwidth}{\sidecapsep}{and}{\sidecapwidth}
  \mem@typeouttwolengths{Sidebarhsep and sidebarwidth}{\sidebarhsep}{and}{\sidebarwidth}
  \mem@typeouttwolengths{Sidebarvsep and sidebartopsep}{\sidebarvsep}{and}{\sidebartopsep}
  \mem@typeoutonelength{Sidebarheight}{\dimen\sideins}
  \mem@typeouttwolengths{Sidefoothsep and sidefootwidth}{\sidefoothsep}{and}{\sidefootwidth}
  \mem@typeouttwolengths{Sidefootvsep and sidefootheight}{\sidefootvsep}{and}{\sidefootheight}
  \typeout{******************************************************}
  \typeout{}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\checkandfixthelayout}
% This macro checks and fixes the layout, and reports the result. It takes the
% same optional argument as \cs{checkthelayout}.
% \changes{v0.2}{2001/06/03}{Replaced \cs{fixpagelayout} by \cs{checkandfixthelayout}}
% \changes{v1.0a}{2002/01/18}{Partitioned \cs{checkandfixthelayout}}
% \changes{v1.61803}{2008/01/30}{Changed \cs{checkandfixthelayout}
%          for the extended \cs{checkthelayout} (mempatch v4.5)}
%    \begin{macrocode}
\newcommand*{\checkandfixthelayout}[1][classic]{%
  \checkthelayout[#1]%
  \fixthelayout
  \typeoutlayout}

%    \end{macrocode}
% \end{macro}
%
% 
% \begin{macro}{\mem@fixpagelayout}
% \changes{v3.7g}{2018/03/09}{Changed to use this instead of
% \cs{fixpdflayout} and \cs{fixdvipslayout}, then we no longer need \Lpack{luatex85}}
% Outputting the size of the output document. This is a little tricky as
% the various engines do not quite agree on which variables to use. As
% of 2018 we will be using this: First of \cs{pdfpageheight/width} is
% used by pdf(e)tex based enginges. We set them if they are
% defined. Just in case someone need to be able to patch this, we make
% it into a macro and just run it at the start of the cocument
%    \begin{macrocode}
\newcommand\mem@fixpagelayout{%
  \@ifundefined{pdfpageheight}{}{\pdfpageheight=\the\stockheight}
  \@ifundefined{pdfpagewidth}{}{\pdfpagewidth=\the\stockwidth}
%    \end{macrocode}
% Next comes the two macros that recent luaTeX versions use instead of
% the \cs{pdf...} equivalents.
%    \begin{macrocode}
  \@ifundefined{pageheight}{}{\pageheight=\the\stockheight}
  \@ifundefined{pagewidth}{}{\pagewidth=\the\stockwidth}
%    \end{macrocode}
% If is unclear why these were added to the class sources in the first
% place, we'll just leave them.
%    \begin{macrocode}
  \@ifundefined{pdfvorigin}{}{\ifdim\pdfvorigin=0pt\pdfvorigin=1in\fi}
  \@ifundefined{pdfhorigin}{}{\ifdim\pdfhorigin=0pt\pdfhorigin=1in\fi}
%    \end{macrocode}
% Lastly we need to output a special to the DVI, but other engines can
% also understand specials, so to not end up getting those pesky
% non-PDF special warnings, we need some engine tests before emiting
% the data to the DVI.
%    \begin{macrocode}
  \ifluatex\else
    \ifxetex\else
      \ifpdf\else
        \AtBeginDvi{\special{papersize=\the\stockwidth,\the\stockheight}}
      \fi
    \fi
  \fi    
}

\AtBeginDocument{\mem@fixpagelayout}
%    \end{macrocode}
% 
% \changes{v3.7k}{2020/03/25}{Added a link to \cs{mem@fixpagelayout}}
%    \begin{macrocode}
\let\refixpagelayout\mem@fixpagelayout

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\fixpdflayout}
% \begin{macro}{\fixdvipslayout}
% As of 2018 these are disabled
% ^^A % Page layout with pdf\LaTeX{} seems a bit iffy.
% ^^A % At the suggestion of Lars Madsen, help with 
% ^^A % setting viewer (e.g., ghostview)
% ^^A % window sizes for dvi/ps. \cs{fixdvipslayout} does for \file{dvi} output
% ^^A % as \cs{fixpdflayout} does for \file{pdf} output.
% \changes{v1.4}{2003/11/22}{Added \cs{fixpdflayout} (from patch v1.6)}
% \changes{v1.4}{2003/12/01}{Added \cs{fixdvipslayout} }
% \changes{v1.61803398}{2009/08/17}{on ctt dynamotwain suggested a
% change to \cs{fixpdflayout} and the following \cs{AtBeginDocument}
% such that the \cs{special} is not outputtet when running xelatex}
%    \begin{macrocode}
\newcommand*{\fixpdflayout}{%
  \ClassWarning{memoir}{As of 2018, \string\fixpdflayout\ is no longer used}
 % \pdfpageheight=\the\stockheight
 % \pdfpagewidth=\the\stockwidth
 % \ifxetex\else
 % \ifdim\pdfvorigin=0pt\pdfvorigin=1in\fi
 % \ifdim\pdfhorigin=0pt\pdfhorigin=1in\fi
 % \fi
}
\newcommand*{\fixdvipslayout}{%
  \ClassWarning{memoir}{As of 2018, \string\fixdvipslayout\ is no longer used}
  %\AtBeginDvi{\special{papersize=\the\stockwidth,\the\stockheight}}
}
%    \end{macrocode}

% ^^A % \AtBeginDocument{%
% ^^A %   \ifxetex
% ^^A %     \fixpdflayout
% ^^A %   \else
% ^^A %     \ifpdf
% ^^A %       \ifnum\pdfoutput<\@ne
% ^^A %         \fixdvipslayout
% ^^A %       \else
% ^^A %         \fixpdflayout
% ^^A %       \fi
% ^^A %     \else
% ^^A %       \fixdvipslayout
% ^^A %     \fi
% ^^A %   \fi}

%
% ^^A % With a landscape document when going \texttt{latex -> dvips} the 
% ^^A % resulting \file{.ps} file
% ^^A % may apear upside down in \texttt{ghostview}. If this happens, try putting
% ^^A % the following in the document preamble:
% ^^A % \begin{verbatim}
% ^^A % \addtodef{\fixdvipslayout}{}{%
% ^^A %   \special{!TeXDict begin /landplus90{true}store end }}
% ^^A % \end{verbatim}
% ^^A % See \texttt{http://www.radicaleye.com.dvips.html} (DVIPS Home Page) for
% ^^A % an explanation.
% ^^A %
% ^^A %  Some other potential specials for PostScript printing may be 
% ^^A % (at least for an HP 5SiMx LaserJet duplex printer):
% ^^A % \begin{verbatim}
% ^^A % \special{!TeXDict begin <</Duplex true>> 
% ^^A %                         setpagedevice end} % duplex
% ^^A % \special{!TeXDict begin <</Tumble true>> 
% ^^A %                         setpagedevice end} % short side binding
% ^^A % \end{verbatim}
% \end{macro}
% \end{macro}
%
% 
% \begin{macro}{\typeoutstandardlayout}
% Types out the current values of the standard page layout parameters.
% \changes{v1.0a}{2002/01/25}{Added \cs{typeoutstandardlayout}}
% \changes{v3.6g}{2010/09/17}{changed such that the user can change
% the unit being used}
%    \begin{macrocode}
\newcommand{\typeoutstandardlayout}{%
  \typeout{}
  \typeout{******************************************************}
 %   \typeout{Page height and width: 
 %                 \the\paperheight\space by \the\paperwidth}
 \mem@typeouttwolengths{Page height and width}{\paperheight}{by}{\paperwidth}
 %   \typeout{Text height and width: 
 %                \the\textheight\space by \the\textwidth}
 \mem@typeouttwolengths{Text height and width}{\textheight}{by}{\textwidth}
 %   \typeout{Oddside and evenside margins: 
 %                 \the\oddsidemargin\space and \the\evensidemargin}
 \mem@typeouttwolengths{Oddside and evenside margins}{\oddsidemargin}{and}{\evensidemargin}
 %   \typeout{Topmargin and footskip: 
 %                 \the\topmargin\space and \the\footskip}
 \mem@typeouttwolengths{Topmargin and footskip}{\topmargin}{and}{\footskip}
 %   \typeout{Headheight and headsep: 
 %                 \the\headheight\space and \the\headsep}
 \mem@typeouttwolengths{Headheight and headsep}{\headheight}{and}{\headsep}
 %   \typeout{Columnsep and columnseprule: 
 %                 \the\columnsep\space and \the\columnseprule}
 \mem@typeouttwolengths{Columnsep and columnseprule}{\columnsep}{and}{\columnseprule}
 %   \typeout{Marginparsep and marginparwidth: 
 %                 \the\marginparsep\space and \the\marginparwidth}
 \mem@typeouttwolengths{Marginparsep and marginparwidth}{\marginparsep}{and}{\marginparwidth}
  \typeout{******************************************************}
  \typeout{}
}

%    \end{macrocode}
% \end{macro}
%
%
% \subsection{Some predefined layouts}
%
% A few predefined layouts for the textblock are presented. The \cs{checkandfixthelayout}
% macro \emph{must} be called afterwards.
%
% \begin{macro}{\medievalpage}
% This implements Jan Tschichold's reconstruction of the page and textblock
% layout used by medieval scribes and the early printers.
% The spine, top, edge and bottom margins are in the ratios 2:3:4:6.
%
% \cs{medievalpage}\oarg{num} positions the typeblock on the page with the
% margins in the above ratios. The spine margin is (page width)/\meta{num} 
% (default 9). This must be an integer.
% \changes{v1.61803}{2008/01/30}{Added \cs{medievalpage}}
%    \begin{macrocode}
%%%% s = w/#1, t = 1.5s, e = 2s, f = 3s
\newcommand*{\medievalpage}[1][9]{%
  \spinemargin=\paperwidth
  \divide\spinemargin #1\relax
  \uppermargin = 1.5\spinemargin
  \setlrmarginsandblock{\spinemargin}{*}{2}
  \setulmarginsandblock{\uppermargin}{*}{2}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\isopage}
% An implementation of Bringhurst's layout for ISO proportioned pages.
% It works for any page though. The edge margin is twice the spine,
% and the bottom margin is twice the top. 
%
% \cs{isopage}\oarg{num} positions and sizes the typeblock on the page
% according to the above ratios. The spine is (page width)/\meta{num}
% and the top margin id (page height)/\meta{num}. \meta{num} must be
% an integer.
% \changes{v1.61803}{2008/01/30}{Added \cs{isopage}}
%    \begin{macrocode}
% s = w/#1, e = 2s, t = h/#1, f = 2h
\newcommand*{\isopage}[1][9]{%
  \spinemargin=\paperwidth
  \divide\spinemargin #1\relax
  \uppermargin=\paperheight
  \divide\uppermargin #1\relax
  \setlrmarginsandblock{\spinemargin}{*}{2}
  \setulmarginsandblock{\uppermargin}{*}{2}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\semiisopage}
% An variation on Bringhurst's layout for ISO proportioned pages.
% It works for any page though. The top margin is the same as the spine,
% and the edge and bottom margins are twice the spine.
%
% \cs{semiisopage}\oarg{num} positions and sizes the typeblock on the page
% according to the above ratios. The spine is (page width)/\meta{num}.
% \meta{num} must be  an integer.
% \changes{v1.61803}{2008/01/30}{Added \cs{isopage}}
%    \begin{macrocode}
%%% s = w/#1, t = s, e = 2s, f = e
\newcommand*{\semiisopage}[1][9]{%
  \spinemargin=\paperwidth
  \divide\spinemargin #1\relax
  \uppermargin=\spinemargin
  \setlrmarginsandblock{\spinemargin}{*}{2}
  \setulmarginsandblock{\uppermargin}{*}{2}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\setpagebl}
% \begin{macro}{\setpageml}
% \begin{macro}{\setpagetl}
% \begin{macro}{\setpagetm}
% \cs{setpagebl}\marg{height}\marg{width}\marg{ratio} sets a page smaller than
% the stock size at the bottom left of the stock. The arguments are the
% the same as for \cs{settrimmedsize};
% \meta{height}, \meta{width} and \meta{ratio} of height and width 
% (choose any two) of the desired page size. The trims are adjusted to suit.
% \cs{setpagetl} puts the page at the top left, \cs{setpageml} at the
% middle left, and \cs{setpagetm} at the top middle.
% \changes{v1.61803}{2008/01/30}{Added \cs{setpagebl}, \cs{setpageml}, and
%                    \cs{setpagetl}}
% \changes{v1.6180339c}{2008/12/26}{Added \cs{setpagetm}}
%    \begin{macrocode}
\newcommand*{\setpagebl}[3]{%
  \settrimmedsize{#1}{#2}{#3}%
  \trimtop=\stockheight \advance\trimtop -\paperheight
  \trimedge=\stockwidth \advance\trimedge -\paperwidth}
\newcommand*{\setpageml}[3]{%
  \settrimmedsize{#1}{#2}{#3}
  \trimtop=\stockheight \advance\trimtop -\paperheight 
    \advance\trimtop -0.5\trimtop
  \trimedge=\stockwidth \advance\trimedge -\paperwidth}
\newcommand*{\setpagetl}[3]{%
  \settrimmedsize{#1}{#2}{#3}
  \trimtop=0pt
  \trimedge=\stockwidth \advance\trimedge -\paperwidth}
\newcommand*{\setpagetm}[3]{%
  \settrimmedsize{#1}{#2}{#3}%
  \trimtop=0pt
  \trimedge=\stockwidth \advance\trimedge -\paperwidth
  \advance\trimedge -0.5\trimedge}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\setpagetr}
% \begin{macro}{\setpagemr}
% \begin{macro}{\setpagebr}
% \begin{macro}{\setpagebm}
% \begin{macro}{\setpagecc}
% Similar to those above, these macros set the page on the stock
% at the top right, middle right, bottom right, bottom middle, and centered.
% \changes{v1.6180339c}{2008/12/26}{Added \cs{setpagetr}, \cs{setpagemr}, \cs{setpagebr},
%                       \cs{setpagebm} and \cs{setpagecc}}
% \changes{v3.7k}{2020/03/15}{Added \cs{setpagemm} as an alias to \cs{setpagecc}}
%    \begin{macrocode}
\newcommand*{\setpagetr}[3]{%
  \settrimmedsize{#1}{#2}{#3}%
  \trimtop=0pt
  \trimedge=0pt}
\newcommand*{\setpagemr}[3]{%
  \settrimmedsize{#1}{#2}{#3}%
  \trimtop=\stockheight \advance\trimtop -\paperheight
    \advance\trimtop -0.5\trimtop
  \trimedge=0pt}
\newcommand*{\setpagebr}[3]{%
  \settrimmedsize{#1}{#2}{#3}%
  \trimtop=\stockheight  \advance\trimtop -\paperheight
  \trimedge=0pt}
\newcommand*{\setpagebm}[3]{%
  \settrimmedsize{#1}{#2}{#3}%
  \trimtop=\stockheight \advance\trimtop -\paperheight
  \trimedge=\stockwidth \advance\trimedge -\paperwidth
    \advance\trimedge -0.5\trimedge}
\newcommand*{\setpagecc}[3]{%
  \settrimmedsize{#1}{#2}{#3}%
  \trimtop=\stockheight \advance\trimtop -\paperheight
    \advance\trimtop -0.5\trimtop
  \trimedge=\stockwidth \advance\trimedge -\paperwidth
    \advance\trimedge -0.5\trimedge}
\let\setpagemm\setpagecc
  
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
%
% \subsection{Float placement parameters}
%
%
% All float parameters are given default values in the \LaTeX{}
% kernel. For this reason counters only need to be set with
% \cs{setcounter} and other parameters are set using \cs{renewcommand}.
%
% \paragraph{Limits for the placement of floating objects}
%
% The settings here make it easier to place floats than with the
% standard classes.
%
% \begin{macro}{\c@topnumber}
%    The \Lcount{topnumber} counter holds the maximum number of
%    floats that can appear on the top of a text page (classically 2)
%    \begin{macrocode}
\setcounter{topnumber}{3}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\topfraction}
%    This indicates the maximum part of a text page that can be
%    occupied by floats at the top (classically 0.7).
%    \begin{macrocode}
\renewcommand{\topfraction}{.85}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\c@bottomnumber}
%    The \Lcount{bottomnumber} counter holds the maximum number of
%    floats that can appear on the bottom of a text page (classically 1).
%    \begin{macrocode}
\setcounter{bottomnumber}{2}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\bottomfraction}
%    This indicates the maximum part of a text page that can be
%    occupied by floats at the bottom (classically 0.3).
%    \begin{macrocode}
\renewcommand{\bottomfraction}{.5}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\c@totalnumber}
%    This indicates the maximum number of floats that can appear on
%    any text page (classically 3).
%    \begin{macrocode}
\setcounter{totalnumber}{4}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\textfraction}
%    This indicates the minimum part of a text page that has to be
%    occupied by text (classically 0.2).
%    \begin{macrocode}
\renewcommand{\textfraction}{.1}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\floatpagefraction}
%    This indicates the minimum part of a page that has to be
%    occupied by floating objects before a `float page' is 
%    produced (classically 0.5).
%    \begin{macrocode}
\renewcommand{\floatpagefraction}{.7}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\c@dbltopnumber}
%    The \Lcount{dbltopnumber} counter holds the maximum number of
%    two column floats that can appear on the top of a two column text
%    page (classically 2).
%    \begin{macrocode}
\setcounter{dbltopnumber}{3}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\dbltopfraction}
%    This indicates the maximum part of a two column text page that
%    can be occupied by two column floats at the top (classically 0.7).
%    \begin{macrocode}
\renewcommand{\dbltopfraction}{.85}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\dblfloatpagefraction}
%    This indicates the minimum part of a page that has to be
%    occupied by two column wide floating objects before a `float
%    page' is produced (classically 0.5).
%    \begin{macrocode}
\renewcommand{\dblfloatpagefraction}{.7}
%    \end{macrocode}
% \end{macro}
%
%
% \section{Page Styles}
%
%    The page style \pstyle{foo} is defined by defining the command
%    \cs{ps@foo}.   This command should make only local definitions.
%    There should be no stray spaces in the definition, since they
%    could lead to mysterious extra spaces in the output.
%
% \begin{macro}{\@evenhead}
% \begin{macro}{\@oddhead}
% \begin{macro}{\@evenfoot}
% \begin{macro}{\@oddfoot}
%    The \cs{ps@...} command defines the macros \cs{@oddhead},
%    \cs{@oddfoot}, \cs{@evenhead}, and \cs{@evenfoot} to define the running
%    heads and feet---e.g., \cs{@oddhead} is the macro to produce the
%    contents of the heading box for odd-numbered pages.  It is called
%    inside an \cs{hbox} of width \cs{textwidth}.
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \subsection{Marking conventions}
%
%    To make headings determined by the sectioning commands, the page
%    style defines the commands \cs{chaptermark}, \cs{sectionmark},
%    \ldots,\\
%     where \cs{chaptermark}\marg{TEXT} is called by
%    \cs{chapter} to set a mark, and so on.
%
%    The \cs{...mark} commands and the \cs{...head} macros are defined
%    with the help of the following macros.  (All the \cs{...mark}
%    commands should be initialized to no-ops.)
%
%    \LaTeX{} extends \TeX's \cs{mark} facility by producing two kinds
%    of marks, a `left' and a `right' mark, using the following
%    commands:
%    \begin{flushleft}
%     \cs{markboth}\marg{LEFT}\marg{RIGHT}: Adds both marks.
%
%     \cs{markright}\marg{RIGHT}: Adds a `right' mark.
%
%     \cs{leftmark}: Used in the \cs{@oddhead}, \cs{@oddfoot}, \cs{@evenhead}
%                  or \cs{@evenfoot} macros, it gets the current `left'
%                  mark.  \cs{leftmark} works like \TeX's \cs{botmark}
%                  command.
%
%     \cs{rightmark}: Used in the \cs{@oddhead}, \cs{@oddfoot}, \cs{@evenhead}
%                   or  \cs{@evenfoot} macros, it gets the current
%                   `right' mark. \cs{rightmark} works like \TeX's
%                   \cs{firstmark} command.
%    \end{flushleft}
%
%    The marking commands work reasonably well for right marks
%    `numbered within' left marks--e.g., the left mark is changed by a
%    \cs{chapter} command and the right mark is changed by a \cs{section}
%    command.  However, it does produce somewhat anomalous results if
%    two \cs{markboth}'s occur on the same page.
%
%
%    Commands like \cs{tableofcontents} that should set the marks in some
%    page styles use a \cs{@mkboth} command, which is \cs{let} by the
%    pagestyle command (\cs{ps@...})  to \cs{markboth} for setting the
%    heading or to \cs{@gobbletwo} to do nothing.
%
%
%
% \subsection{Defining the page styles}
%
%    This class provides a set of commands for the user to define new
% pagestyles. Essentially defining a pagestyle consists of defining the
% macros \cs{@evenhead}, \cs{@oddhead}, \cs{@evenfoot}, and \cs{@oddfoot}.
% For this class, each header and footer is treated as three parts: a left,
% center, and right part. In this case, defining a pagestyle consists of
% specifying these 12 portions of the running headers and footers. The
% width of the headers/footers may also be specified, rules may be drawn
% below the headers and/or above the footers, and the complete header and/or
% footer may be offset with respect to the textblock when the width is not
% the same as the textwidth.
%
%    In the following \meta{style} is the name of a pagestyle being defined
% (e.g., \verb?ruled?).
% 
% \changes{v1.61803398d}{2010/02/09}{Added the following three macros}
% \begin{macro}{\mem@set@ps@xtra@info}
% \begin{macro}{\mem@ps@find@real}
% \begin{macro}{\mem@ps@safe@change}
% The class supports an aliasing feature, where a page style name can
% actually call the code from another. Quite handy. But There might be
% problems if a use try to modify an alias page style. We care for
% this by storing some information about each page style, and throwing
% an error if the user atempts to alter a page style marked as an
% alias.
% 
% \verb?\mem@set@ps@xtra@info? store two things: the name of the style
% we are an alias for (if we are not an alias it will be blank) and an
% indicator whether we are an alias (00 if we are and 01 if we are not).
%    \begin{macrocode}
\newcommand\mem@set@ps@xtra@info[3]{%
  \@namedef{ps@#1@aliasfor}{#2}%
  \@namedef{ps@#1@isalias}{#3}}

%    \end{macrocode}
% \verb?\mem@ps@find@real? starts at a given page style, if it is
% marked as an alias, it will recursively go down the chain of aliases
% and save the name of the first real page style in \verb?\@tempa?.
%    \begin{macrocode}
\newcommand\mem@ps@find@real[1]{%
  \if\@nameuse{ps@#1@isalias}\relax
  \mem@ps@find@real{\@nameuse{ps@#1@aliasfor}}
  \else\def\@tempa{#1}\fi}

%    \end{macrocode}
% \verb?\mem@ps@safe@change? takes a page style name, checks to see if
% it is defined, if it is, it checks to see if it is safe to change
% it.
% \changes{v3.7c}{2014/05/20}{Typo reported by Werner Grundlingh}
%    \begin{macrocode}
\newcommand\mem@ps@safe@change[1]{%
 \@ifundefined{ps@#1}{%
    \@memerror{Undefined pagestyle '#1', so I cannot change it}{}}{}
  \if\@nameuse{ps@#1@isalias}\relax \mem@ps@find@real{#1}
  \@memerror{The pagestyle '#1' is marked as an alias page style.^^J
    Modifying an alias page style may give unexpected results.^^J The
    alias chain resolves to the real page style '\@tempa', so try
    issuing^^J \string\copypagestyle{#1}{\@tempa}^^J
    before modifying '#1'}{} \fi }

%    \end{macrocode}
%
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\makeevenhead}
% The command 
% \cs{makeevenhead}\marg{style}\marg{left}\marg{center}\marg{right}
% specifies that the left, center and right portions of the even header for
% pagestyle \meta{style} are defined as the other three arguments, respectiveley.
% Internally it defines the commands \cs{styleeheadl}, \cs{styleeheadc} and
% \cs{styleeheadr} to be \meta{left}, \meta{center} and \meta{right} respectively.
% \changes{v1.61803398d}{2010/02/09}{Added safe change test}
%    \begin{macrocode}
\newcommand{\makeevenhead}[4]{%
  \mem@ps@safe@change{#1}
  \@namedef{#1eheadl}{#2}
  \@namedef{#1eheadc}{#3}
  \@namedef{#1eheadr}{#4}
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\makeoddhead}
% \begin{macro}{\makeevenfoot}
% \begin{macro}{\makeoddfoot}
%  These three macros are similar to \cs{makeevenhead} except that they are
% for the oddhead, evenfoot and oddfoot.
% \changes{v1.61803398d}{2010/02/09}{Added safe change test}
%    \begin{macrocode}
\newcommand{\makeoddhead}[4]{%
  \mem@ps@safe@change{#1}
  \@namedef{#1oheadl}{#2}
  \@namedef{#1oheadc}{#3}
  \@namedef{#1oheadr}{#4}
}
\newcommand{\makeevenfoot}[4]{%
  \mem@ps@safe@change{#1}
  \@namedef{#1efootl}{#2}
  \@namedef{#1efootc}{#3}
  \@namedef{#1efootr}{#4}
}
\newcommand{\makeoddfoot}[4]{%
  \mem@ps@safe@change{#1}
  \@namedef{#1ofootl}{#2}
  \@namedef{#1ofootc}{#3}
  \@namedef{#1ofootr}{#4}
}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\makerunningwidth}
% \begin{macro}{\makerunningheadwidth}
% \begin{macro}{\makerunningfootwidth}
% \begin{macro}{\m@mhfstyle}
% \begin{macro}{\m@mopthfwidth}
%  The macro \cs{makerunningwidth}\marg{style}\oarg{ftlength}\marg{length} 
% sets the
% width of the headers and footers of pagestyle \meta{style} to 
% be \meta{length}, but if \meta{ftlength} is present the footer
% width is set to \meta{ftlength}. The lengths are stored as the
% macros \cs{styleheadrunwidth} and \cs{stylefootrunwidth}. The two
% widths can be set individually using
% \cs{makerunningheadwidth}\marg{style}\marg{length} and
% \cs{makerunningfootwidth}\marg{style}\marg{length}. 
% \changes{v1.6180339c}{2008/12/26}{Enabled the width of headers and footers 
%                       to be different 
%                       (requested by Wilhelm M\"{u}ller).}
% \changes{v1.6180339c}{2009/01/13}{Added \cs{makerunningheadwidth}
% and \cs{makerunningfootwidth}}.
% \changes{v1.6180339d}{2009/02/04}{Fixed a mental bug, /daleif}
% \changes{v1.61803398d}{2010/02/09}{Added safe change test}
%    \begin{macrocode}
\newcommand*{\makerunningwidth}[1]{%
  \mem@ps@safe@change{#1}%
  \def\m@mhfstyle{#1}%
  \m@mopthfwidth}
\newcommand*{\m@mopthfwidth}[2][\@mpty]{%
%  \setlength\@tempdima{#2}
  \@namedef{\m@mhfstyle headrunwidth}{#2}%
%  \expandafter\edef\csname \m@mhfstyle headrunwidth\endcsname{\the\@tempdima}
  \ifx\@mpty #1
    \@namedef{\m@mhfstyle footrunwidth}{#2}%
%    \expandafter\edef\csname \m@mhfstyle footrunwidth\endcsname{\the\@tempdima}
  \else
    \@namedef{\m@mhfstyle footrunwidth}{#1}%
%    \setlength\@tempdima{#1}
%    \expandafter\edef\csname \m@mhfstyle footrunwidth\endcsname{\the\@tempdima}
  \fi}
\newcommand*{\makerunningheadwidth}[2]{%
%  \setlength\@tempdima{#2}%
%  \expandafter\edef\csname \m@mhfstyle headrunwidth\endcsname{\the\@tempdima}%
  \mem@ps@safe@change{#1}%
  \@namedef{#1headrunwidth}{#2}%
}
\newcommand*{\makerunningfootwidth}[2]{%
%  \setlength\@tempdima{#2}%
  \mem@ps@safe@change{#1}%
  \@namedef{#1footrunwidth}{#2}%
%  \expandafter\edef\csname \m@mhfstyle footrunwidth\endcsname{\the\@tempdima}%
}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\normalrulethickness}
% \begin{macro}{\footruleheight}
% \begin{macro}{\footruleskip}
% \begin{macro}{\makeheadrule}
% \begin{macro}{\makefootrule}
% \cs{normalrulethickness} is the thickness of a normal horizontal 
% or vertical rule. 
% \cs{footruleheight} is the height of a normal rule above a footer (actually zero).
% \cs{footruleskip} is a distance sufficient to ensure that a foot rule 
% will appear between the bottom of the textblock and above any actual footer.
%
% (There was a \ctt{} thread \textit{ngerman, fancyhdr and \cs{footrulewidth} --- bug?}
%  in December 2002 that bears on the definitions below).
% \changes{v1.4}{2003/02/27}{Make \cs{normalrulethickness} a length, 
%                            not a macro (patch 1.1)}
% \changes{v1.4}{2003/02/27}{Initialise \cs{footruleheight} to 0pt, not
%                            \cs{z@skip} (patch 1.1)}
%    \begin{macrocode}
\newlength{\normalrulethickness}
  \setlength{\normalrulethickness}{0.4pt}
\newcommand{\footruleheight}{0pt}
\newcommand{\footruleskip}{0.3\normalbaselineskip}
%    \end{macrocode}
% The macro \cs{makeheadrule}\marg{style}\marg{width}\marg{height}
% specifies the width and height of the header rule for \meta{style}. 
%
% Similarly
% \cs{makefootrule}\marg{style}\marg{width}\marg{height}\marg{skip}
% specifies the width, height and skip for the footrule.
% \changes{v1.61803398d}{2010/02/09}{Added safe change test}
% \changes{v3.7d}{2015/04/22}{Moved \cs{...(head|foot)ruleprefix} out and
% added them else where}
%    \begin{macrocode}
\newcommand{\makeheadrule}[3]{%
  \mem@ps@safe@change{#1}%
  \@namedef{#1headrule}{%
    \hrule\@width #2\@height #3 \vskip-#3}}
\newcommand{\makefootrule}[4]{%
  \mem@ps@safe@change{#1}%
  \@namedef{#1footrule}{%
    \vskip-#4\vskip-#3%
    \hrule\@width #2\@height #3 \vskip #4}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%  
% \changes{v3.6h}{2011/01/25}{Added this macro}
% \begin{macro}{\makeheadfootruleprefix}
% We insert a maro at the start of the head and foot rule. By default
% it does nothing, but it can be ised to specify a different color to
% the head or foot rules.
%    \begin{macrocode}
\newcommand\makeheadfootruleprefix[3]{%
  \@namedef{#1headruleprefix}{#2}%
  \@namedef{#1footruleprefix}{#3}%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\makeheadposition}
% \cs{makeheadposition}\marg{style}\marg{eheadpos}\marg{oheadpos}\marg{efootpos}\marg{ofootpos}
% specifies the horizontal positioning of the even and odd headers and footers,
% respectively, 
% for the pagestyle \meta{style}. Each of the \meta{...pos} arguments may be
% either \verb?flushleft?, \verb?center? or \verb?flushright?, with the obvious meanings.
% An empty argument (or an unrecognised one) is equivalent to \verb?center?.
% \changes{v1.61803398d}{2010/02/09}{Added safe change test}
%    \begin{macrocode}
\newcommand{\makeheadposition}[5]{%
  \mem@ps@safe@change{#1}%
%    \end{macrocode}
% Do the even head position first.
%    \begin{macrocode}
  \nametest{flushleft}{#2}
  \ifsamename
    \@namedef{#1evenheadpl}{\relax} \@namedef{#1evenheadpr}{\hss}
  \else
    \nametest{flushright}{#2}
    \ifsamename
      \@namedef{#1evenheadpl}{\hss} \@namedef{#1evenheadpr}{\relax}
    \else
      \@namedef{#1evenheadpl}{\hss} \@namedef{#1evenheadpr}{\hss}
    \fi
  \fi
%    \end{macrocode}
% And similarly for the odd head and even \& odd footers.
%    \begin{macrocode}   
  \nametest{flushleft}{#3}
  \ifsamename
    \@namedef{#1oddheadpl}{\relax} \@namedef{#1oddheadpr}{\hss}
  \else
    \nametest{flushright}{#3}
    \ifsamename
      \@namedef{#1oddheadpl}{\hss} \@namedef{#1oddheadpr}{\relax}
    \else
      \@namedef{#1oddheadpl}{\hss} \@namedef{#1oddheadpr}{\hss}
    \fi
  \fi
  \nametest{flushleft}{#4}
  \ifsamename
    \@namedef{#1evenfootpl}{\relax} \@namedef{#1evenfootpr}{\hss}
  \else
    \nametest{flushright}{#4}
    \ifsamename
      \@namedef{#1evenfootpl}{\hss} \@namedef{#1evenfootpr}{\relax}
    \else
      \@namedef{#1evenfootpl}{\hss} \@namedef{#1evenfootpr}{\hss}
    \fi
  \fi
  \nametest{flushleft}{#5}
  \ifsamename
    \@namedef{#1oddfootpl}{\relax} \@namedef{#1oddfootpr}{\hss}
  \else
    \nametest{flushright}{#5}
    \ifsamename
      \@namedef{#1oddfootpl}{\hss} \@namedef{#1oddfootpr}{\relax}
    \else
      \@namedef{#1oddfootpl}{\hss} \@namedef{#1oddfootpr}{\hss}
    \fi
  \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\makepsmarks}
% \begin{macro}{\makepshook}
% The macro \cs{makepsmarks}\marg{style}\marg{code} specifies that
% \meta{code} is the definition of the hook for pagestyle \meta{style}.
% \cs{makepshook} was a deprecated version of \cs{makepsmarks} and is
% now deleted.
% \changes{v1.0}{2001/11/15}{Added \cs{makepsmarks} and deprecated 
%                                  \cs{makepshook}}
% \changes{v1.4}{2003/12/14}{Deleted \cs{makepshook}}
% \changes{v1.61803398d}{2010/02/09}{Added safe change test}
%    \begin{macrocode}
\newcommand{\makepsmarks}[2]{\mem@ps@safe@change{#1}\@namedef{#1pshook}{#2}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\m@mhe@dreset}
% To cater for potential baselineskip changes, such as \verb?\linespread{2}?,
% we have to ensure they don't percolate into the header/footer.
% (See CTT thread \textit{memoir + linespread}, 2004/02/11)
% \changes{v1.61}{2004/03/14}{Added \cs{m@mhe@dreset}}
%    \begin{macrocode}
\newcommand*{\m@mhe@dreset}{\def\baselinestretch{1}\normalsize}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\makeheadfootvposition}
%   The headers and footers are typeset inside \cs{parbox}'es, using
%   \cs{makeheadfootvposition}\marg{style}\marg{headvpos}\marg{footvpost}
%   users can specify whether the alignment should be b,t or~c.The
%   default is~b.
%   \changes{v1.6180339c}{2009/01/13}{Added support for 
%   controlling the alignment of the headers and footers}
% \changes{v1.61803398d}{2010/02/09}{Added safe change test}
%    \begin{macrocode}
\newcommand*\makeheadfootvposition[3]{%
  \mem@ps@safe@change{#1}%
  \@namedef{#1headvplacement}{#2}\@namedef{#1footvplacement}{#3}}

%    \end{macrocode}
% \end{macro}
% \begin{macro}{\mem@maxheadheight}
% \begin{macro}{\mem@maxfootheight}
% \begin{macro}{\mem@sayonce@head}
% \begin{macro}{\mem@sayonce@foot}
% \begin{macro}{\mem@hf@measure@vbox}
% \begin{macro}{\mem@toolarge@header@message}
% \begin{macro}{\mem@toolarge@footer@message}
% \changes{v3.6h}{2010/10/21}{Added the above seven macros to be able
% to measure the headers and warn users if their design takes them outside.}  
% \verb?\mem@maxheadheight? and \verb?\mem@maxfootheight? globally
% stores the max measured head and foot heights. Actually the footer
% ought to be measuring the total height and depth. We may add this
% later. The two XsayonceX macros are toggles used such that we can
% add a warning at only the first bad head/foot. We repeat the message
% at the end of the document.
%    \begin{macrocode}
\newlength\mem@maxheadheight
\newlength\mem@maxfootheight
\newcommand\mem@sayonce@head{00}
\newcommand\mem@sayonce@foot{00}
%    \end{macrocode}
% This is the work horse of this construction. First argument is the
% height to compare against, second should be \texttt{head} or
% \texttt{foot}, third is the warning message, and the fourth is the
% material to be measured. The idea to taken from \Lpack{fancyhdr}.
%    \begin{macrocode}
\newcommand\mem@hf@measure@vbox[4]{%
  \setbox0\vbox{#4}%
  \ifdim\ht0>#1\relax%
    \setlength\@tempdima{\@nameuse{mem@max#2height}}%
    \ifdim\ht0>\@tempdima\relax%
      \expandafter\global\@nameuse{mem@max#2height}=\ht0%
      \expandafter\if\@nameuse{mem@sayonce@#2}\relax%
        \@memwarn{#3}%
          \global\@namedef{mem@sayonece@#2}{01}%
      \fi%
    \fi%
  \fi%
  \box0%
}
%    \end{macrocode}
% Warning messages
%    \begin{macrocode}
\newcommand\mem@toolarge@header@message{%
  The material used in the headers is too large^^J%
  (\the\mem@maxheadheight) for the given head height
  (\the\headheight), it is recommended to^^J%
  either increase the head height or redesign the header^^J%
  (in both cases you will find help in the memoir manual).%
}
\newcommand\mem@toolarge@footer@message{%
  The material used in the footer is too large^^J%
  (\the\mem@maxfootheight) for the given foot skip
  (\the\footskip), it is recommended to^^J%
  either increase the foot skip or redesign the footer^^J%
  (in both cases you will find help in the memoir manual).%
}
%    \end{macrocode}
% To make things easier to read we make two short cut macros
%    \begin{macrocode}
\newcommand\mem@hvboxm[1]{%
  \mem@hf@measure@vbox\headheight{head}\mem@toolarge@header@message{#1}}
\newcommand\mem@fvboxm[1]{%
  \mem@hf@measure@vbox\footskip{foot}\mem@toolarge@footer@message{#1}}
%    \end{macrocode}
% Make sure to repeat the message at the end of the document. This
% will show the max value up until the point where the end of document
% stuff is executed. 
%    \begin{macrocode}
\AtEndDocument{
  \ifdim\mem@maxheadheight>\headheight
    \@memwarn{\mem@toolarge@header@message}
  \fi
  \ifdim\mem@maxfootheight>\footskip
    \@memwarn{\mem@toolarge@footer@message}
  \fi
}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\mem@ps@entry@wrap}
%   \changes{v3.6h}{2010/10/06}{Added this to help bidi control the
%   typesetting direction of the header and footer}
%   This macro is wrapped around eash entry in the headers and
%   footers. By default it does nothing, but can be redefined by
%   packages such as \Lpack{bidi} to control the typesetting direction
%   in the header. Bidi for example has two modes such that headers
%   can be RTL locally while the header stay at LTR. If this macro is
%   changed, it will be a good idea to coordinate it with the bidi
%   maintainer. 
%    \begin{macrocode}
\newcommand\mem@ps@entry@wrap{}
%    \end{macrocode}
%   
% \end{macro}
% \begin{macro}{\mem@ps@HLH}
%   \changes{v3.6d}{2010/10/06/24}{Factored \cs{makepagestyle}}
%   The entries in the header used in \cs{makepagestyle} (below) are
%   more or less the same. It depends on \emph{head/foot},
%   \emph{odd/even} and a shorter \emph{o/e}. So to make the code more
%   maintainable we factor this out into a generator macro. The
%   explanation for the code being used is kept below (see
%   \cs{makepagestyle}). 
% \changes{v3.6k}{2012/05/31}{Forgot to separate head/foot position into the
% factorization, propblem reported by Wybo Dekker on
% http://tex.stackexchange.com/q/56141/3929}
%    \begin{macrocode}
\newcommand\mem@ps@HLH[4]{%
  % #1 ps name
  % #2 type: head, foot
  % #3 odd/even
  % #4 odd/even short (o,e)
  \@namedef{#1@#3#2}{%
    \@nameuse{#1#3#2pl}\hb@xt@\@nameuse{#1#2runwidth}{\m@mhe@dreset%
%    \end{macrocode}
% In footers the line goes before the text, so we test and add the
% footline if \texttt{\#2} equals \texttt{foot}.
% \changes{v3.6h}{2010/10/06}{added the entry wrapper}
% \changes{v3.6h}{201010/10/21}{Added the header/footer measuring feature.}
% For the header/footer measuring stuff we look at \#2 and make the
% suiting macro from that value.
% \changes{v3.6h}{2010/10/22}{Added \cs{memRTLmainraggedX} macros such
% that \Lpack{bidi} can also change the order of the header if RTL is
% the main direction of the document.}
%    \begin{macrocode}
      \nametest{#2}{head}\ifsamename\let\mem@hfboxer\mem@hvboxm\else\let\mem@hfboxer\mem@fvboxm\fi%
%    \end{macrocode}
% \changes{v3.7d}{2015/04/22}{Moved \cs{...footruleprefix} outside
% \cs{...footrule}. Otherwise copy does not work correctly. Reported
% at http://tex.stackexchange.com/q/231454/3929}
%    \begin{macrocode}
      \mem@hfboxer{\nametest{#2}{foot}\ifsamename%
          \begingroup% to prevent colors from bleeding into the footer
          \@nameuse{#1#2ruleprefix}%
          \@nameuse{#1#2rule}%
          \endgroup%
        \fi%
        \hbox{%
          \rlap{%
            \parbox[\@nameuse{#1#2vplacement}]{\@nameuse{#1#2runwidth}}{%
              \memRTLmainraggedright\@nameuse{#1ps#2strut}%
              \mem@ps@entry@wrap{\@nameuse{#1#4#2l}}%
              \@nameuse{#1ps#2strut}}}\hfill
          \parbox[\@nameuse{#1#2vplacement}]{\@nameuse{#1#2runwidth}}{%
            \centering\@nameuse{#1ps#2strut}%
            \mem@ps@entry@wrap{\@nameuse{#1#4#2c}}%
            \@nameuse{#1ps#2strut}}\hfill
          \llap{%
            \parbox[\@nameuse{#1#2vplacement}]{\@nameuse{#1#2runwidth}}{%
              \memRTLmainraggedleft\@nameuse{#1ps#2strut}%
              \mem@ps@entry@wrap{\@nameuse{#1#4#2r}}%
              \@nameuse{#1ps#2strut}}}%
        }%
%    \end{macrocode}
% In the header the line goes under the text, so we test and add the
% headline if \texttt{\#2} equals \texttt{head}.
% \changes{v3.6k}{2012/05/31}{Forgot to separate head/foot position into the
% factorization}
% \changes{v3.7d}{2015/04/22}{Moved \cs{...headruleprefix} outside
% \cs{...headrule}. Otherwise copy does not work correctly.}
%    \begin{macrocode}
        \nametest{#2}{head}\ifsamename%
          \@nameuse{#1#2ruleprefix}%
          \@nameuse{#1#2rule}%
        \fi%
      }}\@nameuse{#1#3#2pr}}%
%    \end{macrocode}
% And end by letting the LaTeX head/foot use our version
%    \begin{macrocode}
  \@namedef{@#3#2}{\@nameuse{#1@#3#2}}%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\makepagestyle}
%  At last we can put everything together for defining a new pagestyle,
% via the macro \cs{makepagestyle}\marg{style} which initially sets up 
% a new pagestyle \meta{style} corresponding the the \LaTeX{} \verb?empty?
% pagestyle. The prior macros can then be used to make modifications
% to the style.
% \changes{v1.0}{2001/11/15}{Now 2 stage process for defining \cs{@evenhead}
%                            and friends}
% \changes{v1.61}{2004/03/14}{Added \cs{m@mhe@dreset} at several points in
%                             \cs{makepagestyle} (from patch 2.1)}
% \changes{v1.61803}{2008/01/30}{Removed extraneous spaces from pagestyle code 
%                    (mempatch v4.6)}
% \changes{v1.61803398d}{2010/02/09}{Added storing extra information
% about page styles}
% We also make sure to specify that this is a `real' page style, and
% thus sets the empty alias name and the alias test to 01.
%    \begin{macrocode}
\newcommand{\makepagestyle}[1]{%
  \mem@set@ps@xtra@info{#1}{}{01}%
%    \end{macrocode}
% First define the macro \cs{ps@style}, which in turn defines the macros
% \cs{@evenhead}, \cs{@oddhead}, \cs{@evenfoot} and \cs{@oddfoot}.
%   \changes{v3.6d}{20101/06/24}{Factored \cs{makepagestyle}, such
%   that \cs{#1@evenhead} and friends are made using \emph{one} single
%   macro. We keep the original code just in case.}
%    \begin{macrocode}
  \@namedef{ps@#1}{%
      \mem@ps@HLH{#1}{head}{even}{e}%
      \mem@ps@HLH{#1}{head}{odd}{o}%
      \mem@ps@HLH{#1}{foot}{even}{e}%
      \mem@ps@HLH{#1}{foot}{odd}{o}%
 %    \@namedef{#1@evenhead}{%
%    \end{macrocode}
% The code for the definition of \cs{@evenhead} and friends is based on code
% from Piet van Oostrum's \Lpack{fancyhdr} package~\cite{FANCYHDR}. The three
% parts of the header are put into parboxes, with fills between them, and
% the whole lot is put into a box the width of the header. Fillers are put
% before and after the main box which control the header position.
%
% First the left filler which is either \cs{relax} or \cs{hss}, and then
% start the main box.
% \changes{v1.6180339c}{2008/12/26}{Replaced \cs{...runwidth} by \cs{...headrunwidth}
%                       or \cs{...footrunwidth}, as appropriate for headers and footers.}
% \changes{v1.6180339c}{2009/01/13}{Replaced \cs{parbox}\texttt[b]
% with \cs{parbox}\texttt{[\cs{nameuse{#1headvplacement}}]} etc.}
%    \begin{macrocode}
 %      \@nameuse{#1evenhpl}\hb@xt@\@nameuse{#1headrunwidth}{\m@mhe@dreset%
 %        \vbox{\hbox{%
%    \end{macrocode}
% The left part of the header.
%    \begin{macrocode}
 %        \rlap{\parbox[\@nameuse{#1headvplacement}]{\@nameuse{#1headrunwidth}}{%
 %          \raggedright\@nameuse{#1eheadl}\strut}}\hfill
%    \end{macrocode}
% The center part of the header.
%    \begin{macrocode}
 %               \parbox[\@nameuse{#1headvplacement}]{\@nameuse{#1headrunwidth}}{%
 %           \centering\@nameuse{#1eheadc}\strut}\hfill
%    \end{macrocode}
% The right part of the header.
%    \begin{macrocode}
 %        \llap{\parbox[\@nameuse{#1headvplacement}]{\@nameuse{#1headrunwidth}}{%
 %         \raggedleft\@nameuse{#1eheadr}\strut}}}%
%    \end{macrocode}
% Finally, the header rule and finish with the right filler, which
% is either \cs{relax} or \cs{hss}.
%    \begin{macrocode}
 %       \@nameuse{#1headrule}}}\@nameuse{#1evenhpr}}%
%    \end{macrocode}
% The code for the \cs{@oddhead}, \cs{@evenfoot} and \cs{@oddfoot} follows
% a similar pattern. Here is \cs{@oddhead}.
%    \begin{macrocode}
 %   \@namedef{#1@oddhead}{%
 %     \@nameuse{#1oddhpl}\hb@xt@\@nameuse{#1headrunwidth}{\m@mhe@dreset%
 %       \vbox{\hbox{%
 %       \rlap{\parbox[\@nameuse{#1headvplacement}]{\@nameuse{#1headrunwidth}}{%
 %         \raggedright\@nameuse{#1oheadl}\strut}}\hfill
 %             \parbox[\@nameuse{#1headvplacement}]{\@nameuse{#1headrunwidth}}{%
 %         \centering\@nameuse{#1oheadc}\strut}\hfill
 %       \llap{\parbox[\@nameuse{#1headvplacement}]{\@nameuse{#1headrunwidth}}{%
 %         \raggedleft\@nameuse{#1oheadr}\strut}}}%
 %       \@nameuse{#1headrule}}}\@nameuse{#1oddhpr}}%
%    \end{macrocode}
% And \cs{@evenfoot}. For the footers the rules come \emph{before} any foot
% entries.
%    \begin{macrocode}
 %   \@namedef{#1@evenfoot}{%
 %     \@nameuse{#1evenfpl}\hb@xt@\@nameuse{#1footrunwidth}{\m@mhe@dreset%
 %       \vbox{\@nameuse{#1footrule}\hbox{%
 %       \rlap{\parbox[\@nameuse{#1footvplacement}]{\@nameuse{#1footrunwidth}}{%
 %         \raggedright\@nameuse{#1efootl}\strut}}\hfill
 %             \parbox[\@nameuse{#1footvplacement}]{\@nameuse{#1footrunwidth}}{%
 %         \centering\@nameuse{#1efootc}\strut}\hfill
 %       \llap{\parbox[\@nameuse{#1footvplacement}]{\@nameuse{#1footrunwidth}}{%
 %         \raggedleft\@nameuse{#1efootr}\strut}}}%
 %       }}\@nameuse{#1evenfpr}}%
%    \end{macrocode}
% Lastly the \cs{@oddfoot}.
%    \begin{macrocode}
 %   \@namedef{#1@oddfoot}{%
 %     \@nameuse{#1oddfpl}\hb@xt@\@nameuse{#1footrunwidth}{\m@mhe@dreset%
 %       \vbox{\@nameuse{#1footrule}\hbox{%
 %       \rlap{\parbox[\@nameuse{#1footvplacement}]{\@nameuse{#1footrunwidth}}{%
 %         \raggedright\@nameuse{#1ofootl}\strut}}\hfill
 %             \parbox[\@nameuse{#1footvplacement}]{\@nameuse{#1footrunwidth}}{%
 %         \centering\@nameuse{#1ofootc}\strut}\hfill
 %       \llap{\parbox[\@nameuse{#1footvplacement}]{\@nameuse{#1footrunwidth}}{%
 %         \raggedleft\@nameuse{#1ofootr}\strut}}}%
 %       }}\@nameuse{#1oddfpr}}%
%    \end{macrocode}
% Now we define \cs{@evenhead} etc., in terms of \verb?#1@evenhead?.
%    \begin{macrocode}
 %    \def\@evenhead{\@nameuse{#1@evenhead}}%
 %    \def\@oddhead{\@nameuse{#1@oddhead}}%
 %    \def\@evenfoot{\@nameuse{#1@evenfoot}}%
 %    \def\@oddfoot{\@nameuse{#1@oddfoot}}%
%    \end{macrocode}
% To finish off the definition of \cs{ps@style}, add in a hook which can be
% defined so that it adds additional code, if required.
%    \begin{macrocode}
    \@nameuse{#1pshook}}%
%    \end{macrocode}
% \changes{v3.6d}{2010/06/24}{Added strut initialization} Next we
% initialize the struts being used. Remember the for the
% \pstyle{empty} style, the strut should be empty.
%    \begin{macrocode}
    \nametest{#1}{empty}%
    \ifsamename%
      \@namedef{#1psheadstrut}{}\@namedef{#1psfootstrut}{}%
    \else%
      \@namedef{#1psheadstrut}{\strut}\@namedef{#1psfootstrut}{\strut}%
    \fi%
%    \end{macrocode}
%
% The final part of setting up the new pagestyle
% is defining all the macros called by \cs{ps@style}, and giving them
% default values. Make the headers and footers empty.
%    \begin{macrocode}
  \makeevenhead{#1}{}{}{}%
  \makeoddhead{#1}{}{}{}%
  \makeevenfoot{#1}{}{}{}%
  \makeoddfoot{#1}{}{}{}%
%    \end{macrocode}
% Make the headers/footers the same width as the \cs{textwidth},
% center them, and ensure that the rules have zero height so that they
% will be invisible. Also initialize the head/foot prefixes.
% \changes{v3.6h}{2011/01/25}{Added the \cs{makeheadfootruleprefix}}
%    \begin{macrocode}
  \makerunningwidth{#1}{\textwidth}%
  \makeheadposition{#1}{}{}{}{}%
  \makeheadrule{#1}{\textwidth}{0pt}%
  \makefootrule{#1}{\textwidth}{\footruleheight}{\footruleskip}%
  \makeheadfootruleprefix{#1}{}{}
%    \end{macrocode}
% Set the initial vertical header and footer positions.
% \changes{v1.6180339c}{2009/01/13}{Added head/foot position initialisation}
%    \begin{macrocode}
  \makeheadfootvposition{#1}{b}{b}%
%    \end{macrocode}
% Finally, there is no addtional code needed, so make the hook empty, and
% we are done.
%    \begin{macrocode}
  \makepsmarks{#1}{}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\aliaspagestyle}
% The command \cs{aliaspagestyle}\marg{alias}\marg{original}
% defines the \meta{alias} pagestyle to be an alias for the
% \meta{original} pagestyle.
% \changes{v1.61803398d}{2010/02/09}{Added page style storing info}
% We remember to set the stored alias name, and sets the alias test to
% true (00).
%    \begin{macrocode}
\newcommand{\aliaspagestyle}[2]{%
  \mem@set@ps@xtra@info{#1}{#2}{00}%
  \@namedef{ps@#1}{\@nameuse{ps@#2}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\copypagestyle}
% The command \cs{copypagestyle}\marg{new}\marg{original}
% defines the \meta{new} pagestyle to be a copy of the
% \meta{original} pagestyle.
%
% It first makes the \meta{new} (empty) pagestyle then defines the internals
% in terms of the \meta{original} internals.
% \changes{v1.2}{2002/08/10}{Added \cs{copypagestyle}}
% \changes{v1.61803}{2008/01/30}{Added missing elements to \cs{copypagestyle}
%          (per Erik Quaeghebeur mempatch v4.9)}
%    \begin{macrocode}
\newcommand{\copypagestyle}[2]{%
  \makepagestyle{#1}%
%    \end{macrocode}
% Do the headers and footers.
%    \begin{macrocode}
  \makeevenhead{#1}{\@nameuse{#2eheadl}}%
               {\@nameuse{#2eheadc}}{\@nameuse{#2eheadr}}%
  \makeoddhead{#1}{\@nameuse{#2oheadl}}%
               {\@nameuse{#2oheadc}}{\@nameuse{#2oheadr}}%
  \makeevenfoot{#1}{\@nameuse{#2efootl}}%
               {\@nameuse{#2efootc}}{\@nameuse{#2efootr}}%
  \makeoddfoot{#1}{\@nameuse{#2ofootl}}%
              {\@nameuse{#2ofootc}}{\@nameuse{#2ofootr}}%
%    \end{macrocode}
% Set the width.
%    \begin{macrocode}
  \makerunningwidth{#1}[\@nameuse{#2footrunwidth}]{\@nameuse{#2headrunwidth}}%
%    \end{macrocode}
% Specify the \cs{headposition}.
% \changes{v3.6k}{2012/05/31}{some macro renaming}
%    \begin{macrocode}
  \@namedef{#1evenheadpl}{\@nameuse{#2evenheadpl}}%
  \@namedef{#1oddheadpl}{\@nameuse{#2oddheadpl}}%
  \@namedef{#1evenheadpr}{\@nameuse{#2evenheadpr}}%
  \@namedef{#1oddheadpr}{\@nameuse{#2oddheadpr}}%
%    \end{macrocode}
% Also vertically
% \changes{v1.6180339c}{2008/01/13}{Also copy the vertical positions}
% \changes{v1.6180339e}{2008/02/06}{Bug fix, reported by Per
% Starb\"ack on ctt}
%    \begin{macrocode}
  \makeheadfootvposition{#1}{\@nameuse{#2headvplacement}}{\@nameuse{#2footvplacement}}%
%    \end{macrocode}
% Specify the feet
% \changes{v3.6k}{2012/05/31}{some macro renaming}
%    \begin{macrocode}
  \@namedef{#1evenfootpl}{\@nameuse{#2evenfootpl}}%
  \@namedef{#1oddfootpl}{\@nameuse{#2oddfootpl}}%
  \@namedef{#1evenfootpr}{\@nameuse{#2evenfootpr}}%
  \@namedef{#1oddfootpr}{\@nameuse{#2oddfootpr}}%
%    \end{macrocode}
% Specify the head and foot rules and the prefixes.
% \changes{v3.6h}{2011/01/25}{Added the \cs{makeheadfootruleprefix}}
%    \begin{macrocode}
  \@namedef{#1headrule}{\@nameuse{#2headrule}}%
  \@namedef{#1footrule}{\@nameuse{#2footrule}}%
  \@namedef{#1headruleprefix}{\@nameuse{#2headruleprefix}}%
  \@namedef{#1footruleprefix}{\@nameuse{#2footruleprefix}}%
%    \end{macrocode}
% \changes{v3.6d}{2010/06/24}{Added strut copying to \cs{copypagestyle}}
% And remember the struts
%    \begin{macrocode}
  \@namedef{#1psheadstrut}{\@nameuse{#2psheadstrut}}
  \@namedef{#1psfootstrut}{\@nameuse{#2psfootstrut}}
%    \end{macrocode}
% \end{macro}
% And pick up the hook. We end the macro here.
%    \begin{macrocode}
  \makepsmarks{#1}{\@nameuse{#2pshook}}}

%    \end{macrocode}
%
%
% \begin{macro}{\ifonlyfloats}
% \cs{ifonlyfloats}\marg{yes}\marg{no} processes \meta{yes} if the macro is
% called on a page consisting only of floats, otherwise \meta{no} is 
% processed. \cs{if@fcolmade} is specified in \file{ltoutput.dtx}.
% \changes{v1.0}{2001/11/14}{Added \cs{ifonlyfloats}}
%    \begin{macrocode}
\newcommand{\ifonlyfloats}[2]{\if@fcolmade #1\else #2\fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\mergepagefloatstyle}
% \cs{mergepagefloatstyle}\marg{style}\marg{textstyle}\marg{floatstyle}
% makes a new page style \meta{style} that is \meta{textstyle} on normal
% pages but uses \meta{floatstyle} on float-only pages. Both \meta{textstyle}
% and \meta{floatstyle} must have been previously defined.
% \changes{v1.0}{2001/11/15}{Added \cs{mergepagefloatstyle}}
%    \begin{macrocode}
\newcommand{\mergepagefloatstyle}[3]{%
%    \end{macrocode}
% Make sure that the two styles have been called, otherwise we get some
% undefined errors.
%    \begin{macrocode}
  \@nameuse{ps@#3}\@nameuse{ps@#2}%
%    \end{macrocode}
% Specify the pagestyle's headers and footers.
%    \begin{macrocode}
  \@namedef{ps@#1}{%
  \def\@evenhead{\ifonlyfloats{\@nameuse{#3@evenhead}}%
                {\@nameuse{#2@evenhead}}}%
  \def\@oddhead{\ifonlyfloats{\@nameuse{#3@oddhead}}%
               {\@nameuse{#2@oddhead}}}%
  \def\@evenfoot{\ifonlyfloats{\@nameuse{#3@evenfoot}}%
                {\@nameuse{#2@evenfoot}}}%
  \def\@oddfoot{\ifonlyfloats{\@nameuse{#3@oddfoot}}%
               {\@nameuse{#2@oddfoot}}}%
%    \end{macrocode}
% Set the hook to the \meta{textstyle} on the assumption that that is
% more complex that required for a float page.
%    \begin{macrocode}
  \@namedef{#1pshook}{\@nameuse{#2pshook}}%
%    \end{macrocode}
% That's it.
%    \begin{macrocode}
}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\makeheadfootstrut}
%   \changes{v3.6d}{2010/06/24}{Added \cs{makeheadfootstrut}}
%   In each `field' of the header a strut is added to keep alignment
%   right. This macro can be used to change a particular strut
%   configuration. Each combination is initialy set by
%   \cs{makepagestyle} to be equal to \cs{strut}, except the
%   \pstyle{empty} style, where the strut is empty by default.
%    \begin{macrocode}
\newcommand*\makeheadfootstrut[3]{%
  \@namedef{#1psheadstrut}{#2}\@namedef{#1psfootstrut}{#3}}
%    \end{macrocode}
% \end{macro}
%
%    The pagestyles \pstyle{empty} and \pstyle{plain} are defined 
%    in \file{latex.dtx}. However, I will redefine them here, just in
% case someone takes a fancy to modifying them.
%
% \begin{macro}{\ps@empty}
% The \pstyle{empty} pagestyle is simple, it's just what we get when
% we call \cs{makepagestyle}.
%    \begin{macrocode}
\makepagestyle{empty}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ps@plain}
% The \pstyle{plain} pagestyle is also simple, it just puts the
% page number at the bottom middle of the page.
% We call \verb?\makepagestyle{plain}? and then adjust as required.
%    \begin{macrocode}
\makepagestyle{plain}
  \makeevenfoot{plain}{}{\thepage}{}
  \makeoddfoot{plain}{}{\thepage}{}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ps@simple}
% The \pstyle{simple} page style simply puts the page number in the header
% at the outer margin.
% \changes{v1.61803398}{2009/07/26}{PW: Added the `simple' pagestyle}
%    \begin{macrocode}
\makepagestyle{simple}
  \makeevenhead{simple}{\thepage}{}{}
  \makeoddhead{simple}{}{}{\thepage}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\nouppercaseheads}
% \begin{macro}{\uppercaseheads}
% \begin{macro}{\memUChead}
% Spurred by Lars Madsen's \Lpack{memexsupp} v0.5 package here is a 
% way of switching uppercasing in the headings pagestyle. 
% \changes{v1.61803}{2008/01/30}{Added \cs{(no)uppercaseheads} and
%          \cs{memUChead} (mempatch v4.9)}
% \changes{v3.6k}{2011/05/20}{Making \cs{memUChead} equal to
% \cs{relax} can cause problems when users want to \cs{provide} it in
% other applications. It is now redefined into the empty string.}
% \changes{v3.6k}{2012/09/13}{Default upper case now \cs{MakeTextUppercase}}
% \changes{v3.8.4}{2025/08/08}{Default set to \cs{MakeUppercase} as it
% can the same as \cs{MakeTextUppercase} in modern kernels}
%    \begin{macrocode}
\newcommand*{\nouppercaseheads}{\def\memUChead{}}
\newcommand*{\uppercaseheads}{\def\memUChead{\MakeUppercase}}
\uppercaseheads

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% The macros \cs{createplainmark}, \cs{createmark} and \cs{addtopsmarks}
% are modified versions of code supplied by Lars Madsen.
% \changes{v1.61803}{2008/01/30}{Added, and used, \cs{createplainmark},
%                    \cs{createmark} and \cs{addtopsmarks}} 
% \begin{macro}{\createplainmark}
% \cs{createplainmark}\marg{type}\marg{marks}\marg{text} creates a
% \cs{typemark} (\meta{type} is \texttt{toc}, \texttt{bib}, etc)
% with \meta{marks} (left, both, right) whose contents are \meta{text}.
% For example \verb?\createplainmark{toc}{both}{\contentsname}?. The
% difference between plain and regular marks, is that plain marks use
% a fixed text, whereas regular marks recieve dynamic text and thus
% is given an argument.
% \changes{v3.8.4}{2025/08/06}{Redone via \cs{str_case:nnF}}
%    \begin{macrocode}
\ExplSyntaxOn
\NewDocumentCommand\createplainmark{ mmm }
{
  \str_case:nnF {#2}
  {
    {left} { \@namedef{#1mark}{\markboth{\memUChead{#3}}{}}               }
    {right}{ \@namedef{#1mark}{\markright{\memUChead{#3}}}                }
    {both} { \@namedef{#1mark}{\markboth{\memUChead{#3}}{\memUChead{#3}}} }
  }
  {
    \@memerror{
      Unknown~ mark~ setting~ type~ `#2'~ for~ #1mark}{
      I~ expected~ `left',~ `both'~ or~ `right'. \MessageBreak
      I~ will~ assume~ you~ meant~ `both'} 
  } 
}
\ExplSyntaxOff
 % \newcommand*{\createplainmark}[3]{%
 %   \nametest{#2}{left}%
 %   \ifsamename
 %     \@namedef{#1mark}{\markboth{\memUChead{#3}}{}}%
 %   \else
 %     \nametest{#2}{right}%
 %     \ifsamename
 %       \@namedef{#1mark}{\markright{\memUChead{#3}}}%
 %     \else
 %       \nametest{#2}{both}%
 %       \ifsamename\else
 %         \@memerror{%
 %           Unknown mark setting type `#2' for #1mark}{%
 %           I expected `left', `both' or `right'. \MessageBreak
 %           I will assume you meant `both'}%	
 %       \fi
 %       \@namedef{#1mark}{\markboth{\memUChead{#3}}{\memUChead{#3}}}%
 %     \fi
 %   \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\createmark}
% \cs{createmark}\marg{division}\marg{marks}\marg{show}\marg{prefix}\marg{postfix}
% creates a \cs{divisionmark} with \meta{marks} (= \texttt{left}, \texttt{both}
% or \texttt{right}) controlling which marks are set, 
% \meta{show} (= \texttt{shownumber}, \texttt{nonumber} or \texttt{notitle}) controls the
% display of the divison number in \cs{mainmatter}, \meta{prefix} is text
% before the number and \meta{postfix} is text after the number.
%    \begin{macrocode}
\newcommand\createmark[5]{%
%    \end{macrocode}
% Handle \texttt{(show/no)number/notitle}.
% \changes{v3.7i}{2019/11/07}{Added notitle show option and
% reimplemented its checking a bit}
%    \begin{macrocode}
  % \def\@tempa{00}
  % \nametest{#3}{nonumber}%
  % \ifsamename
  %   \def\@tempa{01}%
  % \else
  %   \nametest{#3}{shownumber}
  %   \ifsamename\else
  %     \@memerror{Unknown numbering value `#3' for #1mark}%
  %     {I expected `shownumber' or `nonumber'.\MessageBreak
  %      I will assume you meant `shownumber'}%
  %   \fi
  % \fi
  % \expandafter\if\@tempa%          compares the two \@tempa digits
  %   \@namedef{#1marksn}##1{##1}%
  % \else
  %   \@namedef{#1marksn}{\@gobble}%
  %   \fi
  \def\@tempa{1}
  \nametest{#3}{nonumber}%
  \ifsamename
    \def\@tempa{0}
  \else
    \nametest{#3}{shownumber}
    \ifsamename
      \def\@tempa{1}
    \else
      \nametest{#3}{notitle}
      \ifsamename
        \def\@tempa{2}
      \else
        \@memerror{Unknown numbering value `#3' for
          #1mark,\MessageBreak
          please use   one of 'shownumber', 'nonumber' or 'notitle'}%
        {I expected `shownumber', `nonumber' or 'notitle'.\MessageBreak
          I will assume you meant `shownumber'}%
      \fi
    \fi
  \fi
  \@namedef{#1markst}##1{##1}  
  \ifcase\@tempa\relax
    % nonumber
    \@namedef{#1marksn}{\@gobble}%
  \or % 1
    % shownumber
    \@namedef{#1marksn}##1{##1}
  \or % 2, 2 implies shownumber
    % shownumber
    \@namedef{#1marksn}##1{##1}
    \@namedef{#1markst}{\@gobble}  
  \fi
%    \end{macrocode}
% The three \meta{marks} cases, \texttt{left}, \texttt{both} and
% \texttt{right}; fails to \texttt{both}.
% \changes{v3.7f}{2015/08/25}{Sporious spaces}
%    \begin{macrocode}
  \nametest{#2}{left}%
  \ifsamename
    \@namedef{#1mark}##1{%
      \@setclcnt{#1}{@memmarkcntra}%
      \advance\c@@memmarkcntra\m@ne
      \markboth{%
        \memUChead{%
          \ifnum \c@secnumdepth > \c@@memmarkcntra
            \if@mainmatter
              \@nameuse{#1marksn}{#4\@nameuse{the#1}#5}%
            \fi
          \fi
%    \end{macrocode}
% \changes{v3.7i}{2019/11/07}{Added macro to get rid of the title if needed}
%    \begin{macrocode}
          \@nameuse{#1markst}{##1}%
        }%
      }%
      {}% just left
    }%
  \else
    \nametest{#2}{right}
    \ifsamename
      \@namedef{#1mark}##1{%
        \@setclcnt{#1}{@memmarkcntra}%
        \advance\c@@memmarkcntra\m@ne
        \markright{%
          \memUChead{%
            \ifnum \c@secnumdepth > \c@@memmarkcntra
              \if@mainmatter%
                \@nameuse{#1marksn}{#4\@nameuse{the#1}#5}%
              \fi%
            \fi%
%    \end{macrocode}
% \changes{v3.7i}{2019/11/07}{Added macro to get rid of the title if needed}
%    \begin{macrocode}
            \@nameuse{#1markst}{##1}%
          }%
        }%
      }%
    \else
      \nametest{#2}{both}%
      \ifsamename\else
        \@memerror{%
        Unknown mark setting type `#2' for #1mark}{%
        I expected `left', `both' or `right'. \MessageBreak
        I will assume you meant `both'}%	
      \fi
    \@namedef{#1mark}##1{%
      \@setclcnt{#1}{@memmarkcntra}%
      \advance\c@@memmarkcntra\m@ne
      \markboth{%
        \memUChead{%
          \ifnum \c@secnumdepth > \c@@memmarkcntra
            \if@mainmatter
              \@nameuse{#1marksn}{#4\@nameuse{the#1}#5}%
            \fi
          \fi
%    \end{macrocode}
% \changes{v3.7i}{2019/11/07}{Added macro to get rid of the title if needed}
%    \begin{macrocode}
          \@nameuse{#1markst}{##1}%
        }%
      }{%
        \memUChead{%
          \ifnum \c@secnumdepth > \c@@memmarkcntra
            \if@mainmatter
              \@nameuse{#1marksn}{#4\@nameuse{the#1}#5}%
            \fi
          \fi
%    \end{macrocode}
% \changes{v3.7i}{2019/11/07}{Added macro to get rid of the title if needed}
%    \begin{macrocode}
          \@nameuse{#1markst}{##1}%
        }%
      }%
    }%
    \fi
  \fi
}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\addtopsmarks}
% \cs{addtopsmarks}\marg{pagestyle}\marg{prepend}\marg{append} inserts
% \meta{prepend} and \meta{append} at the start and end of the current
% definition of \cs{pagestylepshook}.
% \changes{v1.61803398d}{2010/02/09}{Added safe to change test}
% \changes{v3.8.4}{2025/06/12}{Forgot to redef this after we deprecated
% \cs{addtodef}, we will use \cs{pretocmd} and \cs{apptocmd} from
% \pkg{etoolbox} instead.}
%    \begin{macrocode}
\NewDocumentCommand\addtopsmarks{ m m m }
{
  \mem@ps@safe@change{#1}
  \IfBlankF{#2}{ \ExpandArgs{c}\pretocmd{#1pshook}{#2}{}{\typeout{prepending to #1marks failed}} }
  \IfBlankF{#3}{ \ExpandArgs{c}\apptocmd{#1pshook}{#3}{}{\typeout{appending to #1marks failed}}  } 
}
%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\clearplainmark}
% \begin{macro}{\clearmark}
%  For some page styles it is handy to be able to make sure that no
%  section or otherwise add data to the \cs{left-} and
%  \cs{rightmark}. The macros \cs{clearplainmark} and \cs{clearmark}
%  will take one argument specifying which mark to clear, and then
%  redefine this mark to do nothing or to gobble its given argument.
%    \begin{macrocode}
\newcommand\clearplainmark[1]{%
  \@namedef{#1mark}{}}
\newcommand\clearmark[1]{%
  \@namedef{#1mark}{\@gobble}}
%    \end{macrocode}
%  
% \end{macro}
% \end{macro}
%
% \begin{macro}{\ps@headings}
%    The \pstyle{headings} pagestyle behaves differently for
% twosided and onesided printing. This is a rewrite of the
% standard style.
% \changes{v1.1}{2002/03/10}{Added \cs{tocmark} etc., to \cs{ps@headings}}
% \changes{v1.61803}{2008/01/30}{Used \cs{memUChead} in \cs{ps@headings}
%              (mempatch v4.9)}
% \changes{v1.61803}{2008/01/30}{For twosided docs set both marks for ToC, etc. (mempatch v4.9)}
% \changes{v1.61803}{2008/01/30}{Eliminated \cs{@mkboth} as never used
%                    (mempatch v4.9)}
% \changes{v1.61803}{2008/01/30}{Added \cs{glossarymark} to \cs{ps@headings}}
%    \begin{macrocode}
\if@twoside
%    \end{macrocode}
% The footer is empty and the header contains the page number and
% one of the marks.
% \changes{v3.8.4}{2025/08/06}{No idea why this code wasn't outcommented years ago}
%    \begin{macrocode}
  \makepagestyle{headings}
    % \makepsmarks{headings}{%
    %   \def\chaptermark##1{%
    %     \markboth{\memUChead{%
    %       \ifnum \c@secnumdepth >\m@ne
    %         \if@mainmatter
    %           \@chapapp\ \thechapter. \ %
    %         \fi
    %       \fi
    %       ##1}}{}}%
    %   \def\tocmark{\markboth{\memUChead{\contentsname}}{\memUChead{\contentsname}}}%
    %   \def\lofmark{\markboth{\memUChead{\listfigurename}}{\memUChead{\listfigurename}}}%
    %   \def\lotmark{\markboth{\memUChead{\listtablename}}{\memUChead{\listtablename}}}%
    %   \def\bibmark{\markboth{\memUChead{\bibname}}{\memUChead{\bibname}}}%
    %   \def\indexmark{\markboth{\memUChead{\indexname}}{\memUChead{\indexname}}}%
    %   \def\sectionmark##1{%
    %     \markright{\memUChead{%
    %       \ifnum \c@secnumdepth > \z@
    %         \thesection. \ %
    %       \fi
    %       ##1}}}}
%    \end{macrocode}
% And here's a version of the above \cs{makepsmarks} using \cs{createmark} and 
% \cs{createplainmark}.
%    \begin{macrocode}
    \makepsmarks{headings}{%
      \createmark{chapter}{left}{shownumber}{\@chapapp\ }{. \ }
      \createmark{section}{right}{shownumber}{}{. \ }
      \createplainmark{toc}{both}{\contentsname}
      \createplainmark{lof}{both}{\listfigurename}
      \createplainmark{lot}{both}{\listtablename}
      \createplainmark{bib}{both}{\bibname}
      \createplainmark{index}{both}{\indexname}
      \createplainmark{glossary}{both}{\glossaryname}
    }
    \makeevenhead{headings}{\thepage}{}{\slshape\leftmark}
    \makeoddhead{headings}{\slshape\rightmark}{}{\thepage}
\else
%    \end{macrocode}
% For one sided printing even and odd pages are treated the same,
% so no need to bother with the evenhead, and
% just the \cs{rightmark} is used.     
% \changes{v3.8.4}{2025/08/06}{No idea why this code wasn't outcommented years ago}
%    \begin{macrocode}
  \makepagestyle{headings}
    % \makepsmarks{headings}{%
    %   \def\chaptermark##1{%
    %     \markright{\memUChead{%
    %       \ifnum \c@secnumdepth >\m@ne
    %         \if@mainmatter
    %           \@chapapp\ \thechapter. \ %
    %         \fi
    %       \fi
    %       ##1}}}%
    %   \def\tocmark{\markright{\memUChead{\contentsname}}}%
    %   \def\lofmark{\markright{\memUChead{\listfigurename}}}%
    %   \def\lotmark{\markright{\memUChead{\listtablename}}}%
    %   \def\bibmark{\markright{\memUChead{\bibname}}}%
    %   \def\indexmark{\markright{\memUChead{\indexname}}}}
%    \end{macrocode}
% And here's a version of the above \cs{makepsmarks} using \cs{createmark} and 
% \cs{createplainmark}.
%    \begin{macrocode}
    \makepsmarks{headings}{%
      \createmark{chapter}{right}{shownumber}{\@chapapp\ }{. \ }
      \createplainmark{toc}{right}{\contentsname}
      \createplainmark{lof}{right}{\listfigurename}
      \createplainmark{lot}{right}{\listtablename}
      \createplainmark{bib}{right}{\bibname}
      \createplainmark{index}{right}{\indexname}
      \createplainmark{glossary}{right}{\glossaryname}
    }
    \makeoddhead{headings}{\slshape\rightmark}{}{\thepage}
\fi

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ps@myheadings}
%    The \pstyle{myheadings} page style is simpler because the user
% has to specify the contents using \cs{markboth} and \cs{markright}
% commands. This is the definition used in the standard classes.
% \changes{v1.1}{2002/03/10}{Added \cs{tocmark} etc., to \cs{ps@myheadings}}
%    \begin{verbatim}}
% \newcommand{\ps@myheadings}{%
%   \let\@oddfoot\@empty\let\@evenfoot\@empty
%   \def\@evenhead{\thepage\hfil{\slshape\leftmark}}%
%   \def\@oddhead{{\slshape\rightmark}\hfil\thepage}%
%   \let\@mkboth\@gobbletwo
%   \let\chaptermark\@gobble
%   \let\sectionmark\@gobble
% }
% \end{verbatim}
% Translating that into our terms we get:
% \changes{v1.0}{2001/11/15}{Changed the code for creating the myheadings pagestyle}
% \changes{v1.4}{2003/11/22}{Further change to myheadings pagestyle code}
%    \begin{macrocode}
\makepagestyle{myheadings}
  \makepsmarks{myheadings}{%
    \let\chaptermark\@gobble
    \let\sectionmark\@gobble
    \def\tocmark{}%
    \def\lofmark{}%
    \def\lotmark{}%
    \def\bibmark{}%
    \def\indexmark{}%
    \def\glossarymark{}}
  \makeevenhead{myheadings}{\thepage}{}{\slshape\leftmark}
  \makeoddhead{myheadings}{\slshape\rightmark}{}{\thepage}

%    \end{macrocode}
%   (Kai von Fintel emailed me on 2003/02/24 saying that the original
%   \verb?\let\tocmark\@gobble? in the myheadings pagestyle did nasty
%   things to the ToC, etc. Now using \verb?\def\tocmark{}?.)
% \end{macro}
%
% \begin{macro}{\ps@chapter}
% \begin{macro}{\ps@part}
% \begin{macro}{\ps@cleared}
%  The standard classes use the \pstyle{plain} pagestyle for the first page
% of a chapter. This class uses the \pstyle{chapter} instead, which is
% aliased to \pstyle{plain}. Similarly for parts. 
% Further, \cs{cleardoublepage} uses whatever
% pagestyle is in effect for the empty verso page. I find that this
% looks odd if the header contains a chapter name. This class uses
% the \pstyle{cleared} pagestyle in this case. I have aliased this
% to \pstyle{empty}; the \pstyle{plain} would be another reasonable choice.
%    \begin{macrocode}
\aliaspagestyle{chapter}{plain}
\aliaspagestyle{part}{plain}
\aliaspagestyle{cleared}{empty}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\cleardoublepage}
% A slight adjustment to the kernel definition to set a pagestyle.
%    \begin{macrocode}
\def\cleardoublepage{\clearpage\if@twoside \ifodd\c@page\else
  \hbox{}\thispagestyle{cleared}%
  \newpage\if@twocolumn\hbox{}\newpage\fi\fi\fi}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\ps@ruled}
%    Partly to show how it is done, the class provides a \pstyle{ruled} pagestyle.
% In this style the headers and footers are the same width as the textblock,
% there is a rule under the header, page numbers are set in the footers
% at the outside of the page. Even page headers have the chapter number
% and title at the left, and odd page headers have the section title
% at the right.
%
%    Start by making the (empty) \pstyle{ruled} pagestyle.
%    \begin{macrocode}
\makepagestyle{ruled}
%    \end{macrocode}
% There is no need to change the default width (which is the \cs{textwidth}),
% nor the default positions (centered),
% nor to make the footrule visible. We do, though, have to put the page
% numbers into the footers.
%    \begin{macrocode}
\makeevenfoot{ruled}{\thepage}{}{}
\makeoddfoot{ruled}{}{}{\thepage}
%    \end{macrocode}
% Make the header rule visible and equal to the \cs{textwidth}.
%    \begin{macrocode}
\makeheadrule{ruled}{\textwidth}{\normalrulethickness}
%    \end{macrocode}
%
% \begin{macro}{\@ruledmarks}
% We have to make sure that the \cs{chapter} and \cs{section} commands make
% the appropriate marks for use in the headers. We use the hook for this.
% Note that contrary to normal \LaTeX{} practice, the titles are not
% automatically upper-cased. The marks for the tocbibinds also need adjusting.
% \changes{v1.1}{2002/03/10}{Changed \cs{@ruledmarks} to cater for tocbibind}
% \changes{v3.8.4}{2025/08/06}{We only leave the version made with our marks}
%    \begin{macrocode}
 % \newcommand{\@ruledmarks}{%
 %   \def\chaptermark##1{%
 %     \markboth{%
 %       \ifnum \c@secnumdepth >\m@ne
 %         \if@mainmatter
 %           \thechapter. \ %
 %         \fi
 %       \fi
 %       ##1}{}}
 %   \def\sectionmark##1{\markright{##1}}
 %   \def\tocmark{\markboth{\contentsname}{}}
 %   \def\lofmark{\markboth{\listfigurename}{}}
 %   \def\lotmark{\markboth{\listtablename}{}}
 %   \def\bibmark{\markboth{\bibname}{}}
 %   \def\indexmark{\markboth{\indexname}{}}
 %   \def\glossarymark{\markboth{\glossaryname}{}}
 % }
%    \end{macrocode}
% Here's a version using \cs{createmark} and friends.
%    \begin{macrocode}
\newcommand*{\@ruledmarks}{%
  \nouppercaseheads
  \createmark{chapter}{left}{shownumber}{}{. \space}
  \createmark{section}{right}{shownumber}{}{. \space}
  \createplainmark{toc}{both}{\contentsname}
  \createplainmark{lof}{both}{\listfigurename}
  \createplainmark{lot}{both}{\listtablename}
  \createplainmark{bib}{both}{\bibname}
  \createplainmark{index}{both}{\indexname}
  \createplainmark{glossary}{both}{\glossaryname}}
\makepsmarks{ruled}{\@ruledmarks}
%    \end{macrocode}
% \end{macro}
%
% We can now define the even page header which is to have the chapter title
% at the left. As the chapter mark did no upper-casing we will print it
% using small caps, but just use the normal font for section title on
% the odd page header.
%    \begin{macrocode}
\makeevenhead{ruled}{\scshape\leftmark}{}{}
\makeoddhead{ruled}{}{}{\rightmark}

%    \end{macrocode}
% \end{macro}
% This is all that we need to do for the \pstyle{ruled} pagestyle.
%
% \begin{macro}{\ps@Ruled}
%    Also define a \pstyle{Ruled} pagestyle similar to \pstyle{ruled} except that the
% headers and footers are 10\% wider than the textblock, sticking out
% into the fore edge.
%    \begin{macrocode}
\makepagestyle{Ruled}
\makerunningwidth{Ruled}{1.1\textwidth}
\makeheadposition{Ruled}{flushright}{flushleft}{flushright}{flushleft}
\makeevenfoot{Ruled}{\thepage}{}{}
\makeoddfoot{Ruled}{}{}{\thepage}
\makeheadrule{Ruled}{1.1\textwidth}{\normalrulethickness}
\makepsmarks{Ruled}{\@ruledmarks}
\makeevenhead{Ruled}{\scshape\leftmark}{}{}
\makeoddhead{Ruled}{}{}{\rightmark}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\headwidth}
% \begin{macro}{\ps@companion}
% A \pstyle{companion} pagestyle like the one in the 
% \textit{\LaTeX{} Companion} series.
% We need the \cs{headwidth} length for this.
% \changes{v1.1}{2002/03/10}{Added \cs{tocmark} etc., to \cs{ps@companion}}
%    \begin{macrocode}
\newlength{\headwidth}

\makepagestyle{companion}
\setlength{\headwidth}{\textwidth}
  \addtolength{\headwidth}{\marginparsep}
  \addtolength{\headwidth}{\marginparwidth}
\makerunningwidth{companion}{\headwidth}
\makeheadrule{companion}{\headwidth}{\normalrulethickness}
\makeheadposition{companion}{flushright}{flushleft}{}{}
%    \end{macrocode}
% \changes{v3.8.4}{2025/08/06}{might as well outcomment this as the \cs{create...} below overwrites it}
%    \begin{macrocode}
 % \makepsmarks{companion}{%
 %   \def\chaptermark##1{\markboth{##1}{##1}}    % left mark & right marks
 %   \def\sectionmark##1{\markright{%
 %     \ifnum \c@secnumdepth>\z@
 %       \thesection. \ %
 %     \fi
 %     ##1}}
 %   \def\tocmark{\markboth{\contentsname}{\contentsname}}
 %   \def\lofmark{\markboth{\listfigurename}{\listfigurename}}
 %   \def\lotmark{\markboth{\listtablename}{\listtablename}}
 %   \def\bibmark{\markboth{\bibname}{\bibname}}
 %   \def\indexmark{\markboth{\indexname}{\indexname}}}
%    \end{macrocode}
% And here's a version of the above \cs{makepsmarks} using \cs{createmark} and 
% \cs{createplainmark}.
%    \begin{macrocode}
\makepsmarks{companion}{%
  \nouppercaseheads
  \createmark{chapter}{both}{nonumber}{}{}
  \createmark{section}{right}{shownumber}{}{. \space}
  \createplainmark{toc}{both}{\contentsname}
  \createplainmark{lof}{both}{\listfigurename}
  \createplainmark{lot}{both}{\listtablename}
  \createplainmark{bib}{both}{\bibname}
  \createplainmark{index}{both}{\indexname}
  \createplainmark{glossary}{both}{\glossaryname}}
\makeevenhead{companion}{\normalfont\bfseries\thepage}{}%
                        {\normalfont\bfseries\leftmark}
\makeoddhead{companion}{\normalfont\bfseries\rightmark}{}%
                       {\normalfont\bfseries\thepage}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% Another pagestyle called \pstyle{showlocs} can be used to show the
% locations of the header, footer and textblock. I would expect that
% this would be mainly used as an example for authors to create their
% own similar styles.
% \changes{v1.6180339c}{2008/12/28}{Added the showlocs pagestyle and supporting
%                       macros}
% \changes{v1.6180339c}{2009/01/25}{Added more supporting macros for the 
%                       showlocs pagestyle}
%
% \begin{macro}{\ifshowheadfootloc}
% \begin{macro}{\showheadfootloctrue}
% \begin{macro}{\showheadfootlocfalse}
% \begin{macro}{\showheadfootlocon}
% \begin{macro}{\showheadfootlocoff}
% \begin{macro}{\ifshowtextblockloc}
% \begin{macro}{\showtextblockloctrue}
% \begin{macro}{\showtextblocklocfalse}
% \begin{macro}{\showtextblocklocon}
% \begin{macro}{\showtextblocklocoff}
% Booleans controlling the appearance, or not, of the header/footer lines
% and text frame in \pstyle{showlocs}.
%    \begin{macrocode}
\newif\ifshowheadfootloc
  \showheadfootloctrue
\newcommand*{\showheadfootlocon}{\showheadfootloctrue}
\newcommand*{\showheadfootlocoff}{\showheadfootlocfalse}
\newif\ifshowtextblockloc
  \showtextblockloctrue
\newcommand*{\showtextblocklocon}{\showtextblockloctrue}
\newcommand*{\showtextblocklocoff}{\showtextblocklocfalse}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \begin{macro}{\framepichook}
% \changes{v3.6k}{2013/05/08}{Added \cs{framepichook}}
%   The two macros \cs{framepichead} and \cs{framepictextfoot} are used
%   to make up the \texttt{showlocs} page style. They are both zero
%   width \texttt{picture} environments. The very first thing in these
%   \texttt{picture} environments, is a call to \cs{framepichook}
%   (empty by default), which could be used to change the color of the
%   frame.
%    \begin{macrocode}
\newcommand\framepichook{}
%    \end{macrocode}
%   
% \end{macro}
% \begin{macro}{\framepichead}
% For producing a zero-sized picture of a line at the base of the header.
% It is meant to be used as the left part of the header for a pagestyle.
% \changes{v1.6180339c}{2008/12/28}{Added \cs{framepichead}}
% \changes{v3.6k}{2013/05/08}{Added \cs{framepichook}}
%    \begin{macrocode}
\newcommand*{\framepichead}{%
\ifshowheadfootloc
  \begin{picture}(0,0)
    \framepichook
    \unitlength 1pt
    \put(0,0){\line(1,0){\strip@pt\textwidth}}
  \end{picture}%
\fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\framepictextfoot}
% For producing a zero-sized picture of a line at the base of the footer
% and a frame around the text block. It is meant to be used as the left
% part of a footer for a pagestyle.
% \changes{v1.6180339c}{2008/12/28}{Added \cs{framepictextfoot}}
% \changes{v3.6k}{2013/05/08}{Added \cs{framepichook}}
%    \begin{macrocode}
\newcommand*{\framepictextfoot}{%
  \begin{picture}(0,0)
    \framepichook
    \unitlength 1pt
    \ifshowheadfootloc
      \put(0,0){\line(1,0){\strip@pt\textwidth}}
    \fi
    \ifshowtextblockloc
      \put(0,\strip@pt\footskip)%
        {\framebox(\strip@pt\textwidth,\strip@pt\textheight){}}
    \fi
  \end{picture}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ps@showlocs}
% The \pstyle{showlocs} pagestyle. This is more to show what can be done.
% \changes{v1.6180339c}{2008/12/28}{Added the showlocs pagestyle}
%    \begin{macrocode}
\makepagestyle{showlocs}
\makeevenhead{showlocs}{\framepichead\thepage}{\thepage}{\thepage}
\makeoddhead{showlocs}{\framepichead\thepage}{\thepage}{\thepage}
\makeevenfoot{showlocs}{\framepictextfoot\thepage}{\thepage}{\thepage}
\makeoddfoot{showlocs}{\framepictextfoot\thepage}{\thepage}{\thepage}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\fixheaderwidths}
% The companion pagestyle, at least, needs adjusting (at \cs{fixthelayout} time)
% if the \cs{textwidth} has changed from its initial value.
% \changes{v1.6180339f}{2009/03/16}{Added \cs{fixheaderwidths}}
%    \begin{macrocode}
\newcommand*{\fixheaderwidths}{%
  % companion pagestyle
  \setlength{\headwidth}{\textwidth}
    \addtolength{\headwidth}{\marginparsep}
    \addtolength{\headwidth}{\marginparwidth}
  \makerunningwidth{companion}{\headwidth}
  \makeheadrule{companion}{\headwidth}{\normalrulethickness}
  \makefootrule{companion}{\textwidth}{\footruleheight}{\footruleskip}
}

%    \end{macrocode}
% \end{macro}
%
%
% \subsection{Page numbering}
%
% The kernel includes the \cs{pagenumbering} command for setting the
% style (arabic, roman, etc.) of the page numbers, and at the same
% time it resets the page counter. I want a version that resets the
% style but not the number\footnote{Added to meet a request by Daniel
% Richard G.  September 2001.}.
%
% \begin{macro}{\pagenumbering}
% \begin{macro}{\pagenumbering*}
% \cs{pagenumbering}\marg{style} is the normal version whereas
% the starred version does not reset the counter.
% \changes{v1.0}{2001/09/21}{Added \cs{pagenumbering} and \cs{pagenumbering*} }
% \changes{v3.8}{2023/05/08}{Reimplemented as a single macro via \RenewDocumentCommand}
%    \begin{macrocode}
\RenewDocumentCommand\pagenumbering{sm}{%
  \gdef\thepage{\csname @#2\endcsname \c@page}%
  \IfBooleanF{#1}{\global\c@page \@ne}% reset counter unless starred
}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\c@storedpagenumber}
% A counter to store the page number.
%    \begin{macrocode}
\newcounter{storedpagenumber}
  \setcounter{storedpagenumber}{1}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\savepagenumber}
% \begin{macro}{\restoregenumber}
% \cs{savepagenumber} saves the current page number and \cs{restorepagenumber}
% sets the page number to the stored value.
% \changes{v1.0}{2001/09/24}{Added \cs{savepagenumber} and \cs{restorepagenumber}}
%    \begin{macrocode}
\newcommand{\savepagenumber}{\global\c@storedpagenumber \c@page}
\newcommand{\restorepagenumber}{\global\c@page \c@storedpagenumber}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% \section{Non-traditional spacing}
% \changes{v1.61803}{2008/01/30}{Added non-traditional spacing 
%                     (mempatch v4.6)}
%
% \subsection{Double spacing}
%
% This is an embedding and extension of the code from the \Lpack{setspace} 
% package, with
% names changed.
%
% \begin{macro}{\setSpacing}
% \cs{setSpacing}\marg{num} effectively increases the \cs{baselineskip} to 
% \meta{num}*\cs{baselineskip}.
% (In package was \cs{setstretch}).
%    \begin{macrocode}
\newcommand*{\setSpacing}[1]{%
  \def\baselinestretch{#1}%
  \@currsize}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\setSingleSpace}
% \begin{macro}{\setFootnoteSpacing}
% \begin{macro}{\setFloatSpacing}
% \cs{setSingleSpace}\marg{num} effectively increases the \cs{baselineskip} for
% single spacing to \meta{num}*\cs{baselineskip} (\meta{num} should be 
% close to 1.0). (In package was \cs{SetSinglespace}). We extend with
% two extra macros \cs{setFootnoteSpacing} and \cs{setFloatSpacing}
% which can be used to explicitly set the spacing inside page notes
% (fotnotes and friends) and inside floats. Changing
% \cs{setSingleSpace} will also set page note and float spacings to
% the same value.
% \changes{v3.6g}{2010/09/19}{Added two extra 'single' spacing macros}
%    \begin{macrocode}
\newcommand*{\setSingleSpace}[1]{%
  \def\m@m@singlespace{#1}%
  \def\m@m@footnote@spacing{#1}%
  \def\m@m@float@spacing{#1} %
}
\setSingleSpace{1}
\newcommand*\setPagenoteSpacing[1]{\def\m@m@footnote@spacing{#1}}
\newcommand*\setFloatSpacing[1]   {\def\m@m@float@spacing{#1}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\SingleSpacing}
% \begin{macro}{\SingleSpacing*}
% \cs{SingleSpacing} starts single spacing. (In package was \cs{singlespacing}).
% \changes{v3.6g}{2010/09/19}{Added reset of the float and page note spacings}
%    \begin{macrocode}
\newcommand*{\SingleSpacing}{%
  \setSpacing{\m@m@singlespace}%
  \edef\m@m@footnote@spacing{\baselinestretch}%
  \edef\m@m@float@spacing{\baselinestretch}%
%    \end{macrocode}
% \changes{v3.7h}{2018/09/19}{Added the ifstar and \cs{@noocument}}
% We can have a strange interaction with \Lpack{tikz} if this
% \cs{vskip} is emitted in the preamble. We use a trick (via David
% Carlisle) to check whether we are in the preamble, and only emit the
% vskip if we are not. \cs{@ifstar} added to let the user disable the
% vskip if needed.
%    \begin{macrocode}
  \@ifstar{}{\ifx\@nodocument\relax\vskip\baselineskip\fi}% correction for coming into single spacing
}
\SingleSpacing

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\@OnehalfSpacing}
% \begin{macro}{\OnehalfSpacing}
% \cs{OnehalfSpacing} starts `one and a half' spacing, which to most 
% thesis nitpickers will look like double spacing.
% (In package was \cs{onehalfspacing}). The starred version
% \cs{OnehalfSpacing*} will also give page notes and floats the same spacing
% \changes{v3.6g}{2010/09/19}{Made \cs{OnehalfSpacing} into a starred
% version such that the starred version makes everything one half
% spaced including page notes and floats}
%    \begin{macrocode}
\newcommand*{\@OnehalfSpacing}{
  \setSpacing{1.25}% default (10pt)
  \ifcase \@ptsize \relax   % 10pt
    \setSpacing{1.25}%
  \or%  11pt
    \setSpacing{1.213}%
  \or%  12pt
    \setSpacing{1.241}%
  \or\or% 14pt
    \setSpacing{1.20}%
  \or\or\or% 17pt
    \setSpacing{1.16}%
  \or\or% 9pt
    \setSpacing{1.35}%
  \else% the extended sizes
    \setSpacing{1.16}%
  \fi}
\newcommand*\OnehalfSpacing{%
  \@ifstar{%
    \@OnehalfSpacing%
    \edef\m@m@footnote@spacing{\baselinestretch}%
    \edef\m@m@float@spacing{\baselinestretch}%
  }{\@OnehalfSpacing}%
}
    
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\DoubleSpacing}
% \begin{macro}{\@DoubleSpacing}
% \cs{DoubleSpacing} starts double spacing, which to most thesis nitpickers
% will look far too spaced out. (In package was
% \cs{doublespacing}). The starred version will also set the page note
% and float spacing to the same value.
% \changes{v3.6g}{2010/09/19}{Extended with a starred version.}
%    \begin{macrocode}
\newcommand*{\@DoubleSpacing}{
  \setSpacing{1.667}% default (10pt)
  \ifcase \@ptsize \relax   % 10pt
    \setSpacing{1.667}%
  \or%  11pt
    \setSpacing{1.618}%
  \or%  12pt
    \setSpacing{1.655}%
  \or\or% 14pt
    \setSpacing{1.60}%
  \or\or\or% 17pt
    \setSpacing{1.545}%
  \or\or% 9pt
    \setSpacing{1.8}%
  \else%       larger sizes
    \setSpacing{1.5}%
  \fi}
\newcommand*\DoubleSpacing{%
  \@ifstar{%
    \@DoubleSpacing%
    \edef\m@m@footnote@spacing{\baselinestretch}%
    \edef\m@m@float@spacing{\baselinestretch}%
  }{\@DoubleSpacing}%
}
    
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\@setsize}
% Modify the kernel command.
% \changes{v3.8}{2023/08/08}{\cs{@setsize} redef removed. It came from
% setspace.sty which note that it was needed for some 209 packages. In
% the kernel it is just defined to use \cs{@setfontsize}. We remove it}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% check what this does!!!!!!!!
%    \begin{macrocode}
 % \renewcommand*{\@setsize}[4]{%
 %   \@nomath#1%
 %   \let\@currsize#1%
 %   \baselineskip #2%
 %   \baselineskip \baselinestretch\baselineskip
 %   \parskip \baselinestretch\parskip
 %   \setbox\strutbox \hbox{%
 %     \vrule height.7\baselineskip
 %            depth .3\baselineskip
 %            width \z@}%
 %   \skip\footins \baselinestretch\skip\footins
 %   \normalbaselineskip\baselineskip#3#4}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{environment}{SingleSpace}
% Environment form of \cs{SingleSpacing}. (In package was \texttt{singlespace}).
%    \begin{macrocode}
\newenvironment{SingleSpace}{%
  \vskip\baselineskip
  \setSpacing{\m@m@singlespace}%
  \vskip -\baselineskip
}{\par}

%    \end{macrocode}
% \end{environment}
%
% \begin{environment}{SingleSpace*}
% Don't use this; it's only here to match the \Lpack{setspace} package. 
% (In package was \texttt{singlespace*}).
%    \begin{macrocode}
\newenvironment{SingleSpace*}{%
%%  \vskip\baselineskip
  \setSpacing{\m@m@singlespace}%
  \vskip 0.5\baselineskip
}{\vskip -0.5\baselineskip}

%    \end{macrocode}
% \end{environment}
%
% \begin{macro}{\m@mrestore@spacing}
%    \begin{macrocode}
\newcommand*{\m@mrestore@spacing}{%
  \par
  \vskip \parskip
  \vskip \baselineskip
  \endgroup
  \vskip -\parskip
  \vskip -\baselineskip}

%    \end{macrocode}
% \end{macro}
%
% \begin{environment}{Spacing}
% \verb?\begin{Spacing}{num}? increases the \cs{baselineskip} 
% to \verb?num*\baselineskip?. (In package was \texttt{spacing}).
%    \begin{macrocode}
\newenvironment{Spacing}[1]{%
  \par
  \begingroup
    \setSpacing{#1}}{\m@mrestore@spacing}

%    \end{macrocode}
% \end{environment}
%
% \begin{environment}{OnehalfSpace}
% Environment form of \cs{OnehalfSpacing}. (In package was \texttt{onehalfspace}).
% \changes{v3.6g}{2010/09/19}{Added starred version of environment to
% complement the starred macro version}
%    \begin{macrocode}
\newenvironment{OnehalfSpace}{%
  \begingroup
    \OnehalfSpacing}{\m@mrestore@spacing}
\newenvironment{OnehalfSpace*}{%
  \begingroup
    \OnehalfSpacing*}{\m@mrestore@spacing}

%    \end{macrocode}
% \end{environment}
%
% \begin{environment}{DoubleSpace}
% Environment form of \cs{DoubleSpacing}. (In package was \texttt{doublespace}).
% \changes{v3.6g}{2010/09/19}{Added starred version of environment to
% complement the starred macro version}
%    \begin{macrocode}
\newenvironment{DoubleSpace}{%
  \begingroup
    \DoubleSpacing}{\m@mrestore@spacing}
\newenvironment{DoubleSpace*}{%
  \begingroup
    \DoubleSpacing}{\m@mrestore@spacing}

%    \end{macrocode}
% \end{environment}
%
%
%  Deal with spacing around displays.
%
% \begin{macro}{\memdskipstretch}
% \begin{macro}{\setDisplayskipStretch}
% \begin{macro}{\noDisplayskipStretch}
% \cs{setDisplayskipStretch}\marg{num} changes space around displays by the
% factor (1+\meta{num}). \cs{noDisplaydkipStretch} keeps the regular
% spacing around displays. (In package were \cs{setdisplayskipstretch} and
% the \texttt{nodisplayskipstretch} option).
%    \begin{macrocode}
\newcommand*{\memdskipstretch}{0.0}
\newcommand*{\setDisplayskipStretch}[1]{%
  \renewcommand*{\memdskipstretch}{#1}}
\newcommand*{\noDisplayskipStretch}{\setDisplayskipStretch{0.0}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\memdskips}
% Macro added to the kernel hook \cs{everydisplay}, changing the settings 
% of displayskips
%    \begin{macrocode}
\newcommand*{\memdskips}{%
  \advance\abovedisplayskip \memdskipstretch\abovedisplayskip
  \advance\belowdisplayskip \memdskipstretch\belowdisplayskip
  \advance\abovedisplayshortskip \memdskipstretch\abovedisplayshortskip
  \advance\belowdisplayshortskip \memdskipstretch\belowdisplayshortskip}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\everydisplay}
%    \begin{macrocode}
\everydisplay\expandafter{%
  \the\everydisplay
  \memdskips}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@floatboxreset}
%   Reset \cs{baselinestretch} in floats. If the format version
%   supports it we add it via a cmd hook, if not, we delay until the
%   start of the document and use the older definition. Note that the
%   hook cannot access the arguments given to \cs{@xfloat}, luckily it
%   stores \#1 in \cs{@captype}.
%   \changes{v3.7d}{2014/07/28}{Delayed addition to  \cs{@xfloat}. Reported by Ulrike Fischer}
%   \changes{v3.7g}{2017/05/08}{Delayed the addition of the adjustment
%   to the float until after \cs{normalsize}. Reported at \protect\url{https://tex.stackexchange.com/q/368422/3929}}
%   \changes{v3.8}{2023/05/08}{Additions to \cs{@xfloat} now added
%   via a cmd/after hook if the format supports it}
%   \changes{v3.8.1}{2023/08/21}{Changed the hook to add to
%   \cs{@floatboxreset} as the \Lpack{float} package redefines
%   \cs{@xfloat} so the Hook cannot access it.}
% \changes{v3.8.4}{2025/09/24}{Format tjek removed as we now require kernel of 2023/06/01}
%    \begin{macrocode}
\AddToHook{cmd/@floatboxreset/after}{%
  \def\baselinestretch{\m@m@float@spacing}%
  \normalsize%
  \@nameuse{\@captype adjustment}%
}

%    \end{macrocode}
% \end{macro}
%
%  The extra spacing does not add space before and after a minipage.
% The solution, hinted at by Donald Arseneau, is to create a new
% environment. I came up with a solution which DA then much improved upon
% (CTT \textit{setspace and minipages}, 2006/11/28). 
% This is like minipage from an author's view, except that it is 
% always top positioned and acts like a paragraph.
% \begin{macro}{\memPD}
%    \begin{macrocode}
\newdimen\memPD
%    \end{macrocode}
% \end{macro}
% \begin{environment}{vminipage}
% The user view, just as for \texttt{minipage}, but ensures the \texttt{t}
% position and as a new paragraph. It is like \texttt{minipage} but with 
% better fore and aft spacing.
%    \begin{macrocode}
\newenvironment{vminipage}{%
  \par
  \@ifnextchar[%]
    \@ivminipage
    {\@iiiminipage t\relax[s]}
}{%
  \par\global\memPD=\prevdepth
  \endminipage
  \par
  \kern-\memPD%     no pagebreak allowed here
  \hbox{\vrule depth \memPD width \z@}}

%    \end{macrocode}
% \end{environment}
%
% \begin{macro}{\@ivminipage}
% Deal with first optional argument to \texttt{vminipage}.
%    \begin{macrocode}
 \def\@ivminipage[#1]{%
  \@ifnextchar[%]
    {\@iiminipage{t}}{\@iiiminipage{t}\relax[s]}}
%    \end{macrocode}
% \end{macro}
%
%
% \subsection{Abnormal parskips}
%
% Non-zero, positive \cs{parskip}, which is not to be encouraged. Code
% based on Robin Fairbairns \Lpack{parskip} package and the NTG classes.
%
% \begin{macro}{\ifm@mnzpskip}
% \begin{macro}{\m@mnzpskiptrue}
% \begin{macro}{\m@mnzpskipfalse}
% \cs{ifm@mnzpskip} is TRUE if \cs{parskip} set to anything but 0pt.
%    \begin{macrocode}
\newif\ifm@mnzpskip
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\traditionalparskip}
% \begin{macro}{\m@mabparskip}
% \begin{macro}{\abnormalparskip}
% \begin{macro}{\nonzeroparskip}
% \cs{traditionalparskip} sets \cs{parskip} to 0pt.
% \cs{abnormalparskip}\marg{length} sets \cs{parskip} to \meta{length}.
% \cs{nonzeroparskip} sets \cs{parskip} to a non-zero value that might be 
% not too bad (any non-zero \cs{parskip} is not good).
% \changes{v1.61803398c}{2009/11/13}{\cs{parskip} was set to \cs{z@},
% thus the stretch was missing, this broke \cs{flushbottom}}
%    \begin{macrocode}
\newcommand*{\traditionalparskip}{%
  \setlength\parskip{0\p@ \@plus \p@}
  \m@mnzpskipfalse}
\newskip\m@mabparskip
\newcommand*{\abnormalparskip}[1]{%
  \setlength{\parskip}{#1}\m@mabparskip=#1\relax
  \m@mnzpskiptrue}
\newcommand*{\nonzeroparskip}{\abnormalparskip{%
  0.5\baselineskip 
  \@plus .1\baselineskip \@minus .1\baselineskip% NTG
%%  0.5/baselineskip \@plus 2pt% RF
}}
\traditionalparskip

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\@minpagerestore}
% This needs extending: here's what NTG does, but I've put the
% appropriate code later.
% \begin{verbatim}
% \providecommand*{\@minipagerestore}{%
%   \parskip=.5\baselineskip \@plus .1\baselineskip \@minus .1\baselineskip}
% \end{verbatim}
% \end{macro}
%
% \section{Titles}
%
%    For books the title is usually designed specifically for the particular
% work, so originally the class did not provide a \cs{maketitle} command or 
% any of the \cs{title} and other commands that normally go along with this. 
%    After some thought I decided to add in the code from the 
% \Lpack{titling} package~\cite{TITLING}. However, in this case life
% is a bit simpler as there is no pre-existing class code.
% \changes{v0.3}{2001/07/09}{Added titling code}
%
% \begin{macro}{\pretitle}
% \begin{macro}{\@bspretitle}
% \begin{macro}{\posttitle}
% \begin{macro}{\@bsposttitle}
% \begin{macro}{\preauthor}
% \begin{macro}{\@bspreauthor}
% \begin{macro}{\postauthor}
% \begin{macro}{\@bspostauthor}
% \begin{macro}{\predate}
% \begin{macro}{\@bspredate}
% \begin{macro}{\postdate}
% \begin{macro}{\@bspostdate}
%    To provide some flexibilty in the titling style of the document,
% user level commands are provided that can be changed to reconfigure
% the appearance resulting from \cs{maketitle}. 
%    \begin{macrocode}
\newcommand{\pretitle}[1]{\def\@bspretitle{#1}}
\newcommand{\posttitle}[1]{\def\@bsposttitle{#1}}
\newcommand{\preauthor}[1]{\def\@bspreauthor{#1}}
\newcommand{\postauthor}[1]{\def\@bspostauthor{#1}}
\newcommand{\predate}[1]{\def\@bspredate{#1}}
\newcommand{\postdate}[1]{\def\@bspostdate{#1}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% These are defined initially
% to mimic the normal \LaTeX{} style.
%    \begin{macrocode}
  \pretitle{\begin{center}\LARGE}
  \posttitle{\par\end{center}\vskip 0.5em}
  \preauthor{\begin{center}
    \large \lineskip .5em%
    \begin{tabular}[t]{c}}
  \postauthor{\end{tabular}\par\end{center}}
  \predate{\begin{center}\large}
  \postdate{\par\end{center}}

%    \end{macrocode}
%
% \begin{macro}{\maketitlehooka}
% \begin{macro}{\maketitlehookb}
% \begin{macro}{\maketitlehookc}
% \begin{macro}{\maketitlehookd}
% The four hooks which will be called by \cs{maketitle}. These are initially
% vacuous. The hooks are placed before title, before author, before
% date and after date respectively.
%    \begin{macrocode}
\newcommand{\maketitlehooka}{}
\newcommand{\maketitlehookb}{}
\newcommand{\maketitlehookc}{}
\newcommand{\maketitlehookd}{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\thanksmarkseries}
% \begin{macro}{\@bsmarkseries}
% \begin{macro}{\symbolthanksmark}
%  These are for specifying the kind of series for thanks markers.
%    \begin{macrocode}
\newcommand{\thanksmarkseries}[1]{%
  \def\@bsmarkseries{\renewcommand{\thefootnote}%
                     {\@nameuse{#1}{footnote}}}}
\newcommand{\symbolthanksmark}{\thanksmarkseries{\fnsymbol}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\continuousmarks}
% \begin{macro}{\@bscontmark}
% These are for (non) zeroing of the footnote counter.
%    \begin{macrocode}
\newcommand{\@bscontmark}{\setcounter{footnote}{0}}
\newcommand{\continuousmarks}{\def\@bscontmark{}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\thanksheadextra}
% \begin{macro}{\@bsthanksheadpre}
% \begin{macro}{\@bsthanksheadpost}
% These are for inserting stuff before and after a mark in the titling.
%    \begin{macrocode}
\newcommand{\thanksheadextra}[2]{%
  \def\@bsthanksheadpre{#1}%
  \def\@bsthanksheadpost{#2}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \changes{v1.2}{2002/08/10}{Deprecated \cs{thanksfootextra}}
% \changes{v1.2}{2002/08/10}{Removed \cs{thanksfootpre} and \cs{thanksfootpost}}
% \changes{v1.4}{2003/12/14}{Removed \cs{thanksfootextra}}
%
% \begin{macro}{\thanksmark}
% This adds a thanks mark. The \cs{footnotemark} could have been used directly
% but it is fragile in a moving argument.
%    \begin{macrocode}
\DeclareRobustCommand{\thanksmark}[1]{\footnotemark[#1]}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\thanksgap}
% This specifies some horizontal space.
%    \begin{macrocode}
\newcommand{\thanksgap}[1]{\hspace{#1}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\tamark}
% This stores the current definition of \cs{@thefnmark}. For some reason
% using \cs{@thefnmark} directly only gave the last value.
%    \begin{macrocode}
\newcommand{\tamark}{\@thefnmark}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\thanksmarkwidth}
% A length determining the size of the box for typesetting
% a thanks marker.
%    \begin{macrocode}
\newlength{\thanksmarkwidth}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\thanksmarksep}
% A length determining the inset of thanks footnotes.
% \changes{v1.2}{2002/08/10}{Replaced \cs{thanksmargin} by \cs{thanksmarksep}}
%    \begin{macrocode}
\newlength{\thanksmarksep}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\thanksmarkstyle}
% \begin{macro}{\thanksscript}
% \cs{thanksscript} is a wrapper round the actual mark stuff to be typeset. 
% The user can define this via \cs{thanksmarkstyle}\marg{code}.
% The default is a superscript mark.
% \changes{v1.2}{2002/08/10}{Added \cs{thanksmarkstyle}}
%    \begin{macrocode}
\newcommand{\thanksmarkstyle}[1]{\def\thanksscript##1{#1}}
\thanksmarkstyle{\textsuperscript{#1}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\makethanksmarkhook}
% A vacuous macro used as a hook into \cs{makethanksmark}.
%    \begin{macrocode}
\newcommand{\makethanksmarkhook}{}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\thanksfootmark}
% This typesets the thanks footnote mark.
% \changes{v1.2}{2002/08/10}{Complete rewrite of \cs{thanksfootmark}}
%    \begin{macrocode}
\newcommand{\thanksfootmark}{%
  \ifdim\thanksmarkwidth < \z@
%    \end{macrocode}
% Negative width, mark is in the margin.
%    \begin{macrocode}
    \llap{\hb@xt@ -\thanksmarkwidth{%
          \hss\normalfont\thanksscript{\tamark}}%
          \hspace*{-\thanksmarkwidth}}%
  \else
    \ifdim\thanksmarkwidth = \z@
%    \end{macrocode}
% Zero width, mark is at (inside) the margin.
%    \begin{macrocode}
      {\normalfont\thanksscript{\tamark}}%
    \else
%    \end{macrocode}
% Positive width.
%    \begin{macrocode}
      \hb@xt@\thanksmarkwidth{\hss\normalfont\thanksscript{\tamark}}%
    \fi
  \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\makethanksmark}
% This sets the general indentations for the thanks footnote, 
% and typesets the mark. The code is a simplified version of that
% for typesetting ToC entries.
% \changes{v1.2}{2002/08/10}{Minor changes to \cs{makethanksmark}}
% \changes{v1.61803398}{2009/07/17}{Added bidi support to \cs{makethanksmark}}
% \changes{v1.61803398b}{2009/09/21}{fixed typo, \cs{thanksmarksep}
% not \cs{thanksmark}}
%    \begin{macrocode}
\newcommand{\makethanksmark}{%
  \leavevmode%
  \parindent 1em\noindent
  \memRTLleftskip\thanksmarksep\relax
  \advance\memRTLleftskip\thanksmarkwidth
  \null\nobreak\hskip-\memRTLleftskip\relax
  \makethanksmarkhook\relax
  \thanksfootmark}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\usethanksrule}
% \begin{macro}{\cancelhanksrule}
%  Simple macros that let \cs{footnoterule} to another rule definition.
%    \begin{macrocode}
\newcommand{\usethanksrule}{\let\footnoterule\thanksrule}
\newcommand{\cancelthanksrule}{\let\footnoterule\@bsfootnoterule}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
%    Now set up the rest of the thanks defaults, styling having been
% done earlier.
%    \begin{macrocode}
\thanksmarkseries{fnsymbol}  % symbols
\thanksheadextra{}{}
\setlength{\thanksmarkwidth}{1.8em}
\setlength{\thanksmarksep}{-\thanksmarkwidth}

%    \end{macrocode}
% \begin{macro}{\thanksrule}
% \begin{macro}{\@bsfootnoterule}
% These are saved versions of the \cs{footnoterule} definition as it
% is at the end of the preamble.
%    \begin{macrocode}
\AtBeginDocument{%
  \let\thanksrule\footnoterule
  \let\@bsfootnoterule\footnoterule
}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\droptitle}
% A titling block has \cs{droptitle} amount of additional vertical space 
% above it (normally zero).
%    \begin{macrocode}
\newlength{\droptitle}
\setlength{\droptitle}{0pt}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\maketitle}
% The following is a
% modification of \cs{maketitle} as in the \Lpack{article}, \Lpack{report},
% and \Lpack{book} classes. It sets the pagestyle to \pstyle{title}
% and as a default sets \pstyle{title} to point to \pstyle{plain}.
% \changes{v1.4}{2004/01/21}{Removed the \cs{rlap} from \cs{@makefnmark}
%                            in \cs{maketitle} so multiple \cs{thanks}
%                            work per \cs{footnote}}
% \changes{v1.618}{2005/09/03}{Fix to remove extra blank page when
%   \cs{maketitle} (and \cs{@maketitle}) is used within adjustwidth
%    inside a titlingpage (mempatch v3.2)}
%    \begin{macrocode}
\newcommand{\maketitle}{\par
  \begingroup
    \@bsmarkseries
    \def\@makefnmark{\@textsuperscript{%
       \normalfont\@bsthanksheadpre \tamark \@bsthanksheadpost}}%
    \long\def\@makefntext##1{\makethanksmark ##1}
    \if@twocolumn
      \ifnum \col@number=\@ne
        \@maketitle
      \else
        \twocolumn[\@maketitle]%
      \fi
    \else
      \ifdim\pagetotal>\z@
        \newpage
      \fi
      \global\@topnum\z@
      \@maketitle
    \fi
    \thispagestyle{title}\@thanks
  \endgroup
  \@bscontmark  %  \setcounter{footnote}{0}%
  }
\aliaspagestyle{title}{plain}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@mem@titlefootkill}
% \cs{@mem@titlefootkill}\marg{note} Warn about footnotes in titles.
%    \begin{macrocode}
\newcommand*{\@mem@titlefootkill}[1]{%
  \@memwarn{Do not use \string\footnote\space in 
            \string\maketitle.\MessageBreak
            Use \protect\thanks\space instead}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@maketitle}
% Our version of \cs{@maketitle}.
% Footnotes are killed in the title; see the thread `\cs{title}, \cs{author}
% and \cs{footnote} feature in memoir class', February 2003.
% \changes{v1.4}{2003/11/16}{Killed footnote in titles (from patch v1.4)}
%    \begin{macrocode}
\newcommand{\@maketitle}{%               
  \let\footnote\@mem@titlefootkill
  \ifdim\pagetotal>\z@
    \newpage
  \fi
  \null
  \vskip 2em%
        \vspace*{\droptitle}
  \maketitlehooka
  {\@bspretitle \@title \@bsposttitle}
  \maketitlehookb
  {\@bspreauthor \@author \@bspostauthor}
  \maketitlehookc
  {\@bspredate \@date \@bspostdate}
  \maketitlehookd
  \par
  \vskip 1.5em}

%    \end{macrocode}
% \end{macro}
%
% \begin{environment}{mem@titlingpage}
% \begin{environment}{titlingpage}
% \begin{environment}{titlingpage*}
% \begin{macro}{\titlingpageend}
% \begin{macro}{\settitlingpagenumbering}
%   The \Lenv{titlingpage} environment sets the pagestyle to be \pstyle{titlingpage},
% disables the footnote rule and ensures that the page is single
% column. At the end it switches back to twocolumn if neccessary,
% and then starts a new page as number 1. On the other hand
% \Lenv{titlingpage*}, does \emph{not} reset the page counter.
%
% At the end of the titlingpage we clear the page to let the next data
% start on a new page. However there is a slight complication
% here. Should we clear to next page or to next righthand page. One
% could argue that under \Lopt{twoside} going to next right hand page
% would be best, but then there is also \Lopt{openany}. In order to
% make this configurable we will factor this out in a configurable
% macro, and leave the defaults as they are so not to mess with
% existing documents.
% \changes{v3.6k}{2012/12/24}{Added \Lenv{titlingpage*} env}
% \changes{v3.7g}{2018/03/06}{Added \cs{titlingpageend}}
%    \begin{macrocode}
\NewDocumentCommand\settitlingpagenumbering{m}
{ \def\mem@titlingpage@numbering{#1} }
\settitlingpagenumbering\arabic

\newcommand\titlingpageend[2]{%
  \def\mem@titlingpage@clear@for@twoside{#1}%
  \def\mem@titlingpage@clear@for@oneside{#2}%
}
 % default
\titlingpageend{\cleardoublepage}{\clearpage}
\newenvironment{mem@titlingpage}%
  {\let\footnoterule\relax
    \let\footnotesize\small
    \def\thepage{\mem@titlingpage@numbering{page}}
   \if@twocolumn
     \@restonecoltrue\onecolumn
   \else
     \@restonecolfalse
   \fi
   \thispagestyle{titlingpage}%
   \if\mem@titlpg@reset\setcounter{page}{\@ne}\fi%
  }{%
   \thispagestyle{titlingpage}%
   \if@restonecol \twocolumn \fi
   % \if@twoside \cleardoublepage \else \clearpage \fi
   \if@twoside \mem@titlingpage@clear@for@twoside \else \mem@titlingpage@clear@for@oneside \fi
   \if\mem@titlpg@reset\setcounter{page}{\@ne}\fi}
\newenvironment{titlingpage}{%
  \def\mem@titlpg@reset{00}%
  \begin{mem@titlingpage}}{%
  \end{mem@titlingpage}}
\newenvironment{titlingpage*}{%
  \def\mem@titlpg@reset{01}%
  \begin{mem@titlingpage}}{%
  \end{mem@titlingpage}}
\aliaspagestyle{titlingpage}{empty}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{environment}
% \end{environment}
% \end{environment}
%
% \begin{macro}{\emptythanks}
% This macro discards all prior \cs{thanks} texts.
%    \begin{macrocode}
\newcommand{\emptythanks}{\global\let\@thanks\@empty}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\andnext}
%  The kernel \cs{and} macro puts space between author's names. The
% \cs{andnext} macro puts a newline between the names.
% \changes{v1.6}{2004/01/28}{Added \cs{andnext}}
%    \begin{macrocode}
\newcommand*{\andnext}{%
  \end{tabular}\\ \begin{tabular}[t]{c}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@bsmtitlempty}
%    \cs{@bsmtitlempty} is a helper macro to save some macro space. 
% It empties some elements of \cs{maketitle}.
% \changes{v3.6k}{2012/07/01}{Removed \cs{thanksfootextra}, seems to
% have been forgotten back in 2003.}
%    \begin{macrocode}
\newcommand{\@bsmtitlempty}{%
  \global\let\maketitle\relax
  \global\let\@maketitle\relax
  \global\let\title\relax
  \global\let\author\relax
  \global\let\date\relax
  \global\let\thanksmarkseries\relax
  \global\let\thanksfootextra\relax
  \global\let\thanksmark\relax
  \global\let\thanksgap\relax}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\keepthetitle}
% This macro undefines all the titling commands except for
% \cs{thetitle}, \cs{theauthor} and \cs{thedate}.
% \changes{v1.6}{2004/01/28}{changed \cs{keepthetitle} to cater for \cs{andnext}}
%    \begin{macrocode}
\newcommand{\keepthetitle}{%
  \@bsmtitlempty
  \global\let\thanks\relax
  \global\let\and\relax
  \global\let\andnext\relax
  \global\let\@thanks\@empty
  \global\let\@title\@empty
  \global\let\@author\@empty
  \global\let\@date\@empty}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\killtitle}
% \cs{killtitle} undefines the remaining macros of \cs{maketitle}.
%    \begin{macrocode}
\newcommand{\killtitle}{%
  \keepthetitle
  \global\let\thetitle\relax
  \global\let\theauthor\relax
  \global\let\thedate\relax}

%    \end{macrocode}
% \end{macro}
%
% 
% \begin{macro}{\thetitle}
% \begin{macro}{\theauthor}
% \begin{macro}{\thedate}
%    In order to make the \cs{title}, etc., values available for printing
% their definitions (in \file{ltsect.dtx}) need extending to save their 
% arguments. We have to make sure that extraneous material,
% like \cs{thanks}, is excluded from the saved texts.
% \changes{v1.4}{2003/11/16}{Gobble footnotes in \cs{title}, \cs{author}
%               and \cs{date} (from patch v1.4)}
% \changes{v1.6}{2004/01/28}{Added \cs{andnext} handling to \cs{author}}
% \changes{v3.8.3}{2024/02/02}{The changes to \cs{title}, \cs{author} and \cs{date} now moved to be done via \Lpack{xpatch}. }
%    \begin{macrocode}
 % \addtoiargdef{\title}{%
 %   \begingroup\let\footnote\@gobble}{%
 %   \begingroup
 %     \renewcommand{\thanks}[1]{}
 %     \renewcommand{\thanksmark}[1]{}
 %     \renewcommand{\thanksgap}[1]{}
 %     \protected@xdef\thetitle{#1}
 %     \endgroup\endgroup}

\xpretocmd\title{\begingroup\let\footnote\@gobble}{}{\typeout{patch 1 to \string\title\space failed, please inform maintainer}}
\xapptocmd\title{
  \begingroup%
    \renewcommand{\thanks}[1]{}%
     \renewcommand{\thanksmark}[1]{}%
     \renewcommand{\thanksgap}[1]{}%
     \protected@xdef\thetitle{#1}%
   \endgroup\endgroup%
}{}{\typeout{patch 2 to \string\title\space failed, please inform maintainer}}
 
 % \addtoiargdef{\author}{%
 %   \begingroup\let\footnote\@gobble}{%
 %   \begingroup
 %     \renewcommand{\thanks}[1]{}
 %     \renewcommand{\and}{\unskip, }
 %     \renewcommand{\andnext}{\unskip, }
 %     \renewcommand{\thanksmark}[1]{}
 %     \renewcommand{\thanksgap}[1]{}
 %     \protected@xdef\theauthor{#1}
 %   \endgroup\endgroup}

\xpretocmd\author{\begingroup\let\footnote\@gobble}{}{\typeout{patch 1 to \string\author\space failed, please inform maintainer}}
\xapptocmd\author{%
   \begingroup%
     \renewcommand{\thanks}[1]{}%
     \renewcommand{\and}{\unskip, }%
     \renewcommand{\andnext}{\unskip, }%
     \renewcommand{\thanksmark}[1]{}%
     \renewcommand{\thanksgap}[1]{}%
     \protected@xdef\theauthor{#1}%
   \endgroup\endgroup%
}{}{\typeout{patch 1 to \string\author\space failed, please inform maintainer}}

 % \addtoiargdef{\date}{%
 %   \begingroup\let\footnote\@gobble}{%
 %   \begingroup
 %     \renewcommand{\thanks}[1]{}
 %     \renewcommand{\thanksmark}[1]{}
 %     \renewcommand{\thanksgap}[1]{}
 %     \protected@xdef\thedate{#1}
 %   \endgroup\endgroup}

\xpretocmd\date{\begingroup\let\footnote\@gobble}{}{\typeout{patch 1 to \string\date\space failed, please inform maintainer}}
\xapptocmd\date{%
  \begingroup%
    \renewcommand{\thanks}[1]{}%
    \renewcommand{\thanksmark}[1]{}%
    \renewcommand{\thanksgap}[1]{}%
    \protected@xdef\thedate{#1}%
  \endgroup\endgroup%
}{}{\typeout{patch 2 to \string\date\space failed, please inform maintainer}}
 
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% 
% \section{Parts, chapters and other divisions}
%
% \subsection{Building blocks} The definitions in this part of a
%    class file usually make use of two internal macros, \cs{@startsection} and
%    \cs{secdef}. To understand
%    what is going on here, we describe their syntax.
%
% \DescribeMacro{\@startsection}
%    The macro \cs{@startsection} has 6 required arguments, optionally
%    followed by  a $*$, an optional argument and a required argument:
%
%    \cs{@startsection}\meta{name}\meta{level}\meta{indent}^^A
%                    \meta{beforeskip}\meta{afterskip}\meta{style}
%            optional * %\\
%    \null\hphantom{\bslash @startsection}^^A
%            \oarg{altheading}\meta{heading}
%
%    It is a generic command to start a section, the arguments have
%    the following meaning:
%
%    \begin{description}
%    \item[\meta{name}] The name of the user level command, e.g.,
%          `section'.
%    \item[\meta{level}] A number, denoting the depth of the section
%          --- e.g., chapter = 0, section = 1, etc.  A section number
%          will be printed if and only if \meta{level} $<=$  the value
%          of the \Lcount{secnumdepth} counter.
%    \item[\meta{indent}] The indentation of the heading from the left
%          margin
%    \item[\meta{beforeskip}] The absolute value of this argument
%          gives the skip to leave above the heading. If it is
%          negative, then the paragraph indent of the text following
%          the heading is suppressed.
%    \item[\meta{afterskip}] If positive, this gives the skip to leave
%          below the heading, else it gives the skip to leave to the
%          right of a run-in heading.
%    \item[\meta{style}] Commands to set the style of the heading.
%    \item[$*$] When this is missing the heading is numbered and the
%          corresponding counter is incremented.
%    \item[\meta{altheading}] Gives an alternative heading to use in
%          the table of contents and in the running heads. This should
%          be present when the $*$ form is used.
%    \item[\meta{heading}] The heading of the new section.
%    \end{description}
%  A sectioning command is normally defined to \cs{@startsection} and
%  its first six arguments.
%
% \DescribeMacro{\secdef}
%    The macro \cs{secdef} can be used when a sectioning command is
%    defined without using \cs{@startsection}. It has two arguments:
%
%    \cs{secdef}\meta{unstarcmds}\meta{starcmds}
%
%    \begin{description}
%    \item[\meta{unstarcmds}] Used for the normal form of a
%          sectioning command.
%    \item[\meta{starcmds}] Used for the $*$-form of a
%          sectioning command.
%    \end{description}
%
%    You can use \cs{secdef} as follows:
% \begin{verbatim}
%       \def\chapter { ... \secdef \CMDA \CMDB }
%       \def\CMDA    [#1]#2{ ... }  % Command to define
%                                   % \chapter[...]{...}
%       \def\CMDB    #1{ ... }      % Command to define
%                                   % \chapter*{...}
% \end{verbatim}
%
% \DescribeMacro{\@hangfrom}
% Internally the \cs{@startsection} macro uses \verb?\@hangfrom{NUM}?, where
% \verb?NUM? is the sectional number, to produce a hanging paragraph. That is,
% the second and later lines of a multiline title are indented from the
% left margin by the width of the number.
% The definition of \cs{@hangfrom}, from \file{ltsect.dtx}, is:
% \begin{verbatim}
% \def\@hangfrom#1{\setbox\@tempboxa\hbox{{#1}}%
%   \hangindent \wd\@tempboxa\noindent\box\@tempboxa}
% \end{verbatim}
%
% To get a normal paragraphed title you can do: \\
% \verb?\renewcommand{\@hangfrom}[1]{#1}? \\
% or as a block paragraph: \\
% \verb?\renewcommand{\@hangfrom}[1]{\noindent #1}? \\
%
% \DescribeMacro{\@seccntformat}
% The \cs{@startsection} macro also uses \verb?\@seccntformat{NUM}? to format
% the section number, including the space after it. Its definition,
% from \file{ltsect.dtx}, is
% \begin{verbatim}
% \def\@seccntformat#1{\csname the#1\endcsname\quad}
% \end{verbatim}
% This is the command to change if you need different number formatting. For
% example the combination
% \begin{verbatim}
% \renewcommand{\@seccntformat}[1]{\llap{\csname the#1\endcsname\quad}}
% \renewcommand{\@hangfrom}[1]{\noindent #1}
% \end{verbatim}
% will hang the section numbers in the margin.
%
% \begin{table}
% \centering
% \caption{Document division levels}\label{tab:levels}
% \medskip
% \begin{tabular}{lr} \hline
% Division & Level \\ \hline
% book          & -2 \\
% part          & -1 \\
% chapter       &  0 \\
% section       &  1 \\
% subsection    &  2 \\
% subsubsection &  3 \\
% paragraph     &  4 \\
% subparagraph  &  5 \\ 
% \hline
% \end{tabular}
% \end{table}
%
%     The values used for the document division levels are the same
% as defined by the standard \LaTeX{} classes, with the exception
% of the book division which is a memoir addition, and are given in 
% Table~\ref{tab:levels}.
% \changes{v1.61803}{2008/01/30}{Added book division (from mempatch v4.4)}
% \subsection{Mark commands}
%
% \begin{macro}{\bookpagemark}
% \begin{macro}{\partmark}
% \begin{macro}{\chaptermark}
% \begin{macro}{\sectionmark}
% \begin{macro}{\subsectionmark}
% \begin{macro}{\subsubsectionmark}
% \begin{macro}{\paragraphmark}
% \begin{macro}{\subparagraphmark}
%   The default initialisations of the \cs{...mark} commands for use
%   in the pagestyles. Most are already defined in the kernel but they
%   are all noted here. In the rare occasion that there are text
%   between, say, a \cs{part} and a \cs{chapter}, the header from the
%   previous chapter may spill into this text. Therefore two marks
%   \cs{bookpagemark} and \cs{partmark} should default to resettting
%   the marks.
% \changes{3.8.3}{2025/02/25}{Changed the default for \cs{partmark} and \cs{bookpagemark}}
%    \begin{macrocode}
\newcommand*{\bookpagemark}[1]{\markboth{}{}}
\newcommand*{\partmark}[1]{\markboth{}{}}
\newcommand*{\chaptermark}[1]{}
% \newcommand*{\sectionmark}[1]{}
% \newcommand*{\subsectionmark}[1]{}
% \newcommand*{\subsubsectionmark}[1]{}
% \newcommand*{\paragraphmark}[1]{}
% \newcommand*{\subparagraphmark}[1]{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\bibmark}
%  Marks for the bibliography, which may be filled with \cs{bibname}.
% \changes{v1.1}{2002/03/10}{Added \cs{bibmark}}
%    \begin{macrocode}
\newcommand*{\bibmark}{}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\indexmark}
% Marks for the index, which may be filled with \cs{indexname}.
% \changes{v1.1}{2002/03/10}{Added \cs{indexmark}}
%    \begin{macrocode}
\newcommand*{\indexmark}{}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\glossarymark}
% Marks for the glossary, which may be filled with \cs{glossaryname}.
% \changes{v1.618}{2005/09/25}{Added \cs{glossarymark}}
%    \begin{macrocode}
\newcommand*{\glossarymark}{}

%    \end{macrocode}
% \end{macro}
%
%
% \subsection{Define Counters}
%
% \begin{macro}{\c@secnumdepth}
%    The value of the counter \Lcount{secnumdepth} gives the depth of
%    the highest-level sectioning command that is to produce section
%    numbers.
%    \begin{macrocode}
\setcounter{secnumdepth}{2}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\c@book}
% \begin{macro}{\c@part}
% \begin{macro}{\c@chapter}
% \begin{macro}{\c@section}
% \begin{macro}{\c@subsection}
% \begin{macro}{\c@subsubsection}
% \begin{macro}{\c@paragraph}
% \begin{macro}{\c@subparagraph}
%    These counters are used for the sectioning numbers. The macro\\
%    \cs{newcounter}\marg{newctr}\oarg{oldctr}\\
%     defines\meta{newctr} to be a counter, which is reset to zero when
%    counter \meta{oldctr} is stepped. Counter \meta{oldctr} must
%    already be defined.
%
%    Book, part and chapter are the top level document divisions.
%    \begin{macrocode}
\newcounter{book}    \setcounter{book}{0}
\newcounter{part}    \setcounter{part}{0}
\newcounter{chapter} \setcounter{chapter}{0}
%    \end{macrocode}
%    The lower level divisions get reset by higher level divisions.
%    \begin{macrocode}
\newcounter{section}[chapter]
\newcounter{subsection}[section]
\newcounter{subsubsection}[subsection]
\newcounter{paragraph}[subsubsection]
\newcounter{subparagraph}[paragraph]
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\thebook}
% \begin{macro}{\thepart}
% \begin{macro}{\thechapter}
% \begin{macro}{\thesection}
% \begin{macro}{\thesubsection}
% \begin{macro}{\thesubsubsection}
% \begin{macro}{\theparagraph}
% \begin{macro}{\thesubparagraph}
%    For any counter \Lcount{CTR}, \cs{theCTR} is a macro that defines
%    the printed version of counter \Lcount{CTR}.  It is defined in
%    terms of the following macros:
%
%    \cs{arabic}\marg{COUNTER} prints the value of
%    \meta{COUNTER} as an arabic numeral.
%
%    \cs{roman}\marg{COUNTER} prints the value of
%    \meta{COUNTER} as a lowercase roman numeral.
%
%    \cs{Roman}\marg{COUNTER} prints the value of
%    \meta{COUNTER} as an uppercase roman numeral.
%
%    \cs{alph}\marg{COUNTER} prints the value of \meta{COUNTER}
%    as a lowercase letter: $1 =$~a, $2 =$~ b, etc.
%
%    \cs{Alph}\marg{COUNTER} prints the value of \meta{COUNTER}
%    as an uppercase letter: $1 =$~A, $2 =$~B, etc.
%
%    \begin{macrocode}
\renewcommand*{\thebook}{\@Roman\c@book}
\renewcommand*{\thepart}{\@Roman\c@part}
\renewcommand*{\thechapter}{\@arabic\c@chapter}
\renewcommand*{\thesection}{\thechapter.\@arabic\c@section}
\renewcommand*{\thesubsection}{%
              \thesection.\@arabic\c@subsection}
\renewcommand*{\thesubsubsection}{%
              \thesubsection.\@arabic\c@subsubsection}
\renewcommand*{\theparagraph}{%
              \thesubsubsection.\@arabic\c@paragraph}
\renewcommand*{\thesubparagraph}{%
              \theparagraph.\@arabic\c@subparagraph}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@chapapp}
% \cs{@chapapp} is initially defined as \cs{chaptername}. The \cs{appendix}
% command redfines it as \cs{appendixname}.
%    \begin{macrocode}
\newcommand{\@chapapp}{\chaptername}

%    \end{macrocode}
% \end{macro}
%
% \subsection{Front, main and back matter}
%
% These are the three main logical divisions in a book. As noted earlier,
% the boolean \cs{if@mainmatter} is TRUE iff the main matter is being
% processed. Chapters will be unnumbered when \cs{if@mainmatter} is FALSE.
%
% \begin{macro}{\frontmatter}
% \begin{macro}{\frontmatter*}
%   The \cs{frontmatter} command starts roman numbering and turns off
%   chapter numbering.  It ensures that lower level divisions will not
%   have chapter numbers, nor will figures or tables. It also ensures
%   that the next page will be recto.  The starred version makes no
%   changes to the page numbering\footnote{The starred versions were
%   added to meet a request by Daniel Richard G.  in September 2001.}.
% \changes{v0.3}{2001/07/09}{\cs{frontmatter} switches off numbering via
%                the secnumdepth counter}
% \changes{v1.0}{2001/09/21}{Added \cs{frontmatter*} command}
%    \begin{macrocode}
\newcommand{\frontmatter}{%
  \@ifstar{\@smemfront}{\@memfront}}
%    \end{macrocode}
% \begin{macro}{\@memfront@floats}
% \changes{v1.6180339f}{Added \cs{@memfront@floats}}
%   Factoring out the float counter domination, in case someone wants
%   something added or changed
%    \begin{macrocode}
\newcommand\@memfront@floats{%
  \counterwithout{figure}{chapter}
  \counterwithout{table}{chapter}
}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\@smemfront}
%    \begin{macrocode}
\newcommand{\@smemfront}{%
  \cleardoublepage
  \@mainmatterfalse
  \setcounter{secnumdepth}{-10}
  \@memfront@floats
}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\@memfront}
%    \begin{macrocode}
\newcommand{\@memfront}{%
  \@smemfront\pagenumbering{roman}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\mainmatter}
% \begin{macro}{\mainmatter*}
% The \cs{mainmatter} command starts arabic numbering and turns on chapter numbering.
% It sets numbering to the normal state. It
% also ensures that the next page will be recto. The starred version does 
% not change the page numbering.
%
% Romano Giannetti suggested that \cs{mainmatter} (and \cs{backmatter}) should
% be almost no-ops with the article option.
% \changes{v0.3}{2001/07/09}{\cs{mainmatter} switches on section numbering
%                via the secnumdepth counter}
% \changes{v1.0}{2001/09/21}{Added \cs{mainmatter*} command}
%    \begin{macrocode}
\newcommand{\mainmatter}{%
  \@ifstar{\@smemmain}{\@memmain}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@memmain@floats}
% \changes{v1.6180339f}{}{Added \cs{@memmain@floats}}
%   Factoring out the float counter domination, in case someone wants
%   something added or changed
%    \begin{macrocode}
\newcommand\@memmain@floats{%
   \counterwithin{figure}{chapter}
   \counterwithin{table}{chapter}
}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\@smemmain}
% If \cs{frontmatter} and \cs{mainmatter} are used with the article option,
% then a page numbering / margin problem can occur if the frontmatter ends
% on an odd page --- the first mainmatter next page is odd as well which throws
% puts two odd-margined pages together.
%
% One fix from Morten is to always \cs{cleardoublepage} for twosided articles.
%
% One fix from me is for the ...matter macros to just switch on/off section
% numbering.
%
% Morten's is simpler to implement.
%
% \changes{v1.1}{2002/03/10}{Modified \cs{@smemmain} to reset the secnumdepth
%                counter to maxsecnumdepth}
% \changes{v1.4}{2003/11/22}{Included cognizance of article option in \cs{@smemmain}
%                            (from patch v1.7)}
% \changes{v1.61803}{2008/01/30}{Changed timing of \cs{clear[double]page} in
%     \cs{@smemmain} (David Wilson, mempatch v4.5)}
% \changes{v1.61803}{2008/01/30}{Changed clear pages in \cs{@smemmain}
%                              (mempatch v4.9)}
%    \begin{macrocode}
\newcommand*{\@smemmain}{%
  \@mainmattertrue
  \setcounter{secnumdepth}{\value{maxsecnumdepth}}
  \ifartopt
    \if@twoside
      \cleardoublepage
    \else
      \clearpage
    \fi
  \else
    \cleardoublepage
    \@memmain@floats
  \fi}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@memmain}
%    \begin{macrocode}
\newcommand{\@memmain}{%
  \@smemmain\pagenumbering{arabic}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@memback@floats}
% \changes{v1.6180339f}{Added \cs{@memback@floats}}
%   Factoring out the float counter domination, in case someone wants
%   something added or changed
%    \begin{macrocode}
\newcommand\@memback@floats{%
    \counterwithout{figure}{chapter}
    \counterwithout{table}{chapter}
    \setcounter{figure}{0}
    \setcounter{table}{0}
}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\backmatter}
% This command turns off chapter numbering but leaves the page numbering alone. 
% It twiddles the numbering caption numbering.
% The back matter may start on any new page.
% \changes{v0.3}{2001/07/09}{\cs{backmatter} uses the secnumdepth counter}
% \changes{v1.4}{2003/11/22}{Included cognizance of article option in \cs{backmatter}
%                            (from patch v1.7)}
%    \begin{macrocode}
\newcommand{\backmatter}{%
  \ifartopt
    \clearpage
  \else
    \if@openright
      \cleardoublepage
    \else
      \clearpage
    \fi
  \fi
  \@mainmatterfalse
  \setcounter{secnumdepth}{-10}
  \ifartopt\else
    \@memback@floats
  \fi}

%    \end{macrocode}
% \end{macro}
%
%
% \subsection{Book}
%
% This was added at the request of Frederic Connes who said that in
% French typography there was often a division above the \cs{part} level.
%
% \begin{macro}{\theHbook}
% \begin{macro}{\toclevel@book}
% These are needed if the \Lpack{hyperref} is used.
% \changes{v3.7.19}{2022/10/25}{Changing \cs{theH...} definitions to
% \cs{def} for better compability with future hyperref}
% \changes{v3.8}{2023/06/20}{Changed \cs{theHbook} to use
% \cs{the}\cs{value\{counter\}} as packages can mess up \cs{arabic}
% advise from Ulrike}
%    \begin{macrocode}
\def\theHbook{\the\value{book}}
\def\toclevel@book{-2}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\book}
% \begin{macro}{\book*}
% \cs{book}\marg{title} starts a new book division called \meta{title}.
% The actual typesetting of the title is done by \cs{@book} or \cs{@sbook}.
% \changes{v1.61803}{2008/01/30}{Added \cs{book} and its entourage (mempatch v4.4)}
%    \begin{macrocode}
\newcommand*{\book}{%
  \@setupbook
  \secdef\@book\@sbook}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\beforebookskip}
% \begin{macro}{\midbookskip}
% \begin{macro}{\afterbookskip}
% These three macros are the skips before, in the middle, and after the
% Book heading.
%    \begin{macrocode}
\newcommand*{\beforebookskip}{\null\vfil}
\newcommand*{\midbookskip}{\par\vskip 2\onelineskip}
\newcommand*{\afterbookskip}{\vfil\newpage}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@setupbook}
% This macro does the work of setting up for the \cs{book} command.
% A single column page, normally recto, with a \pstyle{book} pagestyle is 
% started.
%    \begin{macrocode}
\newcommand{\@setupbook}{%
  \if@openright
    \cleardoublepage
  \else
    \clearpage
  \fi
  \thispagestyle{book}%
  \if@twocolumn
    \onecolumn
    \@tempswatrue
  \else
    \@tempswafalse
  \fi
  \beforebookskip}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\booknamefont}
% \begin{macro}{\booknumfont}
% \begin{macro}{\booktitlefont}
% These three macros specify the fonts for the book name and number, and
% for the book title, respectively.
%    \begin{macrocode}
\newcommand*{\booknamefont}{\normalfont\huge\bfseries}
\newcommand*{\booknumfont}{\normalfont\huge\bfseries}
\newcommand*{\booktitlefont}{\normalfont\Huge\bfseries}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\printbookname}
% \begin{macro}{\booknamenum}
% \begin{macro}{\printbooknum}
% \begin{macro}{\printbooktitle}
% Macros to print the various books of a Book heading.
%    \begin{macrocode}
\newcommand*{\printbookname}{\booknamefont \bookname}
\newcommand*{\booknamenum}{\space}
\newcommand*{\printbooknum}{\booknumfont \thebook}
\newcommand*{\printbooktitle}[1]{\booktitlefont #1}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\membookinfo}
% \begin{macro}{\membookstarinfo}
%   Hooks. Arguments given for \cs{membookinfo} will be \cs{thebook}
%   (unless secnumdepth), the data for the toc and the title. The
%   argument for \cs{membookstarinfo} (starred version) will just be
%   the title.
%    \begin{macrocode}
\newcommand{\membookinfo}[3]{}
\newcommand{\membookstarinfo}[1]{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\@book}
% \cs{@book}\oarg{short}\marg{long} typesets the title of a \cs{book}
% book. There is a number if \cs{secnumdepth} is greater than -3.
%    \begin{macrocode}
\long\def\@book[#1]#2{%
  \M@gettitle{#1}%
%    \end{macrocode}
% For continuity we store the toc entry in \verb?\f@rtoc? before
% writing it to the \verb?.toc? file. We also provide a hook to be
% able to transform it.
% \changes{v3.6k}{2012/09/18}{Provided \cs{f@rtoc} and hook}
% \changes{v3.6k}{2013/04/24}{Added \cs{mempreaddbooktotochook} and \cs{mempostaddbooktotochook}}
% \changes{v3.8.4}{2025/09/16}{Replacedd \cs{phantomsection} with \cs{MakeLinkTarget} and moved it to unnumbered branch}
%    \begin{macrocode}
  \def\f@rtoc{#1}%
  \@nameuse{book@f@rtoc@before@write@hook}%
  % \phantomsection
  \mempreaddbooktotochook
  \ifnum \c@secnumdepth >-3\relax
    \refstepcounter{book}%
    \addcontentsline{toc}{book}%
      {\protect\booknumberline{\thebook}\f@rtoc}%
    \membookinfo{\thebook}{\f@rtoc}{#2}%
  \else
    \MakeLinkTarget[book]{}%
    \addcontentsline{toc}{book}{\f@rtoc}%
    \membookinfo{}{\f@rtoc}{#2}%
  \fi
  \mempostaddbooktotochook
%    \end{macrocode}
% Empty the marks, center the title on the page, and set the normal font.
% \changes{v3.6j}{2011/03/03}{Set \cs{parskip} to zero, such that a
% non-zero \cs{parskip} does not interfer with the title layout}
%    \begin{macrocode}
  \bookpagemark{#1}%
  {\centering
   \interlinepenalty \@M
   \parskip\z@
   \normalfont
%    \end{macrocode}
% Print the number, if there is one, then the title below. Macro \cs{@endbook}
% tidies everything up at the end.
%    \begin{macrocode}
   \ifnum \c@secnumdepth >-3\relax
     \printbookname \booknamenum \printbooknum
     \midbookskip
   \fi
   \printbooktitle{#2}\par}%
  \@endbook}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\mempreaddbooktotochook}
% \begin{macro}{\mempostaddbooktotochook}
% Hooks executed just before and just after \cs{book} adds something
% to the ToC. Does nothing by default
%    \begin{macrocode}
\newcommand\mempreaddbooktotochook{}
\newcommand\mempostaddbooktotochook{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@sbook}
% \cs{@sbook}\marg{long} formats the title of a \cs{book*} book. It is 
% simpler than \cs{@book} because there is no  number to print.
% \changes{v1.4}{2003/11/16}{Added \cs{M@gettitle} to \cs{@sbook}}
% \changes{v3.6j}{2011/03/03}{Set \cs{parskip} to zero here as well}
% \changes{v3.8.4}{2025/09/16}{Replaced \cs{phantomsection} by \cs{MakeLinkTarget}}
%    \begin{macrocode}
\long\def\@sbook#1{%
  \M@gettitle{#1}%
  % \phantomsection
  \MakeLinkTarget[book]{}%
  \membookstarinfo{#1}%
  {\centering
   \interlinepenalty \@M
   \parskip\z@
   \normalfont
   \printbooktitle{#1}\par}%
  \@endbook}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ifm@mnobooknewpage}
% \begin{macro}{\m@mnobooknewpagetrue}
% \begin{macro}{\m@mnobooknewpagefalse}
% \begin{macro}{\bookblankpage}
% \begin{macro}{\nobookblankpage}
%    The declaration \cs{nobookblankpage} prevents \cs{book} from
% outputting a further (blank) page when it finishes. The default is set by
% \cs{bookblankpage}. 
%    \begin{macrocode}
\newif\ifm@mnobooknewpage
  \m@mnobooknewpagefalse
\newcommand*{\bookblankpage}{\m@mnobooknewpagefalse}
\newcommand*{\nobookblankpage}{\m@mnobooknewpagetrue}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% 
% \begin{macro}{\bookpageend}
% \begin{macro}{\@endbook}
% This finishes off both \cs{@book} and \cs{@sbook}. 
% Following a \cs{nobookblankpage} nothing is done, otherwise
% (after \cs{bookblankpage}) the current page is flushed,
% and an extra blank page is created if both \Lopt{twoside} and 
% \Lopt{openright} are in effect. 
% At the end, if necessary, two column mode is switched back on.
% \changes{v1.61803398}{2009/07/26}{PW: Added \cs{bookpageend} as cover for \cs{@endbook}}
%    \begin{macrocode}
\newcommand*{\bookpageend}{\afterbookskip
  \ifm@mnobooknewpage
  \else
    \if@twoside
      \if@openright
        \null
        \thispagestyle{afterbook}%
        \newpage
      \fi
    \fi
  \fi
  \if@tempswa
    \twocolumn
  \fi}
\def\@endbook{\bookpageend}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\ps@book}
% \begin{macro}{\ps@afterbook}
% Pagestyles for the book page and the (blank) page after a book page.
%    \begin{macrocode}
\aliaspagestyle{book}{empty}
\aliaspagestyle{afterbook}{empty}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \subsection{Part}
%
% \begin{macro}{\part}
% \cs{part}\marg{title} starts a new Part called \meta{title}.
% The actual typesetting of the title is done by \cs{@part} or \cs{@spart}.
%    \begin{macrocode}
\newcommand{\part}{%
  \@setuppart
  \secdef\@part\@spart}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\beforepartskip}
% \begin{macro}{\midpartskip}
% \begin{macro}{\afterpartskip}
% These three macros are the skips before, in the middle, and after the
% Part heading.
% \changes{v1.61803}{2008/01/30}{Changed \cs{midpartskip} (mempatch v4.9)}
%    \begin{macrocode}
\newcommand{\beforepartskip}{\null\vfil}
\newcommand{\midpartskip}{\par\vskip 2\onelineskip}
\newcommand{\afterpartskip}{\vfil\newpage}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@setuppart}
% This macro does the work of setting up for the \cs{part} command.
% A single column page, normally recto, with a \pstyle{part} pagestyle is started.
%    \begin{macrocode}
\newcommand{\@setuppart}{%
  \if@openright
    \cleardoublepage
  \else
    \clearpage
  \fi
  \thispagestyle{part}%
  \if@twocolumn
    \onecolumn
    \@tempswatrue
  \else
    \@tempswafalse
  \fi
  \beforepartskip}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\partnamefont}
% \begin{macro}{\partnumfont}
% \begin{macro}{\parttitlefont}
% These three macros specify the fonts for the part name and number, and
% for the part title, respectively.
% \changes{v0.2}{2001/06/03}{Rewrote the typesetting for Part titles}
%    \begin{macrocode}
\newcommand{\partnamefont}{\normalfont\huge\bfseries}
\newcommand{\partnumfont}{\normalfont\huge\bfseries}
\newcommand{\parttitlefont}{\normalfont\Huge\bfseries}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\printpartname}
% \begin{macro}{\partnamenum}
% \begin{macro}{\printpartnum}
% \begin{macro}{\printparttitle}
% Macros to print the various parts of a Part heading.
%    \begin{macrocode}
\newcommand{\printpartname}{\partnamefont \partname}
\newcommand{\partnamenum}{\space}
\newcommand{\printpartnum}{\partnumfont \thepart}
\newcommand{\printparttitle}[1]{\parttitlefont #1}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\mempartinfo}
% \begin{macro}{\mempartstarinfo}
% Hooks for the part data. Arguments as listed. Though first arg for
% \cs{mempartinfo} might be empty if secnumdepth say so.
%
% \medskip\noindent
% \verb?\mempartinfo{\thepart}{short}{long}? \\
% \verb?\mempartstarinfo{long}? \\
% \changes{v1.61803}{2008/01/30}{Made \cs{mempartinfo} long (mempatch v4.9).}
%    \begin{macrocode}
\newcommand{\mempartinfo}[3]{}
\newcommand{\mempartstarinfo}[1]{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@part}
% \cs{@part}\oarg{short}\marg{long} typesets the title of a \cs{part}
% part. There is a number if \cs{secnumdepth} is greater than -2.
% \changes{v1.3}{2002/11/14}{Used \cs{partnumberline} in \cs{@part}}
% \changes{v1.4}{2003/11/16}{Added \cs{M@gettitle} to \cs{@part}}
% \changes{v1.618}{2005/09/03}{Replaced \cs{markboth} by \cs{partmark} 
%          in \cs{@part} courtesy of Frederic Connes (mempatch v3.11)}
%    \begin{macrocode}
\long\def\@part[#1]#2{%
  \M@gettitle{#1}%
%    \end{macrocode}
% For continuity we store the toc entry in \verb?\f@rtoc? before
% writing it to the \verb?.toc? file. We also provide a hook to be
% able to transform it.
% \changes{v3.6k}{2012/09/18}{Provided \cs{f@rtoc} and hook}
% \changes{v3.6k}{2013/04/24}{Added \cs{mempreaddparttotochook} and \cs{mempostaddparttotochook}}
% \changes{v3.8.4}{2025/09/16}{Replaced \cs{phansomsection} by \cs{MakeLinkTarget} and moved it to unnumbered branch}
%    \begin{macrocode}
  \def\f@rtoc{#1}%
  \@nameuse{part@f@rtoc@before@write@hook}%
  %\phantomsection
  \mempreaddparttotochook
  \ifnum \c@secnumdepth >-2\relax
    \refstepcounter{part}%
    \addcontentsline{toc}{part}%
      {\protect\partnumberline{\thepart}\f@rtoc}%
    \mempartinfo{\thepart}{\f@rtoc}{#2}%
  \else
    \MakeLinkTarget[part]{}%
    \addcontentsline{toc}{part}{\f@rtoc}%
    \mempartinfo{}{\f@rtoc}{#2}%
  \fi
  \mempostaddparttotochook
%    \end{macrocode}
% Empty the marks, center the title on the page, and set the normal font.
% \changes{v3.6j}{2011/03/03}{Set \cs{parskip} to zero inside the
% group, such that a non-zero \cs{parskip} does not interfer with the
% title layout}
%    \begin{macrocode}
  \partmark{#1}%
  {\centering
   \interlinepenalty \@M
   \parskip\z@
   \normalfont
%    \end{macrocode}
% Print the number, if there is one, then the title below. Macro \cs{@endpart}
% tidies everything up at the end.
%    \begin{macrocode}
   \ifnum \c@secnumdepth >-2\relax
     \printpartname \partnamenum \printpartnum
     \midpartskip
   \fi
   \printparttitle{#2}\par}%
  \@endpart}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\mempreaddparttotochook}
% \begin{macro}{\mempostaddparttotochook}
% Hooks executed just before and just after \cs{part} adds something
% to the ToC. Does nothing by default
%    \begin{macrocode}
\newcommand\mempreaddparttotochook{}
\newcommand\mempostaddparttotochook{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@spart}
% \cs{@spart}\marg{long} formats the title of a \cs{part*} part. It is 
% simpler than \cs{@part} because there is no  number to print.
% \changes{v1.4}{2003/11/16}{Added \cs{M@gettitle} to \cs{@spart}}
% \changes{v3.6j}{2011/03/03}{Set \cs{parskip} to zero here as well}
% \changes{v3.8.4}{2025/09/16}{Replaced \cs{phantomsection} by \cs{MakeLinkTarget}}
%    \begin{macrocode}
\long\def\@spart#1{%
  \M@gettitle{#1}%
  % \phantomsection
  \MakeLinkTarget[part]{}%
  \mempartstarinfo{#1}%
  {\centering
   \interlinepenalty \@M
   \parskip\z@
   \normalfont
   \printparttitle{#1}\par}%
  \@endpart}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ifm@mnopartnewpage}
% \begin{macro}{\m@mnopartnewpagetrue}
% \begin{macro}{\m@mnopartnewpagefalse}
% \begin{macro}{\partblankpage}
% \begin{macro}{\nopartblankpage}
%    The declaration \cs{nopartblankpage} prevents \cs{part} from
% outputting a blank page when it finishes. The default is set by
% \cs{partblankpage}. This code was originally supplied by Frederic Connes.
% \changes{v1.61803}{2008/01/30}{Added \cs{partblankpage} and 
%                    \cs{nopartblankpage} (mempatch v v4.4).}
%    \begin{macrocode}
\newif\ifm@mnopartnewpage
  \m@mnopartnewpagefalse
\newcommand*{\partblankpage}{\m@mnopartnewpagefalse}
\newcommand*{\nopartblankpage}{\m@mnopartnewpagetrue}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% 
% \begin{macro}{\partpageend}
% \begin{macro}{\@endpart}
% This finishes off both \cs{@part} and \cs{@spart}. 
% Following a \cs{nopartblankpage} nothing is done, otherwise
% (after \cs{partblankpage}) the current page is flushed.
% In the standard \Lpack{book} class if 
% two-sided mode is on a blank page is then produced. I think that this looks
% odd when the \Lopt{openany} option is in force, so here it only produces
% an extra blank page if both \Lopt{twoside} and \Lopt{openright} are
% in effect. 
%
% At the end, if necessary, two column mode is switched back on.
% \changes{v1.61803}{2008/01/30}{Used the afterpart pagestyle in \cs{@endpart}}
% \changes{v1.61803398}{2009/07/26}{PW: Added \cs{partpageend} as cover for \cs{@endpart}}
%    \begin{macrocode}
\newcommand*{\partpageend}{\afterpartskip
  \ifm@mnopartnewpage
  \else
    \if@twoside
      \if@openright
        \null
        \thispagestyle{afterpart}%
        \newpage
      \fi
    \fi
  \fi
  \if@tempswa
    \twocolumn
  \fi}
\def\@endpart{\partpageend}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\ps@afterpart}
% Pagestyle for the (blank) page after a part page.
% \changes{v1.61803}{2008/01/30}{Added afterpart pagestyle (mempatch v4.4)}
%    \begin{macrocode}
\aliaspagestyle{afterpart}{empty}

%    \end{macrocode}
% \end{macro}
%
% \subsection{Chapter}
%
% \begin{macro}{\chapter}
%    The command to start a new chapter. Chapters always start on a new page
% with a \pstyle{chapter} pagestyle. Floats are not allowed at the top of the page.
% The typesetting is done by either \cs{@chapter} or \cs{@schapter}.
% \changes{v0.3}{2001/07/09}{Changed \cs{chapter} for article option}
% \changes{v1.0}{2001/10/24}{Changed chapter page clearing to \cs{clearforchapter}}
% \changes{v1.2}{2002/07/27}{New optarg in \cs{chapter} for short heading}
% \changes{v1.618}{2005/09/03}{Made article chapter start on a newline (mempatch v3.5)}
% \changes{v3.6e}{2010/07/16}{Factored out the \cs{@afterindentfalse}}
% \changes{v3.6h}{2011/02/07}{Added the chapter block}
%    \begin{macrocode}
\newcommand\chapter{%
%    \end{macrocode}
% The block macro can be defined to execute a \cs{FloatBlock} when we
% are in article mode. Outside article mode \cs{clearforchapter} is
% expected to be used for this.
%    \begin{macrocode}
  \ifartopt\par\@nameuse{chapterblock}\else
    \clearforchapter
    \thispagestyle{chapter}
    \global\@topnum\z@
  \fi
%  \@afterindentfalse
  \m@mindentafterchapter
  \@ifstar{\@m@mschapter}{\@m@mchapter}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@mindentafterchapter}
% \begin{macro}{\indentafterchapter}
% \begin{macro}{\noindentafterchapter}
%   In order to make whether to indent the first paragraph after af
%   chapter configurable, we store \verb?\@afterindenttrue/false? in
%   \verb?\m@mindentafterchapter?, and provide
%   \verb?\indentafterchapter? and \verb?\noindentafterchapter? to set
%   it to a suitable value. 
%    \begin{macrocode}
\newcommand*\indentafterchapter{\def\m@mindentafterchapter{\@afterindenttrue}}
\newcommand*\noindentafterchapter{\def\m@mindentafterchapter{\@afterindentfalse}}
%    \end{macrocode}
%  Default is not to indent.
%    \begin{macrocode}
\noindentafterchapter

%    \end{macrocode}
%  
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@m@mchapter}
% \begin{macro}{\ch@pt@c}
% \begin{macro}{\m@m@empty}
% Intermediate and support macros for the extra optional argument
% to \cs{chapter}. Have to do this long windedly otherwise dear old
% \Lpack{hyperref} barfs.
%
% The code for two optional arguments is based on a posting
% to \ctt{} by Robin Fairbairns (1997/04/12 \textit{Re: Several optional 
% arguments for macro?}). 
% \changes{v1.618}{2005/09/04}{Major changes to \cs{chapter} macros (from Morten Hogholm 2005/08/30)}
%    \begin{macrocode}
\newcommand{\@m@mchapter}[1][]{%
  \def\ch@pt@c{#1}% capture first optional arg
  \@ifnextchar[{\@chapter}{\@chapter[]}%
}
\def\m@m@empty{\@empty}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\memchapinfo}
% \begin{macro}{\memchapstarinfo}
% \begin{macro}{\memappchapinfo}
% \begin{macro}{\memappchapstarinfo}
% \verb?\memchapinfo{num}{toc}{head}{full}? \\
% \verb?\memchapstarinfo{short}{full}?
% \changes{v1.618}{2005/09/06}{Added \cs{memchapinfo}}
%    \begin{macrocode}
\newcommand{\memchapinfo}[4]{}
\newcommand{\memchapstarinfo}[2]{}
\newcommand{\memappchapinfo}[4]{}
\newcommand{\memappchapstarinfo}[2]{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\ifm@mpn@new@chap}
% \begin{macro}{\m@mpn@new@chapfalse}
% \begin{macro}{\m@mpn@new@chaptrue}
% \begin{macro}{\ifm@mpn@new@schap}
% \begin{macro}{\m@mpn@new@schapfalse}
% \begin{macro}{\m@mpn@new@schaptrue}
% These are for supporting the page/end notes, flagging that a 
% \verb?\chapter(*)? has been called.
% \changes{v1.61803}{2008/01/30}{Added \cs{ifm@mpn@new@chap} and
%          \cs{ifm@mpn@new@chap} (mempatch v4.5)}
%    \begin{macrocode}
\newif\ifm@mpn@new@chap
  \m@mpn@new@chapfalse
\newif\ifm@mpn@new@schap
  \m@mpn@new@schapfalse

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@chapter}
% \begin{macro}{\f@rtoc}
% \begin{macro}{\f@rhdr}
% \begin{macro}{\f@rbody}
% \cs{@chapter}\oarg{tocmark}\marg{title}
% typesets the title of a \cs{chapter}. 
% There is a number if \cs{secnumdepth} is greater than -1 and \cs{@mainmatter}
% is TRUE. 
%
% \changes{v1.2}{2002/07/27}{Complete rewrite of \cs{@chapter}}
% \changes{v1.3}{2002/11/14}{Changed \cs{numberline} to \cs{chapternumberline}
%                            in \cs{@chapter}}
% \changes{v1.61803}{2008/01/30}{Added \cs{f@rbody} to \cs{@chapter},
%      plus newchapter flag (mempatch v4.5)}
% \changes{v1.6180339g}{2009/07/13}{added \cs{m@mpn@new@schapfalse}
% otherwise both might end up true at the same time}
%    \begin{macrocode}
\def\@chapter[#1]#2{%
  \m@mpn@new@chaptrue%
  \m@mpn@new@schapfalse%
  \def\f@rbdy{#2}%
  \ifx\ch@pt@c\@empty % no optional args
    \def\f@rtoc{#2}%
    \def\f@rhdr{#2}%
  \else                  % at least one opt arg
    \let\f@rtoc\ch@pt@c
    \ifx\@empty#1\@empty
      \let\f@rhdr\ch@pt@c
    \else
      \def\f@rhdr{#1}%
    \fi
  \fi
  \m@m@Andfalse
  \ifnum \c@secnumdepth >\m@ne
    \if@mainmatter
      \m@m@Andtrue
    \fi
  \fi
  \ifm@m@And
    \refstepcounter{chapter}%
%    \end{macrocode}
% \changes{v3.8.4}{2025/08/20}{Adding a feature from
% \texttt{book.cls}, have each \cs{chapter} write to the log}
%    \begin{macrocode}
    \typeout{\@chapapp\space\thechapter.}%
%    \end{macrocode}
%   \changes{v3.8.4}{2025/09/16}{Added a link target for when unnumbered}
%    \begin{macrocode}
  \else
    \MakeLinkTarget[chapter]{}%
  \fi
%    \end{macrocode}
% Deal with the \Lopt{article} option.
%    \begin{macrocode}
  \ifartopt
    \@makechapterhead{#2}%
    \@afterheading
    \chaptermark{\f@rhdr}%
  \else
%    \end{macrocode} 
% Store the (short) title via \cs{chaptermark}, and add some whitespace to
% the LoF and LoT. Then fiddle when we are using two columns, calling
% \cs{@makechapterhead} to do the typesetting.
% \changes{v0.3}{2001/07/09}{Changed \cs{@chapter} for article option}
%    \begin{macrocode}
    \chaptermark{\f@rhdr}
    \insertchapterspace
    \if@twocolumn
      \@topnewpage[\@makechapterhead{#2}]%
    \else
      \@makechapterhead{#2}%
    \fi
    \@afterheading
  \fi
%    \end{macrocode}
% When working with \Lpack{hyperref} it is not possible to add, say,
% upper casing to ToC entries via \cs{cftchapterfont}. We provide a
% hook, such that users can transform \cs{f@rtoc} before it is
% actually written to the \texttt{.toc} file.
% \changes{v3.6k}{2012/09/18}{Added}
%    \begin{macrocode}
  \@nameuse{chapter@f@rtoc@before@write@hook}%     
%    \end{macrocode}
%
%   Vittorio De Martino on 31 March 2003 reported that for articled
%   chapters, which do not do any \cs{clearpage}, \cs{addcontents} had
%   to come after the title.
% \changes{v1.4}{2003/11/16}{Changed \cs{@chapter} to match patches v1.n}
% \changes{v3.6k}{2013/04/24}{Added pretoc and posttoc hooks}
%    \begin{macrocode}
  \mempreaddchaptertotochook%
  \ifm@m@And
    \ifanappendix
      \addcontentsline{toc}{appendix}{%
        \protect\chapternumberline{\thechapter}\f@rtoc}%
      \memappchapinfo{\thechapter}{\f@rtoc}{\f@rhdr}{#2}%
    \else
      \addcontentsline{toc}{chapter}{%
        \protect\chapternumberline{\thechapter}\f@rtoc}%
      \memchapinfo{\thechapter}{\f@rtoc}{\f@rhdr}{#2}%
    \fi
  \else
    \addcontentsline{toc}{chapter}{\f@rtoc}%
    \ifanappendix
      \memappchapinfo{}{\f@rtoc}{\f@rhdr}{#2}%
    \else
      \memchapinfo{}{\f@rtoc}{\f@rhdr}{#2}%
    \fi
  \fi
  \mempostaddchaptertotochook%
%    \end{macrocode}
% Add hook for title referencing.
% \changes{v1.4}{2003/11/16}{Added \cs{M@gettitle} to \cs{@chapter}}
% \changes{v3.6k}{2013/04/24}{Added \cs{memendofchapterhook}}.
% The hook at the very end can be used to automatically add a new page
% right after \cs{chapter}.
% \changes{v3.70.20}{2023/07/24}{Redef of \cs{M@gettitle} requires
% expansion for macro arguments}
%    \begin{macrocode}
  \ifheadnameref\ExpandArgs{V}\M@gettitle\f@rhdr\else\ExpandArgs{V}\M@gettitle\f@rtoc\fi%
  \memendofchapterhook%
}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \begin{macro}{\mempreaddchaptertotochook}
% \begin{macro}{\mempostaddchaptertotochook}
% \begin{macro}{\memendofchapterhook}
%   These two hooks are executed before \cs{chapter} adds anything to
%   the TOC and after it does so. It can be used to add hooks into the
%   TOC such that parts can be switched on and off. By default they do nothing.
%    \begin{macrocode}
\newcommand\mempreaddchaptertotochook{}
\newcommand\mempostaddchaptertotochook{}
\newcommand\memendofchapterhook{}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\settocpreprocessor}
% \changes{v3.6k}{2012/09/18}{Added}
% This can be used to set a hook which users can fill in in order to
% get the toc material preprocessed before writing it to the
% \verb?.toc? file. The primary use for this is as a workaround when
% \Lpack{hyperref} is used, and one want to have, say, upper cased toc
% entries. Example of use
% \begin{verbatim}
% \makeatletter
% \settocpreprocessor{chapter}{%
%  \let\temp@f@rtoc\f@rtoc
%  \def\f@rtoc{\texorpdfstring{\MakeUppercase{\temp@f@rtoc}}{\temp@f@rtoc}}
%  }
% \makeatother
% \end{verbatim}
% The idea comes from \url{http://tex.stackexchange.com/q/11892/3929}
% eliminating the need for patching.
%    \begin{macrocode}
\newcommand\settocpreprocessor[2]{%
  \MarkDeprecated{\settocpreprocessor}{in 2026, the problem it tried to solve \MessageBreak
    (see manual, section 9.2.3),\MessageBreak
    has been fixed in the kernel, and the feature is\MessageBreak
    no longer needed.}%
  \@namedef{#1@f@rtoc@before@write@hook}{#2}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@makechapterhead}
% This \emph{really} typesets a \cs{chapter}. Leave some whitespace and prepare to
% set \cs{raggedright}.
% \changes{v1.3}{2002/10/10}{Added \cs{printchapternonum} to 
%                            \cs{@makechapterhead}}
% \changes{v1.61803398}{2009/07/17}{Added bidi support to \cs{@makechapterhead}}
% \changes{v3.6j}{2011/03/01}{Set \cs{parskip} to zero such that a
% non-zero \cs{parskip} to not interfer with the placement of the title}
%    \begin{macrocode}
\def\@makechapterhead#1{%
  \chapterheadstart% 
  {%
   \parskip \z@
   \parindent \z@ \memRTLraggedright \normalfont
%    \end{macrocode}
% If there is a number, typeset it, otherwise call \cs{printchapternonum}.
%    \begin{macrocode}
   \ifm@m@And
     \printchaptername \chapternamenum \printchapternum 
     \afterchapternum % 
   \else
     \printchapternonum
   \fi
%    \end{macrocode}
% Typeset the title.
%    \begin{macrocode}
   \interlinepenalty\@M
   \printchaptertitle{#1} % 
   \afterchaptertitle % 
  }}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\insertchapterspace}
% By default, a \cs{chapter} inserts some vertical space into the LoF and LoT.
% The macro \cs{insertchapterspace} performs the insertion.
% \changes{v0.33}{2001/08/31}{Added \cs{insertchapterspace}}
%    \begin{macrocode}
\newcommand*{\insertchapterspace}{%
  \addtocontents{lof}{\protect\addvspace{10pt}}%
  \addtocontents{lot}{\protect\addvspace{10pt}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\beforechapskip}
% \begin{macro}{\midchapskip}
% \begin{macro}{\afterchapskip}
% Lengths separating the various parts of a chapter heading.
%    \begin{macrocode}
\newlength{\beforechapskip} \setlength{\beforechapskip}{50pt}
\newlength{\midchapskip}    \setlength{\midchapskip}{20pt}
\newlength{\afterchapskip}  \setlength{\afterchapskip}{40pt}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\@chs@def@ult}
% This sets up all the definitions and defaults used in \cs{@makechapterhead}
% and \cs{@makeschapterhead}.
% \changes{v1.3}{2002/10/10}{Added \cs{printchapternonum} to \cs{@chs@def@ult}}
% \changes{v1.61803}{2008/01/30}{Made \cs{@chs@def@ult} set all default chapter values}
% \begin{macro}{\chapterheadstart}
% \begin{macro}{\printchaptername}
% \begin{macro}{\chapternamenum}
% \begin{macro}{\printchapternum}
% \begin{macro}{\afterchapternum}
% \begin{macro}{\printchapternum}
% \begin{macro}{\printchapternonum}
% \begin{macro}{\printchaptertitle}
% \begin{macro}{\afterchaptertitle}
%    \begin{macrocode}
\newcommand{\@chs@def@ult}{%
  \def\chapterheadstart{\vspace*{\beforechapskip}}%
  \def\printchaptername{\chapnamefont \@chapapp}%
  \def\chapternamenum{\space}%
  \def\printchapternum{\chapnumfont \thechapter}%
  \def\afterchapternum{\par\nobreak\vskip \midchapskip}%
  \def\printchapternonum{}%
  \def\printchaptertitle##1{\chaptitlefont ##1}%
  \def\afterchaptertitle{\par\nobreak\vskip \afterchapskip}%
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% 
% \begin{macro}{\chapnamefont}
% \begin{macro}{\chapnumfont}
% \begin{macro}{\chaptitlefont}
% Fonts for setting chapter name, number, and title.
%    \begin{macrocode}
  \def\chapnamefont{\normalfont\huge\bfseries}%
  \def\chapnumfont{\normalfont\huge\bfseries}%
  \def\chaptitlefont{\normalfont\Huge\bfseries}%
  \setlength{\beforechapskip}{50pt}%
  \setlength{\midchapskip}{20pt}%
  \setlength{\afterchapskip}{40pt}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% 
%
% \begin{macro}{\@m@mschapter}
% This deals with the new optional argument for starred chapters.
% \changes{v3.70.20}{2023/07/24}{Redef of \cs{M@gettitle} requires
% expansion for macro arguments}
%    \begin{macrocode}
\newcommand{\@m@mschapter}[2][\@empty]{%
  \@schapter{#2}%
  \ifx \@empty#1
    \def\f@rhdr{#2}%
  \else%                    opt arg
    \def\f@rhdr{#1}%
    \setcounter{secnumdepth}{-10}%
    \chaptermark{#1}%
    \setcounter{secnumdepth}{\value{maxsecnumdepth}}%
  \fi
  \ifanappendix
    \memappchapstarinfo{\f@rhdr}{#2}%
  \else
    \memchapstarinfo{\f@rhdr}{#2}%
  \fi
  \ifheadnameref\ExpandArgs\M@gettitle\f@rhdr\else\M@gettitle{#2}\fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@schapter}
% \begin{macro}{\f@rbdy}
% \cs{@schapter}\marg{long} typesets the title of a 
% \cs{chapter*}. It is easier than the \cs{@chapter} as there is no number
% to worry about.
% \changes{v0.3}{2001/07/09}{Changed \cs{@schapter} for article option}
% \changes{v1.2}{2002/07/27}{Major rewrite of \cs{@schapter}}
% \changes{v1.4}{2003/11/16}{Added \cs{M@gettitle} to \cs{@schapter}}
% \changes{v1.61803}{2008/01/30}{Changed \cs{@schapter} like 
%          \cs{@chapter} (mempatch v4.5)}
% \changes{v1.6180339g}{2009/07/13}{added \cs{m@mpn@new@chapfalse}
% otherwise both might end up true at the same time}
% \changes{v3.8.4}{2025/09/16}{Added a link target}
%    \begin{macrocode}
\newcommand{\@schapter}[1]{%
  \m@mpn@new@schaptrue%
  \m@mpn@new@chapfalse%
  \MakeLinkTarget[chapter]{}%
  \def\f@rbdy{#1}%
  \ifartopt
    \@makeschapterhead{#1}%
  \else
    \if@twocolumn
      \@topnewpage[\@makeschapterhead{#1}]%
    \else
      \@makeschapterhead{#1}%
    \fi
  \fi
  \@afterheading}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@makeschapterhead}
% This \emph{really} typesets a \cs{chapter*}, and is similar to \cs{@makechapterhead}.
% \changes{v1.3}{2002/10/10}{Added \cs{printchapternonum} to 
%                            \cs{@makeschapterhead}}
% \changes{v1.61803398}{2009/07/17}{Added bidi support to \cs{@makeschapterhead}}
% \changes{v3.6j}{2011/0301}{Made sure the \cs{parskip} is zero inside
% the title area, otherwise placement might come out wrong}
%    \begin{macrocode}
\def\@makeschapterhead#1{%
  \chapterheadstart
  {%
   \parskip \z@% 
   \parindent \z@ \memRTLraggedright \normalfont
   \printchapternonum
   \interlinepenalty\@M
   \printchaptertitle{#1}%
   \afterchaptertitle}%
}

%    \end{macrocode}
% \end{macro}
%
%
% \subsubsection{Chapter styling}
%
%
% \begin{macro}{\makechapterstyle}
% \begin{macro}{\chapterstyle}
% \cs{chapterstyle}\marg{style} is like \cs{pagestyle}, except it's for 
% chapters.
%
% \medskip\noindent
% \cs{makechapterstyle}\marg{style}\marg{text} creates
% or overrides the \meta{style} chapter style defining it as \meta{text}
% So, \verb?\makechapterstyle{fred}{code}? specifies that the chapter style 
% \pstyle{fred}
% is defined as the macro \verb?\chs@fred{code}?, 
% and \verb?\chapterstyle{fred}? calls the macro \cs{chs@fred}.
%    \begin{macrocode}
\newcommand{\makechapterstyle}[2]{\@namedef{chs@#1}{\@chs@def@ult #2}}
\newcommand{\chapterstyle}[1]{\@nameuse{chs@#1}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% Set the \pstyle{default} chapter style.
% \changes{v0.2}{2001/06/03}{Added code when making the default chapterstyle}
% \changes{v1.61803}{2008/01/30}{Simplified specification of the default chapterstyle}
%    \begin{macrocode}
\makechapterstyle{default}{}%
 %%  \setlength{\beforechapskip}{50pt}
 %%  \def\chapterheadstart{\vspace*{\beforechapskip}}
 %%  \def\chapnamefont{\normalfont\huge\bfseries}
 %%  \def\printchaptername{\chapnamefont \@chapapp}
 %%  \def\chapternamenum{\space}
 %%  \def\chapnumfont{\normalfont\huge\bfseries}
 %%  \def\printchapternum{\chapnumfont \thechapter}
 %%  \setlength{\midchapskip}{20pt}
 %%  \def\afterchapternum{\par\nobreak\vskip \midchapskip}
 %%  \def\printchapternonum{}
 %%  \def\chaptitlefont{\normalfont\Huge\bfseries}
 %%  \def\printchaptertitle##1{\chaptitlefont ##1}
 %%  \setlength{\afterchapskip}{40pt}
 %%  \def\afterchaptertitle{\par\nobreak\vskip \afterchapskip}
\chapterstyle{default}

%    \end{macrocode}
%
% \begin{macro}{\chs@section}
% The \pstyle{section} chapter style. It prints the heading as though it
% were a section.
% \changes{v1.0a}{2002/01/18}{Made \cs{chapnumfont} change in section 
%                 chapterstyle explicit}
%    \begin{macrocode}
\makechapterstyle{section}{%
  \chapterstyle{default}
  \renewcommand{\printchaptername}{}
  \renewcommand{\chapternamenum}{}
  \renewcommand{\chapnumfont}{\normalfont\Huge\bfseries}
  \renewcommand{\printchapternum}{\chapnumfont \thechapter\space}
  \renewcommand{\afterchapternum}{}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@article}
% The \pstyle{article} chapter style. It prints the heading as though it
% were a section in an \Lpack{article} class document.
% \changes{v0.3}{2001/07/09}{Added article chapterstyle}
% \changes{v1.0a}{2002/01/18}{Made \cs{chapnumfont} change in article chapterstyle explicit}
% \changes{v1.4}{2003/11/22}{Replaced \cs{space} by \cs{quad} in article chapterstyle
%               (from patch v1.7)}
% \changes{v3.8.3}{2025/01/07}{Changed \cs{vspace} to \cs{addvspace} otherwise the spacing above \cs{chapter} does not behave like \cs{section}}
%    \begin{macrocode}
\makechapterstyle{article}{%
  \chapterstyle{default}
  \setlength{\beforechapskip}{3.5ex \@plus 1ex \@minus .2ex}
  \renewcommand*{\chapterheadstart}{\addvspace{\beforechapskip}}
  \setlength{\afterchapskip}{2.3ex \@plus .2ex}
  \renewcommand{\printchaptername}{}
  \renewcommand{\chapternamenum}{}
  \renewcommand{\chaptitlefont}{\normalfont\Large\bfseries}
  \renewcommand{\chapnumfont}{\chaptitlefont}
  \renewcommand{\printchapternum}{\chapnumfont \thechapter\quad}
  \renewcommand{\afterchapternum}{}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@reparticle}
% The \pstyle{reparticle} chapter style. It replicates the appearance
% of a \cs{section} in an \Lpack{article} class document.
% \changes{v1.61803}{2008/01/30}{Added reparticle chapterstyle (mempatch v4.3)}
%    \begin{macrocode}
\makechapterstyle{reparticle}{%
  \chapterstyle{default}
  \setlength{\beforechapskip}{3.5ex \@plus 1ex \@minus .2ex}
  \renewcommand*{\chapterheadstart}{\vspace{\beforechapskip}}
  \setlength{\afterchapskip}{2.3ex \@plus .2ex}
  \renewcommand*{\printchaptername}{}
  \renewcommand*{\chapternamenum}{}
  \renewcommand*{\chaptitlefont}{\normalfont\Large\bfseries}
  \renewcommand*{\chapnumfont}{\chaptitlefont}
  \renewcommand*{\printchapternum}{\@hangfrom{\chapnumfont \thechapter\quad}}%
  \renewcommand*{\afterchapternum}{}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\reparticle}
% Call this to get division heads to replicate the \Lopt{article} class.
% For example: \\
% \verb?\ifartopt \reparticle \fi? \\
% The \cs{chapter} commands must still be used, though.
% \changes{v1.61803}{2008/01/30}{Added \cs{reparticle} (mempatch v4.3)}
% \changes{v1.61803398}{2009/07/17}{Added bidi support to \cs{reparticle}}
%    \begin{macrocode}
\newcommand*{\reparticle}{%
  \chapterstyle{reparticle}
  \setsecheadstyle{\normalfont\large\bfseries\memRTLraggedright}%
  \setsubsecheadstyle{\normalfont\bfseries\memRTLraggedright}%
}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@hangnum}
% The \pstyle{hangnum} style puts the chapter number in the margin.
%    \begin{macrocode}
\makechapterstyle{hangnum}{%
  \chapterstyle{default}
  \renewcommand*{\chapnumfont}{\chaptitlefont}
  \settowidth{\chapindent}{\chapnumfont 999}
  \renewcommand*{\printchaptername}{}
  \renewcommand*{\chapternamenum}{}
  \renewcommand*{\printchapternum}{%
    \noindent\llap{\makebox[\chapindent][l]{\chapnumfont \thechapter}}}
  \renewcommand*{\afterchapternum}{}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chapindent}
% \begin{macro}{\chs@companion}
% The \pstyle{companion} style is like that in the \textit{\LaTeX{} Companion}
% series. It requires the \cs{chapindent} length. The user needs
% to be careful to have a wide enough spine margin on verso pages
% if the title may appear on a verso page.
% \changes{v0.31}{2001/07/24}{Changed adjustwidth* to adjustwidth in companion chapterstyle}
%    \begin{macrocode}
\newlength{\chapindent}

\makechapterstyle{companion}{%
  \chapterstyle{default}
  \renewcommand*{\chapnamefont}{\normalfont\LARGE\scshape}
  \renewcommand*{\printchaptername}{\raggedleft\chapnamefont \@chapapp}
  \renewcommand*{\chapnumfont}{\normalfont\Huge}
  \setlength{\chapindent}{\marginparsep}
  \addtolength{\chapindent}{\marginparwidth}
  \renewcommand*{\printchaptertitle}[1]{%
    \begin{adjustwidth}{}{-\chapindent}
      \raggedleft \chaptitlefont ##1\par\nobreak
    \end{adjustwidth}}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\chs@demo}
% An exotic chapter style for demonstration purposes.
%    \begin{macrocode}
\makechapterstyle{demo}{%
  \chapterstyle{default}
  \renewcommand*{\printchaptername}{\centering}
  \renewcommand*{\printchapternum}{\chapnumfont \numtoName{\c@chapter}}
  \renewcommand*{\chaptitlefont}{\normalfont\Huge\sffamily}
  \renewcommand*{\printchaptertitle}[1]{%
    \hrule\vskip\onelineskip \raggedleft \chaptitlefont ##1}
  \renewcommand*{\afterchaptertitle}%
               {\vskip\onelineskip \hrule\vskip \afterchapskip}}

%    \end{macrocode}
% \end{macro}
%
% \changes{v1.61803}{2008/01/30}{Added chapterstyles: bianchi, bringhurst,
%          brotherton, chappel, culver, dash, demo2, ell, Ger,
%          lyhne, madsen, pedersen, southall, thatcher, veelo,
%          verville, demo3 (mempatch v4.6)}
% \begin{macro}{\chs@bianchi}
% Posted to CTT on 2003/12/09, \textit{New chapter style: chapter vs chapter*}
% by Stefano Bianchi.
%    \begin{macrocode}
\makechapterstyle{bianchi}{%
  \chapterstyle{default}
  \renewcommand*{\chapnamefont}{\normalfont\Large\sffamily\itshape}
  \renewcommand*{\chapnumfont}{\normalfont\huge}
  \renewcommand*{\printchaptername}{%
    \chapnamefont\centering\@chapapp}
  \renewcommand*{\printchapternum}{\chapnumfont \textit{\thechapter}}
  \renewcommand*{\chaptitlefont}{\normalfont\Huge\sffamily}
  \renewcommand*{\printchaptertitle}[1]{%
    \hrule\vskip\onelineskip \centering \chaptitlefont\textbf{##1}\par}
  \renewcommand*{\afterchaptertitle}{\vskip\onelineskip \hrule\vskip
    \afterchapskip}
  \renewcommand*{\printchapternonum}{%
    \vphantom{\chapnumfont \textit{9}}\afterchapternum}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@bringhurst}
% My bringhurst style.
% \changes{v1.61803398}{2009/07/17}{Added bidi support to bringhurst chapterstyle}
% \changes{c3.6k}{2012/09/18}{\cs{MakeLowercase} $\to$ \cs{MakeTextLowercase}}
% \changes{v3.8.4}{2025/08/08}{Reverted \cs{Make...case} change}
%    \begin{macrocode}
\makechapterstyle{bringhurst}{%
  \chapterstyle{default}
  \renewcommand*{\chapterheadstart}{}
  \renewcommand*{\printchaptername}{}
  \renewcommand*{\chapternamenum}{}
  \renewcommand*{\printchapternum}{}
  \renewcommand*{\afterchapternum}{}
  \renewcommand*{\printchaptertitle}[1]{%
    \memRTLraggedright\Large\scshape\MakeLowercase{##1}}
  \renewcommand*{\afterchaptertitle}{%
  \vskip\onelineskip \hrule\vskip\onelineskip}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@brotherton}
% An extremely simple chapterstyle created by William Adams for Mike 
% Brotherton's science fiction novel \textit{Star Dragon}, posted to CTT
% 2006/12/09, \textit{An example of a novel?}.
%    \begin{macrocode}
\makechapterstyle{brotherton}{%
  \chapterstyle{default}
  \renewcommand*{\printchapternum}{\chapnumfont 
    \ifanappendix \thechapter \else \numtoName{\c@chapter}\fi}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@chappell}
% My Chappell style
%    \begin{macrocode}
\makechapterstyle{chappell}{%
  \chapterstyle{default}
  \setlength{\beforechapskip}{0pt}
  \renewcommand*{\chapnamefont}{\large\centering}
  \renewcommand*{\chapnumfont}{\large}
  \renewcommand*{\printchapternonum}{%
    \vphantom{\printchaptername \chapnumfont 1}
    \afterchapternum
    \vskip \onelineskip \vskip -\topskip}
  \renewcommand*{\chaptitlefont}{\Large\itshape}
  \renewcommand*{\printchaptertitle}[1]{%
    \hrule\vskip\onelineskip \centering\chaptitlefont ##1}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@culver}
% By me in an answer to Christopher Culver on CTT, 
% \textit{"Biblical" formatting, how?} on 2004/03/29,where I called it 
% the `biblical' style.
%    \begin{macrocode}
\makechapterstyle{culver}{%
  \chapterstyle{default}
  \chapterstyle{article}%
  \renewcommand*{\thechapter}{\Roman{chapter}}
  \renewcommand*{\printchapternum}{% center number/title
    \centering\chapnumfont \thechapter\space\space}%
  \renewcommand*{\printchapternonum}{\centering}
  \renewcommand*{\clearforchapter}{}% no new page
  \aliaspagestyle{chapter}{headings}}% no special pagestyle

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@dash}
% A very simple style of mine but I couldn't think of a good name for it.
%    \begin{macrocode}
\makechapterstyle{dash}{%
  \chapterstyle{default}
  \setlength{\beforechapskip}{5\onelineskip}
  \renewcommand*{\printchaptername}{}
  \renewcommand*{\chapternamenum}{}
  \renewcommand*{\chapnumfont}{\normalfont\large}
  \settoheight{\midchapskip}{\chapnumfont 1}
  \renewcommand*{\printchapternum}{\centering \chapnumfont 
    \rule[0.5\midchapskip]{1em}{0.4pt} \thechapter\ 
    \rule[0.5\midchapskip]{1em}{0.4pt}}
  \renewcommand*{\afterchapternum}{\par\nobreak\vskip 0.5\onelineskip}
  \renewcommand*{\printchapternonum}{\centering 
                 \vphantom{\chapnumfont 1}\afterchapternum}
  \renewcommand*{\chaptitlefont}{\normalfont\Large}
  \renewcommand*{\printchaptertitle}[1]{\centering \chaptitlefont ##1}
  \setlength{\afterchapskip}{2.5\onelineskip}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@demo2}
% My second version of the demo chapterstyle.
%    \begin{macrocode}
\makechapterstyle{demo2}{%
  \chapterstyle{default}
  \renewcommand*{\printchaptername}{\centering}
  \renewcommand*{\printchapternum}{\chapnumfont 
     \ifanappendix \thechapter \else \numtoName{\c@chapter}\fi}
  \renewcommand*{\chaptitlefont}{\normalfont\Huge\sffamily}
  \renewcommand*{\printchaptertitle}[1]{%
    \hrule\vskip\onelineskip \raggedleft \chaptitlefont ##1}
  \renewcommand*{\afterchaptertitle}{%
    \vskip\onelineskip \hrule\vskip \afterchapskip}
  \setlength{\beforechapskip}{3\baselineskip}
  \renewcommand*{\printchapternonum}{%
    \vphantom{\chapnumfont One}
    \afterchapternum%
    \vskip\topskip}
  \setlength{\beforechapskip}{2\onelineskip}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@demo3}
% My third version of the demo chapterstyle.
%    \begin{macrocode}
\makechapterstyle{demo3}{%
  \chapterstyle{default}
  \renewcommand*{\printchaptername}{\centering}
  \renewcommand*{\chapnumfont}{\normalfont\HUGE\itshape}
  \renewcommand*{\printchapternum}{\chapnumfont 
     \ifanappendix \thechapter \else \numtoName{\c@chapter}\fi}
  \renewcommand*{\chaptitlefont}{\normalfont\Huge\sffamily}
  \renewcommand*{\printchaptertitle}[1]{%
    \hrule\vskip\onelineskip \raggedleft \chaptitlefont ##1}
  \renewcommand*{\afterchaptertitle}{%
    \vskip\onelineskip \hrule\vskip \afterchapskip}
  \setlength{\beforechapskip}{0pt}
  \setlength{\midchapskip}{2\onelineskip}
  \setlength{\afterchapskip}{2\onelineskip}
  \renewcommand*{\printchapternonum}{%
    \vphantom{\chapnumfont One}
    \afterchapternum%
    \vskip\topskip}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@ell}
% Another of my styles which I'll probably use for my next book.
%
% James Dietrich (2014/05/29)
% reports that the line and number part of the \textsf{ell} chapter
% style does not align correctly if the page is excessively
% stretched. The style is reimplemented using \Lenv{tabularx} instead.
% \changes{v3.7d}{2014/11/05}{Reimplemeted the ell chapter style}
% \begin{macro}{\chs@ell@helper}
%   For code reuse (the slightly strange values come from trial and
%   error to match the original look):
%    \begin{macrocode}
\newcommand\chs@ell@helper[1]{%
  \par%
    \begin{adjustwidth}{}{-\chapindent}
      \begin{tabularx}{\linewidth}{>{\raggedleft\arraybackslash}X|}%|emacs
        \leavevmode\chapnumfont #1\vphantom{1}%
        \hspace*{3.6pt}%
        \rule[-13.5pt]{0pt}{14.8mm}%
        \\%
        \hline%
      \end{tabularx}%
    \end{adjustwidth}%
    \par%
  }%

%    \end{macrocode}
% \end{macro}
% 
%    \begin{macrocode}
\makechapterstyle{ell}{%
  \chapterstyle{default}
  \renewcommand*{\chapnumfont}{\normalfont\HUGE\sffamily}
  \renewcommand*{\chaptitlefont}{\normalfont\huge\sffamily}
  \settowidth{\chapindent}{\chapnumfont 111}
  % \renewcommand*{\chapterheadstart}{\begingroup
  %   \vspace*{\beforechapskip}%
  %   \begin{adjustwidth}{}{-\chapindent}%
  %   \hrulefill
  %   \smash{\rule{0.4pt}{15mm}}
  %   \end{adjustwidth}\endgroup}
  \renewcommand*{\printchaptername}{}
  \renewcommand*{\chapternamenum}{}
  \renewcommand*{\printchapternum}{% 
    % \begin{adjustwidth}{}{-\chapindent}
    % \hfill
    % \raisebox{10mm}[0pt][0pt]{\chapnumfont \thechapter}%
    %                           \hspace*{1em}
    % \end{adjustwidth}\vspace*{-3.0\onelineskip}
    \chs@ell@helper{\thechapter}%
  }
  \renewcommand\printchapternonum{%
    \chs@ell@helper{}\afterchapternum}
  \renewcommand*{\printchaptertitle}[1]{%
    %\vskip\onelineskip
    \raggedleft {\chaptitlefont ##1}\par\nobreak}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@ger}
% Posted to CTT on 2002/04/12 \textit{Fancy Headings, Chapter Headings} by Gerardo Garcia.
%    \begin{macrocode}
\makechapterstyle{ger}{%
  \chapterstyle{default}
  \renewcommand*{\chapterheadstart}{\vspace*{\beforechapskip}
  \mbox{}\\\mbox{}\rule[0pt]{\textwidth}{0.4pt}\par}
  \setlength{\midchapskip}{20pt}
  \renewcommand*{\printchaptertitle}[1]{\chaptitlefont ##1
    \\\mbox{}\rule[5pt]{\textwidth}{0.4pt}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@lyhne}
% Posted to CTT 2006/02/09 \textit{Glossary}, by Anders Lyhne.
% It requires the \Lpack{graphicx} package. I have modified it to remove the
% new length and adjusted the unnumbered appearance.
%    \begin{macrocode}
\makechapterstyle{lyhne}{%  needs graphicx package
  \chapterstyle{default}
  \setlength{\beforechapskip}{1.5cm}
  \setlength{\afterchapskip}{1cm}
  \setlength{\midchapskip}{2cm}
  \renewcommand*{\chapnamefont}{\normalfont\normalsize\scshape\raggedleft}
  \renewcommand*{\chaptitlefont}{\normalfont\normalsize\bfseries\sffamily\raggedleft}
  \renewcommand*{\chapternamenum}{}
  \renewcommand*{\printchapternum}{\makebox[0pt][l]{\hspace{0.2em}%
    \resizebox{!}{2ex}{\chapnamefont\bfseries\sffamily\thechapter}}}
  \renewcommand*{\afterchapternum}{\par\hspace{1.5cm}\hrule\vspace{0.2cm}}
 \renewcommand*{\printchapternonum}{\vphantom{\chapnamefont 1}\afterchapternum}
  \renewcommand*{\afterchaptertitle}{\vskip 0.2cm 
    \hrule\vskip\afterchapskip}}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\chs@madsen}
% Posted to CTT on 2003/12/09, \textit{New chapter style: chapter vs chapter*}
% by Lars Madsen. 
% This requires the \Lpack{graphicx} package,
% \changes{v1.61803398c}{2009/11/15}{Updated to provide a better
% unnumbered look}
% \changes{v3.6d}{2010/05/13}{the unnumbered version may be executed
% in a context where \cs{thechapter} is not weldefined, replaced with
% a 1}
%    \begin{macrocode}
\makechapterstyle{madsen}{% requires graphicx package
  \chapterstyle{default}
  \renewcommand*{\chapnamefont}{%
    \normalfont\Large\scshape\raggedleft}
  \renewcommand*{\chaptitlefont}{%
    \normalfont\Huge\bfseries\sffamily\raggedleft}
  \renewcommand*{\chapternamenum}{}
  \renewcommand*{\printchapternum}{%
    \makebox[0pt][l]{\hspace{0.4em}%
      \resizebox{!}{4ex}{%
        \chapnamefont\bfseries\sffamily\thechapter}%
    }%
  }%
  \renewcommand*{\printchapternonum}{%
    \chapnamefont \phantom{\printchaptername \chapternamenum%
      \makebox[0pt][l]{\hspace{0.4em}%
        \resizebox{!}{4ex}{%
          \chapnamefont\bfseries\sffamily 1}%
      }%
    }%
    \afterchapternum %
  }% 
  \renewcommand*{\afterchapternum}{%
    \par\hspace{1.5cm}\hrule\vskip\midchapskip}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\colorchapnum}
% \begin{macro}{\colorchaptitle}
% \begin{macro}{\chs@pedersen}
% Posted to CTT 2006/01/31, \textit{Chapter style}, by Troels Pedersen.
% It requires the \Lpack{graphicx} package and possibly the \Lpack{color}
% package. I have used a \cs{sidebar} instead of the original \cs{marginpar},
% and eliminated a new length. The original color specification, the same for
% the title and nunmber, can now be set via \cs{colorchapnum} and
% \cs{colorchaptitle}.
%    \begin{macrocode}
\newcommand*{\colorchapnum}{}
\newcommand*{\colorchaptitle}{}
\makechapterstyle{pedersen}{%
  \chapterstyle{default}
  \setlength{\beforechapskip}{-20pt}
  \setlength{\afterchapskip}{10pt}
  \renewcommand*{\chapnamefont}{\normalfont\LARGE\itshape}
  \renewcommand*{\chapnumfont}{\normalfont\HUGE\itshape\colorchapnum}
  \renewcommand*{\chaptitlefont}{\normalfont\huge\itshape\colorchaptitle}
  \renewcommand*{\afterchapternum}{}
  \renewcommand*{\printchaptername}{}
  \setlength{\midchapskip}{20mm}% was \numberheight
  \renewcommand*{\chapternamenum}{}
  \renewcommand*{\printchapternum}{%
    \sidebar{\raisebox{0pt}[0pt][0pt]{\makebox[0pt][l]{%
      \resizebox{!}{\midchapskip}{\chapnumfont\thechapter}}}}}
  \renewcommand*{\printchaptertitle}[1]{\chaptitlefont ##1}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\chs@southall}
% Style provided by Thomas Dye. I have modified the original to eliminate
% the use of new lengths.
% \changes{v1.61803398}{2009/07/17}{Added bidi support to southall chapterstyle}
%    \begin{macrocode}
%% Thomas Dye's southall chapter style
\makechapterstyle{southall}{%
  \chapterstyle{default}
  \setlength{\afterchapskip}{5\baselineskip}
  \setlength{\beforechapskip}{36pt}%    \headindent
  \setlength{\midchapskip}{\textwidth}% \rightblock
  \addtolength{\midchapskip}{-\beforechapskip}
  \renewcommand*{\chapterheadstart}{\vspace*{2\baselineskip}}
  \renewcommand*{\chaptitlefont}{\huge\rmfamily\memRTLraggedright}
  \renewcommand*{\chapnumfont}{\chaptitlefont}
  \renewcommand*{\printchaptername}{}
  \renewcommand*{\chapternamenum}{}
  \renewcommand*{\afterchapternum}{}
  \renewcommand*{\printchapternum}{%
    \begin{minipage}[t][\baselineskip][b]{\beforechapskip}
      {\vspace{0pt}\chapnumfont%%%\figureversion{lining} 
                   \thechapter}
    \end{minipage}}
  \renewcommand*{\printchaptertitle}[1]{%
    \hfill\begin{minipage}[t]{\midchapskip}
      {\vspace{0pt}\chaptitlefont ##1\par}\end{minipage}}
  \renewcommand*{\afterchaptertitle}{%
    \par\vspace{\baselineskip}%
    \hrulefill \par\nobreak\noindent \vskip \afterchapskip}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@thatcher}
%  Original posted to CTT on 2006/01/18 by Scott Thatcher,
% \textit{memoir: chapter headings capitalize math symbols}. I have modified
% it to cater for multiline titles, appendices, and unnumbered
% chapters.
% \changes{c3.6k}{2012/09/18}{\cs{MakeUppercase} $\to$ \cs{MakeTextUppercase}}
% \changes{c3.6k}{2012/09/18}{\cs{MakeLowercase} $\to$ \cs{MakeTextLowercase}}
% \changes{v3.8.4}{2025/08/08}{Reverted \cs{Make...case} change}
%    \begin{macrocode}
\makechapterstyle{thatcher}{%
  \chapterstyle{default}
  \renewcommand*{\chapterheadstart}{}
  \renewcommand*{\printchaptername}{%
    \centerline{\chapnumfont{\@chapapp\ \thechapter}}}
  \renewcommand*{\chapternamenum}{}
  \renewcommand*{\chapnumfont}{\normalfont\scshape\MakeLowercase}
  \renewcommand*{\printchapternum}{}
  \renewcommand*{\afterchapternum}{%
    \par\centerline{\parbox{0.5in}{\hrulefill}}\par}
  \renewcommand*{\printchapternonum}{%
    \vphantom{\chapnumfont \@chapapp 1}\par 
    \parbox{0.5in}{}\par}
  \renewcommand*{\chaptitlefont}{\normalfont\large}
  \renewcommand*{\printchaptertitle}[1]{%
    \centering \chaptitlefont\MakeUppercase{##1}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@veelo}
% This, from Baastian Veelo, has been noted in the documentation for 
% quite a time.
% I have modified the original to eliminate the need for extra lengths.
% It well suits trimmed documents.
% We are scaling the chapter number, which most DVI viewers
% will not display accurately. It requires the graphicx package.
% \changes{v3.6k}{2012/09/18}{\cs{MakeUppercase} $\to$ \cs{MakeTextUppercase}}
% \changes{v3.8.4}{2025/08/08}{Reverted \cs{Make...case} change}
%    \begin{macrocode}
\makechapterstyle{veelo}{%
%  \chapterstyle{default}
   \setlength{\afterchapskip}{40pt}
  \renewcommand*{\chapterheadstart}{\vspace*{40pt}}
  \renewcommand*{\afterchapternum}{\par\nobreak\vskip 25pt}
   \renewcommand*{\chapnamefont}{\normalfont\LARGE\flushright}
   \renewcommand*{\chapnumfont}{\normalfont\HUGE}
   \renewcommand*{\chaptitlefont}{\normalfont\HUGE\bfseries\flushright}
   \renewcommand*{\printchaptername}{%
     \chapnamefont\MakeUppercase{\@chapapp}}
   \renewcommand*{\chapternamenum}{}
%   \setlength{\numberheight}{18mm}
%   \setlength{\barlength}{\paperwidth}
%   \addtolength{\barlength}{-\textwidth}
%   \addtolength{\barlength}{-\spinemargin}
  \setlength{\beforechapskip}{18mm}%  \numberheight
  \setlength{\midchapskip}{\paperwidth}% \barlength
  \addtolength{\midchapskip}{-\textwidth}
  \addtolength{\midchapskip}{-\spinemargin}
   \renewcommand*{\printchapternum}{%
     \makebox[0pt][l]{%
       \hspace{.8em}%
       \resizebox{!}{\beforechapskip}{\chapnumfont \thechapter}%
       \hspace{.8em}%
       \rule{\midchapskip}{\beforechapskip}%
     }%
   }%
   \makeoddfoot{plain}{}{}{\thepage}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@verville}
% I posted the original to CTT on 2005/01/18, \textit{Headers and special
% formatting of sections}, in answer to a question by 
% Guy Verville. This version caters for unnumbered chapters.
%    \begin{macrocode}
\makechapterstyle{verville}{%
 % \chapterstyle{default}
  \setlength{\beforechapskip}{0pt}
  \renewcommand*{\printchaptername}{}
  \renewcommand*{\printchapternum}{%
    \hrule \vskip 0.5\onelineskip
    \Huge \centering \thechapter.\ }
  \renewcommand*{\printchapternonum}{%
    \hrule \vskip 0.5\onelineskip
    \Huge \centering}
  \renewcommand*{\afterchapternum}{}
  \setlength{\midchapskip}{0pt}
  \renewcommand*{\printchaptertitle}[1]{%
    ##1 \par
    \vskip 0.5\onelineskip
   \hrule}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@crosshead}
% A centered chapterstyle (from Bringhurst)
% \changes{v1.61803}{2008/01/30}{Added chapterstyles: crosshead, dowding, 
%                    komalike, ntglike, tandh, and wilsondob}
%    \begin{macrocode}
\makechapterstyle{crosshead}{%
  \setlength{\beforechapskip}{2\onelineskip}%
  \renewcommand*{\chapterheadstart}{\vspace{\beforechapskip}}%
  \setlength{\afterchapskip}{2\onelineskip \@plus .2\onelineskip 
                             \@minus 0.2\onelineskip}%
  \renewcommand*{\printchaptername}{}%
  \renewcommand*{\chapternamenum}{}%
  \renewcommand*{\chapnumfont}{\normalfont\LARGE\bfseries}%
  \renewcommand*{\chaptitlefont}{\chapnumfont}%
  \renewcommand*{\printchapternum}{%
    \centering\chapnumfont \thechapter\quad}%
  \renewcommand{\afterchapternum}{}%
  \renewcommand*{\printchapternonum}{\centering}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@dowding}
% A centered chapterstyle (from Dowding's \textit{Finer Points})
%    \begin{macrocode}
\makechapterstyle{dowding}{%
  \setlength{\beforechapskip}{2\onelineskip}%
  \setlength{\afterchapskip}{1.5\onelineskip \@plus .1\onelineskip 
                            \@minus 0.167\onelineskip}%
  \renewcommand*{\chapnamefont}{\normalfont}%
  \renewcommand*{\chapnumfont}{\chapnamefont}%
  \renewcommand*{\printchapternum}{\centering\chapnumfont \ifanappendix \thechapter
                 \else \numtoName{\c@chapter}\fi}%
  \renewcommand*{\chaptitlefont}{\normalfont\itshape\huge\centering}%
  \renewcommand*{\printchapternonum}{%
    \vphantom{\printchaptername}\vskip\midchapskip}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@komalike}
% A chapterstyle approximating the KOMA script style (\texttt{scrbook.cls})
%    \begin{macrocode}
\makechapterstyle{komalike}{%
  \setlength{\beforechapskip}{2\onelineskip}%
  \setlength{\afterchapskip}{1.5\onelineskip \@plus .1\onelineskip 
                             \@minus 0.167\onelineskip}%
  \renewcommand*{\printchaptername}{}%
  \renewcommand*{\chapternamenum}{}%
  \renewcommand*{\chapnumfont}{\normalfont\LARGE\sffamily\bfseries}%
  \renewcommand*{\printchapternum}{\chapnumfont \thechapter\space}%
  \renewcommand*{\afterchapternum}{}%
  \renewcommand*{\chaptitlefont}{\normalfont\LARGE\sffamily\bfseries}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@ntglike}
% A chapterstyle approximating the NTG style (\texttt{boek.cls})
%    \begin{macrocode}
\makechapterstyle{ntglike}{%
  \setlength{\beforechapskip}{50pt \@plus 20pt}%
  \renewcommand*{\chapnamefont}{\normalfont\Large\bfseries}%
  \renewcommand*{\chapnumfont}{\normalfont\Large\bfseries}%
  \renewcommand*{\chaptitlefont}{\normalfont\Large\bfseries}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@tandh}
% A chapterstyle based on Thames \& Hudson \textit{Typography}.
% \changes{v1.61803398}{2009/07/17}{Added bidi support to tandh chapterstyle}
%    \begin{macrocode}
\makechapterstyle{tandh}{%
  \setlength{\beforechapskip}{1\onelineskip}%
  \setlength{\afterchapskip}{2\onelineskip \@plus .1\onelineskip 
                            \@minus 0.167\onelineskip}%
  \renewcommand*{\printchaptername}{}%
  \renewcommand*{\chapternamenum}{}%
  \renewcommand*{\chapnumfont}{\normalfont\huge\bfseries}%
  \renewcommand*{\printchapternum}{\chapnumfont \thechapter\quad}%
  \renewcommand*{\afterchapternum}{}%
  \renewcommand*{\chaptitlefont}{\chapnumfont\memRTLraggedright}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@wilsondob}
% A chapterstyle based on Adrian Wilson's \textit{Design of books}.
%    \begin{macrocode}
\makechapterstyle{wilsondob}{%
  \setlength{\beforechapskip}{2\onelineskip}%
  \setlength{\afterchapskip}{4\onelineskip \@plus .1\onelineskip 
                             \@minus 0.167\onelineskip}%
  \renewcommand*{\printchaptername}{}%
  \renewcommand*{\chapternamenum}{}%
  \renewcommand*{\chapnumfont}{\normalfont\Huge\itshape}%
  \renewcommand*{\printchapternum}{\raggedleft\chapnumfont \thechapter\quad}%
  \renewcommand*{\afterchapternum}{}%
  \renewcommand*{\chaptitlefont}{\chapnumfont}%
  \renewcommand*{\printchapternonum}{\raggedleft}}

%    \end{macrocode}
% \end{macro}
%
%
% \subsection{Lower level headings}
%
%    These commands all make use of \cs{@startsection}. However,
% for the purposes of the class the kernel version needs modification
% to support:
% \begin{itemize}
% \item make short pages (where a section heading is moved to the top
%       of the next page) ragged bottom;
% \item provide headings with two optional arguments.
% \end{itemize}
%
%
%    We will tweak \cs{@startsection} so that a short page (where a section
% heading is moved from the bottom of the page to the top of the next)
% can be set \cs{raggedbottom}. 
%
% \begin{macro}{\ifraggedbottomsection}
% \begin{macro}{\raggedbottomsectiontrue}
% \begin{macro}{\raggedbottomsectionfalse}
% \begin{macro}{\raggedbottomsection}
% \begin{macro}{\normalbottomsection}
% \begin{macro}{\bottomsectionpenalty}
% \cs{raggedbottomsectiontrue} for ragged short pages.
% \changes{v1.3}{2002/11/14}{Added \cs{ifraggedbottomsection}}
% \changes{v1.61803}{2008/01/30}{Added \cs{raggedbottomsection} and 
%                               \cs{normalbottomsection}}
% \changes{v3.6k}{2012/07/22}{Made the \cs{raggedbottomsection}
% penalty configurable}
%    \begin{macrocode}
\newif\ifraggedbottomsection
  \raggedbottomsectionfalse
\newcommand*{\raggedbottomsection}{\raggedbottomsectiontrue}
\newcommand*{\normalbottomsection}{\raggedbottomsectionfalse}
\newcommand*{\bottomsectionpenalty}{\z@}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\bottomsectionskip}
% Decreasing this length increases short page bottom flushness.
% \changes{v1.3}{2002/11/14}{Added \cs{bottomsectionskip}}
%    \begin{macrocode}
\newlength{\bottomsectionskip}
  \setlength{\bottomsectionskip}{10mm}

%    \end{macrocode}
% \end{macro}
%
% We will add a second optional argument for \cs{section}, etc.
% See the \ctt{} thread \textit{`Long headers'} 15 Jan 2003.
%
% The kernel \cs{@dblarg} is used in situations where the default
% value for an optional argument is the same as the required argument.
% Schematically, \\
% \verb?\@dblarg -> Main, Main? \\
% The macros \cs{@trplargomm} and \cs{@trplargoom} are extensions to this
% idea for two optional arguments.
%
% \begin{macro}{\@trplargomm}
% \begin{macro}{\@xtrplargomm}
% \begin{macro}{\@xxtrplarg}
% \verb?\@trplargomm -> Opt, Main, Main?
%    \begin{macrocode}
\newcommand{\@trplargomm}[1]{%
  \@ifnextchar[{\@xtrplargomm{#1}}%
               {\@xxtrplarg{#1}}}
\long\def\@xtrplargomm#1[#2]{\@dblarg{#1[#2]}}
\newcommand{\@xxtrplarg}[2]{#1[{#2}][{#2}]{#2}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@trplargoom}
% \begin{macro}{\@xtrplargoom}
% \verb?\@trplargoom -> Opt, Opt, Main?
%    \begin{macrocode}
\newcommand{\@trplargoom}[1]{%
  \@ifnextchar[{\@xtrplargoom{#1}}%
               {\@xxtrplarg{#1}}}
\long\def\@xtrplargoom#1[#2]{%
  \@ifnextchar[{#1[{#2}]}%
               {#1[{#2}][{#2}]}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\memsecinfo}
% \begin{macro}{\memsecstarinfo}
% \verb?\memsecinfo{secname}{\thenum}{toc}{head}{title}? \\
% \verb?\memsecstarinfo{secname}{title}? \\
%    \begin{macrocode}
\newcommand{\memsecinfo}[5]{}
\newcommand{\memsecstarinfo}[2]{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@startsection}
% \begin{macro}{\m@msecn@me}
% Change kernel \cs{@startsection} to: \\
% \begin{itemize}
% \item Make short pages raggedbottom. This is based on the thread 
% \textit{Can \cs{flushbottom} and \cs{section} be made to live together?} 
% on \ctt{} in September 2002.
% \changes{v1.3}{2002/11/14}{Modified \cs{@startsection} for raggedbottoming}
% \item add an extra optional argument.
% \changes{v1.4}{2003/11/22}{Added extra optional arg to \cs{@startsection}
%                            (from patch v1.4)}
% \item make sure it is not effected by a non-zero \cs{parskip}
%   \changes{v3.6j}{2011/03/02}{added the above feature}
% \item store the name of the type in \cs{m@msecn@me}
% \end{itemize}
% The original is in \file{latex.ltx}. \\
% \cs{@startsection}\marg{name}\marg{level}\marg{indent} \\
% \hspace*{1.5in} \marg{beforeskip}\marg{afterskip}\marg{style}
%
% In order to make experiments with the tagging code, we only make the
% redefinition, if \textsf{dev-mode} is not active. Otherwise we
% patch. It is intentional that the patches are ``talkative''.
% \changes{v3.8.2}{2023/08/24}{Forgot to add this patching branch in 3.8}
%    \begin{macrocode}
\ifmem@devmode

%    \end{macrocode}
% The first patch add the block hook, the raggedbottom secton code,
% and the storing of the name of the section type.
%    \begin{macrocode}
  \patchcmd\@startsection{%
    \if@noskipsec \leavevmode \fi%
  }{%
    \@nameuse{#1block}%
    \ifraggedbottomsection\if@nobreak\else
        \vskip\z@\@plus\bottomsectionskip
        \penalty\bottomsectionpenalty
        \vskip\z@\@plus -\bottomsectionskip
      \fi\fi
    \def\m@msecn@me{#1}%
    \if@noskipsec \leavevmode \fi%
  }%
  {\typeout{\string\@startsection\space patch 1 success}}
  {\typeout{\string\@startsection\space patch 1 failed}}

%    \end{macrocode}
% The second patch adds a small adjustment that help counter the
% effect of a non-zero \cs{parskip}
%    \begin{macrocode}
  \patchcmd\@startsection{%
    \addpenalty\@secpenalty\addvspace\@tempskipa%
  }{%
    \addpenalty\@secpenalty\addvspace\@tempskipa
    \addvspace{-\parskip}% <--- added 2011/03/02
  }%
  {\typeout{\string\@startsection\space patch 2 success}}
  {\typeout{\string\@startsection\space patch 2 failed}}

%    \end{macrocode}
% The third patch completely replaces
% \begin{verbatim}
% \@ifstar
%     {\@ssect{#3}{#4}{#5}{#6}}%
%     {\@dblarg{\@sect{#1}{#2}{#3}{#4}{#5}{#6}}}
% \end{verbatim}
% as we need to handle two optional args not just the normal
% 1. Perhaps there are better ways.
%    \begin{macrocode}
  \patchcmd\@startsection{%
     \@ifstar%
     {\@ssect{#3}{#4}{#5}{#6}}%
     {\@dblarg{\@sect{#1}{#2}{#3}{#4}{#5}{#6}}}%
   }{%
     \@ifstar%
    {\@ssect{#3}{#4}{#5}{#6}}%
    {\@trplargoom{\M@sect{#1}{#2}{#3}{#4}{#5}{#6}}}%
  }%
  {\typeout{\string\@startsection\space patch 3 success}}
  {\typeout{\string\@startsection\space patch 3 failed}}
 
\else % standard branch for dev-mode false
%    \end{macrocode}
%   Then the normal redefinition
% ^^A name, level, indent, beforeskip, afterskip, style
%    \begin{macrocode}
  \renewcommand{\@startsection}[6]{%
%    \end{macrocode}
% \changes{v3.6h}{2011/02/07}{Added float block hook}
%    \begin{macrocode}
    \@nameuse{#1block}%
%    \end{macrocode}
% Do raggedbottom stuff.
% \changes{v3.6k}{2012/07/22}{Made the \cs{raggedbottomsection}
% penalty configurable}
%    \begin{macrocode}
    \ifraggedbottomsection\if@nobreak\else
      \vskip\z@\@plus\bottomsectionskip
      \penalty\bottomsectionpenalty
      \vskip\z@\@plus -\bottomsectionskip
    \fi\fi
%    \end{macrocode}
% Save the section name.
%    \begin{macrocode}
    \def\m@msecn@me{#1}%
%    \end{macrocode}
% The original code.
%    \begin{macrocode}
    \if@noskipsec \leavevmode \fi
    \par
    \@tempskipa #4\relax
    \@afterindenttrue
    \ifdim \@tempskipa <\z@
      \@tempskipa -\@tempskipa \@afterindentfalse
    \fi
    \if@nobreak
      \everypar{}%
    \else
%    \end{macrocode}
% Slight change such that the effect of \cs{parskip} is cancelled
% \changes{v3.6j}{2011/03/02}{Adding a negative \cs{parskip} seem to
% be able to remove the effect of a non-zero \cs{parskip}}
%    \begin{macrocode}
      \addpenalty\@secpenalty\addvspace\@tempskipa
      \addvspace{-\parskip}% <--- added 2011/03/02
    \fi
%    \end{macrocode}
% For the extra optional argument, change the original \verb?\@dblarg{\@sect{...?
% below to \verb?\@trplargoom{\M@sect{...?.
%    \begin{macrocode}
    \@ifstar
      {\@ssect{#3}{#4}{#5}{#6}}%
      {\@trplargoom{\M@sect{#1}{#2}{#3}{#4}{#5}{#6}}}}
  
%    \end{macrocode}
% end dev-mode-else branch for \cs{@startsection}:
%    \begin{macrocode}

\fi % en dev-mode else branch

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \changes{v3.6j}{2011/03/02}{Added the change of the kernel \cs{@xsect}}
% \begin{macro}{\@xsect}
%   In order to fulfill removing the effect that a non-zero
%   \cs{parskip} has on the sectional spacing after the title, we also have to patch
%   the kernel \cs{@xsect}. (The original is found in latex.ltx) 
% \changes{v3.8.4}{2025/09/18}{Now done using a patch instead of copying and adding one line}
% \changes{v3.8.4}{2025/10/02}{Tagging code may touch \cs{@xsect} and then the patch fails because of catcodes}
%    \begin{macrocode}
 % \def\@xsect#1{%
 %   \@tempskipa #1\relax
 %   \ifdim \@tempskipa>\z@
 %     \par \nobreak
 %     \vskip \@tempskipa
 %     \vskip-\parskip%<--- added 2011/03/02
 %     \@afterheading
 %   \else
 %     \@nobreakfalse
 %     \global\@noskipsectrue
 %     \everypar{%
 %       \if@noskipsec
 %         \global\@noskipsecfalse
 %        {\setbox\z@\lastbox}%
 %         \clubpenalty\@M
 %         \begingroup \@svsechd \endgroup
 %         \unskip
 %         \@tempskipa #1\relax
 %         \hskip -\@tempskipa
 %       \else
 %         \clubpenalty \@clubpenalty
 %         \everypar{}%
 %       \fi}%
 %   \fi
 %   \ignorespaces}
\ExplSyntaxOn 
 \xpatchcmd{\@xsect}{\@afterheading}
 {\vskip-\parskip\@afterheading}{}{\typeout{Patching~of~\string\@xsect~failed}}
\ExplSyntaxOff 

%    \end{macrocode}
% \end{macro}
% %
% \begin{macro}{\M@sect}
% At least the \Lpack{hyperref} and \Lpack{nameref} packages, and
% possibly other packages,  modify the kernel \cs{@sect} assuming 8 args.
% That's why I've called my version, which has 9 args, something 
% else (i.e., \cs{M@sect}). This version also has the support
% for title referencing. \\
% \cs{M@sect}\marg{name}\marg{level}\marg{indent}\marg{beforeskip}\marg{afterskip}\marg{style}\\ \hspace*{0.5in} \oarg{toc}\oarg{head}\marg{title}
% \changes{v1.4}{2003/11/22}{Added \cs{M@sect}}
% For now we will not add targets for section and friends as hyperref already does.
%    \begin{macrocode}
\def\M@sect#1#2#3#4#5#6[#7][#8]#9{%
  \ifheadnameref\M@gettitle{#8}\else\M@gettitle{#7}\fi
  \ifnum #2>\c@secnumdepth
    \let\@svsec\@empty
    \memsecinfo{#1}{}{#7}{#8}{#9}%
  \else
    \refstepcounter{#1}%
    \protected@edef\@svsec{\@seccntformat{#1}\relax}%
    \memsecinfo{#1}{\@nameuse{the#1}}{#7}{#8}{#9}%
  \fi
  \@tempskipa #5\relax
  \ifdim \@tempskipa>\z@
    \begingroup
      #6{%
      \@hangfrom{\hskip #3\relax\@svsec}%
        \interlinepenalty \@M #9\@@par}%
    \endgroup
    \csname #1mark\endcsname{#8}%
    \addcontentsline{toc}{#1}{%
      \ifnum #2>\c@secnumdepth \else
        \protect\numberline{\csname the#1\endcsname}%
      \fi
      #7}%
  \else
    \def\@svsechd{%
      #6{\hskip #3\relax
     \@svsec #9}%
     \csname #1mark\endcsname{#8}%
     \addcontentsline{toc}{#1}{%
       \ifnum #2>\c@secnumdepth \else
        \protect\numberline{\csname the#1\endcsname}%
       \fi
       #7}}%
  \fi
  \@xsect{#5}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@sect}
% \changes{v3.8}{2023/07/24}{Added patch.}
% The \Lpack{pdfpages} package assumes \cs{@sect} in order to add
% stuff to say \cs{@currentlabelname}. So in case others use it we map \cs{@sect}.
%    \begin{macrocode}
\def\@sect#1#2#3#4#5#6[#7]#8{\M@sect{#1}{#2}{#3}{#4}{#5}{#6}[{#7}][{#7}]{#8}}

%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\@ssect}
% Add hook for name reference to \cs{section*} etc. \\
% \cs{@ssect}\marg{indent}\marg{beforeskip}\marg{afterskip}\marg{style}\marg{title}
% \changes{v1.61803}{2008/01/30}{Used corrected number of arguments to 
%         \cs{memsecstarinfo} in \cs{@ssect} (Gabriel Guernik, mempatch v4.1)}
%    \begin{macrocode}
\let\@mem@old@ssect\@ssect
\def\@ssect#1#2#3#4#5{%
  \M@gettitle{#5}%
  \memsecstarinfo{\m@msecn@me}{#5}%
  \@mem@old@ssect{#1}{#2}{#3}{#4}{#5}}

%    \end{macrocode}
% \end{macro}
%
%
% 
% \begin{macro}{\section}
% A normal heading with white space above and below and no indentation
% of the first paragraph. 
% By default the heading is set in a \verb?\Large\bfseries? font.
%    \begin{macrocode}
\newcommand{\section}{%
  \sechook%
  \@startsection{section}{1}%  level 1
      {\secindent}%            heading indent
      {\beforesecskip}%        skip before the heading
      {\aftersecskip}%         skip after the heading
      {\normalfont\secheadstyle}} % font
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sechook}
% \begin{macro}{\setsechook}
% \cs{sechook} is called at the start of a \cs{section} and 
% \cs{setsechook}\marg{code} redefines it.
%    \begin{macrocode}
\newcommand{\sechook}{}
\newcommand{\setsechook}[1]{\renewcommand{\sechook}{#1}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\secindent}
% \begin{macro}{\beforesecskip}
% \begin{macro}{\aftersecskip}
% \begin{macro}{\secheadstyle}
% \begin{macro}{\setsecindent}
% \begin{macro}{\setbeforesecskip}
% \begin{macro}{\setaftersecskip}
% \begin{macro}{\setsecheadstyle}
% \cs{secindent} is the indentation of the section heading from the left margin,
% \cs{beforesecskip} and \cs{aftersecskip} specify the white space before
% and after the heading, and \cs{secheadstyle} specifies the heading style.
% These are set to the default values for the \Lpack{book} class,
% except that the heading will be \cs{raggedright}, thus preventing
% hyphenation. The
% \cs{set...} commands are for the user to change the values.
% \changes{v1.61803398}{@009/07/17}{Added bidi support to default secheadstyle}
%    \begin{macrocode}
\newlength{\secindent}
\newcommand{\setsecindent}[1]{\setlength{\secindent}{#1}}
  \setsecindent{\z@}
\newskip\beforesecskip
\newcommand{\setbeforesecskip}[1]{\setlength{\beforesecskip}{#1}}
  \setbeforesecskip{-3.5ex \@plus -1ex \@minus -.2ex}
\newskip\aftersecskip
\newcommand{\setaftersecskip}[1]{\setlength{\aftersecskip}{#1}}
  \setaftersecskip{2.3ex \@plus .2ex}
\newcommand{\secheadstyle}{}
\newcommand{\setsecheadstyle}[1]{\renewcommand{\secheadstyle}{#1}}
  \setsecheadstyle{\Large\bfseries\memRTLraggedright}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\subsection}
% A normal heading with white space above and below and no indentation
% of the first paragraph.
% By default the heading is set in a \verb?\large\bfseries? font.
%    \begin{macrocode}
\newcommand{\subsection}{%
  \subsechook%
  \@startsection{subsection}{2}%  level 2
      {\subsecindent}%            heading indent
      {\beforesubsecskip}%        skip before the heading
      {\aftersubsecskip}%         skip after the heading
      {\normalfont\subsecheadstyle}} % font
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\subsechook}
% \begin{macro}{\setsubsechook}
% \cs{subsechook} is called at the start of a \cs{subsection} and 
% \cs{setsubsechook}\marg{code} redefines it.
%    \begin{macrocode}
\newcommand{\subsechook}{}
\newcommand{\setsubsechook}[1]{\renewcommand{\subsechook}{#1}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\subsecindent}
% \begin{macro}{\beforesubsecskip}
% \begin{macro}{\aftersubsecskip}
% \begin{macro}{\subsecheadstyle}
% \begin{macro}{\setsubsecindent}
% \begin{macro}{\setbeforesubsecskip}
% \begin{macro}{\setaftersubsecskip}
% \begin{macro}{\setsubsecheadstyle}
% The macros for controlling \cs{subsection} headings.
% \changes{v1.61803398}{2009/07/17}{Added bidi support to default subsec headstyle}
%    \begin{macrocode}
\newlength{\subsecindent}
\newcommand{\setsubsecindent}[1]{\setlength{\subsecindent}{#1}}
  \setsubsecindent{\z@}
\newskip\beforesubsecskip
\newcommand{\setbeforesubsecskip}[1]{\setlength{\beforesubsecskip}{#1}}
  \setbeforesubsecskip{-3.25ex \@plus -1ex \@minus -.2ex}
\newskip\aftersubsecskip
\newcommand{\setaftersubsecskip}[1]{\setlength{\aftersubsecskip}{#1}}
  \setaftersubsecskip{1.5ex \@plus .2ex}
\newcommand{\subsecheadstyle}{}
\newcommand{\setsubsecheadstyle}[1]{\renewcommand{\subsecheadstyle}{#1}}
  \setsubsecheadstyle{\large\bfseries\memRTLraggedright}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\subsubsection}
% A normal heading with white space above and below and no indentation
% of the first paragraph.
% By default the heading is set in a \verb?\normalsize\bfseries? font.
%    \begin{macrocode}
\newcommand{\subsubsection}{%
  \subsubsechook%
  \@startsection{subsubsection}{3}%  level 3
      {\subsubsecindent}%            heading indent
      {\beforesubsubsecskip}%        skip before the heading
      {\aftersubsubsecskip}%         skip after the heading
      {\normalfont\subsubsecheadstyle}} % font
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\subsubsechook}
% \begin{macro}{\setsubsubsechook}
% \cs{subsubsechook} is called at the start of a \cs{subsubsection} and 
% \cs{setsubsubsechook}\marg{code} redefines it.
%    \begin{macrocode}
\newcommand{\subsubsechook}{}
\newcommand{\setsubsubsechook}[1]{\renewcommand{\subsubsechook}{#1}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\subsubsecindent}
% \begin{macro}{\beforesubsubsecskip}
% \begin{macro}{\aftersubsubsecskip}
% \begin{macro}{\subsubsecheadstyle}
% \begin{macro}{\setsubsubsecindent}
% \begin{macro}{\setbeforesubsubsecskip}
% \begin{macro}{\setaftersubsubsecskip}
% \begin{macro}{\setsubsubsecheadstyle}
% The macros for controlling \cs{subsubsection} headings.
% \changes{v1.61803398}{2009/07/17}{Added bidi support to default subsubsec headstyle}
%    \begin{macrocode}
\newlength{\subsubsecindent}
\newcommand{\setsubsubsecindent}[1]{%
            \setlength{\subsubsecindent}{#1}}
\setsubsubsecindent{\z@}
\newskip\beforesubsubsecskip
\newcommand{\setbeforesubsubsecskip}[1]{%
            \setlength{\beforesubsubsecskip}{#1}}
\setbeforesubsubsecskip{-3.25ex \@plus -1ex \@minus -.2ex}
\newskip\aftersubsubsecskip
\newcommand{\setaftersubsubsecskip}[1]{%
            \setlength{\aftersubsubsecskip}{#1}}
\setaftersubsubsecskip{1.5ex \@plus .2ex}
\newcommand{\subsubsecheadstyle}{}
\newcommand{\setsubsubsecheadstyle}[1]{%
            \renewcommand{\subsubsecheadstyle}{#1}}
\setsubsubsecheadstyle{\normalsize\bfseries\memRTLraggedright}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% 
%
% \begin{macro}{\paragraph}
% A runin heading with white space above and to the right of the heading.
% By default the heading is set in a \verb?\normalsize\bfseries? font.
%    \begin{macrocode}
\newcommand{\paragraph}{%
  \parahook%
  \@startsection{paragraph}{4}%  level 4
      {\paraindent}%            heading indent
      {\beforeparaskip}%        skip before the heading
      {\afterparaskip}%         skip after the heading
      {\normalfont\paraheadstyle}} % font
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\parahook}
% \begin{macro}{\setparahook}
% \cs{parahook} is called at the start of a \cs{paragraph} and 
% \cs{setparahook}\marg{code} redefines it.
%    \begin{macrocode}
\newcommand{\parahook}{}
\newcommand{\setparahook}[1]{\renewcommand{\parahook}{#1}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\paraindent}
% \begin{macro}{\beforeparaskip}
% \begin{macro}{\afterparaskip}
% \begin{macro}{\paraheadstyle}
% \begin{macro}{\setparaindent}
% \begin{macro}{\setbeforeparaskip}
% \begin{macro}{\setafterparaskip}
% \begin{macro}{\setparaheadstyle}
% The macros for controlling \cs{paragraph} headings.
%    \begin{macrocode}
\newlength{\paraindent}
\newcommand{\setparaindent}[1]{\setlength{\paraindent}{#1}}
  \setparaindent{\z@}
\newskip\beforeparaskip
\newcommand{\setbeforeparaskip}[1]{\setlength{\beforeparaskip}{#1}}
  \setbeforeparaskip{3.25ex \@plus 1ex \@minus .2ex}
\newskip\afterparaskip
\newcommand{\setafterparaskip}[1]{\setlength{\afterparaskip}{#1}}
  \setafterparaskip{-1em}
\newcommand{\paraheadstyle}{}
\newcommand{\setparaheadstyle}[1]{\renewcommand{\paraheadstyle}{#1}}
  \setparaheadstyle{\normalsize\bfseries}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% 
%
% \begin{macro}{\subparagraph}
% A runin heading with white space above and to the right of the heading.
% By default the heading is set in a \verb?\normalsize\bfseries? font.
%    \begin{macrocode}
\newcommand{\subparagraph}{%
  \subparahook%
  \@startsection{subparagraph}{5}%  level 5
      {\subparaindent}%            heading indent
      {\beforesubparaskip}%        skip before the heading
      {\aftersubparaskip}%         skip after the heading
      {\normalfont\subparaheadstyle}} % font
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\subparahook}
% \begin{macro}{\setsubparahook}
% \cs{subparahook} is called at the start of a \cs{subparagraph} and 
% \cs{setsubparahook}\marg{code} redefines it.
%    \begin{macrocode}
\newcommand{\subparahook}{}
\newcommand{\setsubparahook}[1]{\renewcommand{\subparahook}{#1}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\subparaindent}
% \begin{macro}{\beforesubparaskip}
% \begin{macro}{\aftersubparaskip}
% \begin{macro}{\subparaheadstyle}
% \begin{macro}{\setsubparaindent}
% \begin{macro}{\setbeforesubparaskip}
% \begin{macro}{\setaftersubparaskip}
% \begin{macro}{\setsubparaheadstyle}
% The macros for controlling \cs{subparagraph} headings.
%    \begin{macrocode}
\newlength{\subparaindent}
\newcommand{\setsubparaindent}[1]{%
            \setlength{\subparaindent}{#1}}
  \setsubparaindent{\parindent}
\newskip\beforesubparaskip
\newcommand{\setbeforesubparaskip}[1]{%
            \setlength{\beforesubparaskip}{#1}}
  \setbeforesubparaskip{3.25ex \@plus 1ex \@minus .2ex}
\newskip\aftersubparaskip
\newcommand{\setaftersubparaskip}[1]{%
            \setlength{\aftersubparaskip}{#1}}
  \setaftersubparaskip{-1em}
\newcommand{\subparaheadstyle}{}
\newcommand{\setsubparaheadstyle}[1]{%
            \renewcommand{\subparaheadstyle}{#1}}
  \setsubparaheadstyle{\normalsize\bfseries}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\sethangfrom}
% The macro \cs{sethangfrom}\marg{code} is a user-level command
% for changing the definition of \cs{@hangfrom}. Use \verb?#1? in \meta{code}
% for the argument to \cs{@hangfrom} (or \verb?##1? if used inside another macro).
% \changes{v0.2}{2001/06/03}{Added \cs{sethangfrom}}
%    \begin{macrocode}
\newcommand{\sethangfrom}[1]{\renewcommand{\@hangfrom}[1]{#1}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\setsecnumformat}
% The macro \cs{setsecnumformat}\marg{code} is a user-level command
% for changing the definition of \cs{@seccntformat}. Use \verb?#1? in \meta{code}
% for the argument to \cs{@seccntformat} (or \verb?##1? if used inside another macro).
% \changes{v0.2}{2001/06/03}{Added \cs{setsecnumformat}}
%    \begin{macrocode}
\newcommand{\setsecnumformat}[1]{\renewcommand{\@seccntformat}[1]{#1}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\hangsecnum}
% \begin{macro}{\defaultsecnum}
% These are declarations for putting sectional numbers in the margin,
% or the default sectional number formatting.
% \changes{v0.2}{2001/06/03}{Added \cs{hangsecnum} and \cs{defaultsecnum}}
%    \begin{macrocode}
\newcommand{\hangsecnum}{%
  \def\@seccntformat##1{\llap{\csname the##1\endcsname\quad}}}
\newcommand{\defaultsecnum}{%
  \def\@seccntformat##1{\csname the##1\endcsname\quad}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \subsubsection{Anonymous headings}
%
% \begin{macro}{\plainbreak}
% \cs{plainbreak}\marg{num} generates \meta{num} blanks lines and
% suppresses the indentation of a following paragraph. The starred
% version, \cs{plainbreak*}, does not suppress paragraph indentation.
% \changes{v0.2}{2001/06/03}{Added starred version of \cs{plainbreak}}
%    \begin{macrocode}
\newcommand{\plainbreak}{\@ifstar{\@spbreak}{\@pbreak}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@pbreak}
% \begin{macro}{\@spbreak}
% These are the internal forms for the two versions of \cs{plainbreak}.
% The code for \cs{@pbreak} is almost a straight copy of code posted to
% \ctt{} by Donald Arseneau on 2001/03/26.
%    \begin{macrocode}
\newcommand*{\@pbreak}[1]{\par
  \penalty -100
  \vskip #1\onelineskip \@plus 2\onelineskip
  \penalty -20
  \vskip \z@ \@plus -2\onelineskip
  \@afterindentfalse
  \@afterheading}
\newcommand*{\@spbreak}[1]{\par
  \penalty -100
  \vskip #1\onelineskip \@plus 2\onelineskip
  \penalty -20
  \vskip \z@ \@plus -2\onelineskip
  \@afterindenttrue
  \@afterheading}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\fancybreak}
% \cs{fancybreak}\marg{text} typesets \meta{text} centered. For example,
% \verb?\fancybreak{{*}\\{* * *}\\{*}}?. It suppresses indentation of the 
% following paragraph. The starred version leaves indentation as is.
% \changes{v0.2}{2001/06/03}{Added starred version of \cs{fancybreak}}
% \changes{v1.3}{2002/11/14}{Tweaked \cs{fancybreak} to remove underfull hbox}
% \changes{v1.61803}{2008/01/30}{Changed fancybreak code to end the paragraph
%                   it started (Dan Leucking mempatch v4.5)}
%    \begin{macrocode}
\newcommand{\fancybreak}{\@ifstar{\@sfbreak}{\@fbreak}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@fbreak}
% \begin{macro}{\@sfbreak}
% These are the internal forms for the two versions of \cs{fancybreak}.
%    \begin{macrocode}
\newcommand{\@fbreak}[1]{\par
  \penalty -100
  \noindent\parbox{\linewidth}{\centering #1}%%\null
  \par
%%  \penalty -20
%%  \vskip -\onelineskip
  \@afterindentfalse
  \@afterheading}
\newcommand{\@sfbreak}[1]{\par
  \penalty -100
  \noindent\parbox{\linewidth}{\centering #1}%%\null
  \par
%%  \penalty -20
%%  \vskip -\onelineskip
  \@afterindenttrue
  \@afterheading}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\plainfancybreak}
% The \cs{plainfancybreak}\marg{space}\marg{num}\marg{text} acts
% like \cs{plainbreak}\marg{num} in the middle of a page and like
% \cs{fancybreak}\marg{text} at the bottom of a page. The \meta{space}
% argument is the vertical space required for the \meta{num} blank lines
% and some additional lines of text. From experiments, it seems that
% \meta{space} should be at least (3+\meta{num}) lines (\cs{onelineskip}).
% There is also a starred version, \cs{plainfancybreak*}, to match the other
% starred break commands.
% \changes{v0.2}{2001/06/03}{Added \cs{plainfancybreak} and supporting macros}
%    \begin{macrocode}
\newcommand{\plainfancybreak}{\@ifstar{\@spfbreak}{\@pfbreak}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@pfbreak}
% \begin{macro}{\@spfbreak}
% These are the internal macros for the unstarred and starred versions
% of \cs{plainfancybreak}. They essentially do the same thing, except they call, 
% respectively, the unstarred and starred internal versions of \cs{plainbreak}
% and \cs{fancybreak}. The code for checking the amount of space left on the
% page is from an early, and abandoned, version of the code for \cs{needspace}.
%    \begin{macrocode}
\newcommand{\@pfbreak}[3]{\par
  \@tempdimc\pagegoal \advance\@tempdimc-\pagetotal
  \ifdim #1>\@tempdimc \@fbreak{#3}\else \@pbreak{#2}\fi}
\newcommand{\@spfbreak}[3]{\par
  \@tempdimc\pagegoal \advance\@tempdimc-\pagetotal
  \ifdim #1>\@tempdimc \@sfbreak{#3}\else \@spbreak{#2}\fi}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% From the thread \textit{Customizing section hooks in memoir.cls} on \ctt{}
% in October 2002 it appeared that \cs{plainfancybreak} may be fragile.
% Donald Arseneau said that \cs{plainfancybreak} guessed at the amount
% of space available and gave code based on a modified output routine
% to make it more robust. The following code is based on that thread.
% \changes{v1.3}{2002/11/14}{Added lots of code for new \cs{pfbreak}}
%
% \begin{macro}{\pen@ltyabovepfbreak}
% \begin{macro}{\pen@ltybelowpfbreak}
% Penalities for communication with the output routine.
%    \begin{macrocode}
\newcommand*{\pen@ltyabovepfbreak}{2}
\newcommand*{\pen@ltybelowpfbreak}{-4}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\pfbreakskip}
% The vertical space taken by the plain and fancy breaks.
%    \begin{macrocode}
\newlength{\pfbreakskip}
  \setlength{\pfbreakskip}{2\baselineskip}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\pfbreakdisplay}
% This is the fancybreak display, which must fit into \cs{pfbreakskip}
% vertical space.
%    \begin{macrocode}
\newcommand{\pfbreakdisplay}{*\quad*\quad*}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\pfbre@kdispl@y}
% Typesets \cs{pfbreakdisplay} vertically and horizontally centered.
%    \begin{macrocode}
\def\pfbre@kdispl@y{\vbox to 1\pfbreakskip{\vss
  \hb@xt@ \columnwidth{\hss \pfbreakdisplay \hss}%
  \vss}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\nopfbreakOutput}
% Save the current output routine.
%    \begin{macrocode}
\edef\nopfbreakOutput{\the\output}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\pfbreakOutput}
% Special output to handle the \cs{pfbreak}.
%    \begin{macrocode}
\def\pfbreakOutput{%
  \ifnum\outputpenalty=\pen@ltyabovepfbreak
    \nopfbreakOutput
    \pfbre@kdispl@y
    \nobreak
    \vskip-\pfbreakskip
  \else\ifnum\outputpenalty=\pen@ltybelowpfbreak
    \unvbox 255\relax
    \nobreak
    \vskip-\pfbreakskip
    \pfbre@kdispl@y
    \break
  \else
    \nopfbreakOutput
  \fi
  \fi}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\output}
% Use the new \cs{pfbreak} output routine.
%    \begin{macrocode}
\output={\pfbreakOutput}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\pfbreak}
% Typesets a plain break in the middle of the page, otherwise
% a fancybreak at either the bottom or top of the page.
%    \begin{macrocode}
\newcommand{\pfbreak}{\@ifstar{\@spfbreakgap}{\@pfbreakgap}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@pfbreakgap}
% Unstarred version of \cs{pfbreak}.
% \changes{v3.6h}{2010/10/06}{fixed \cs{@pfbreakgab} kudos to DA for
% the fix}
%    \begin{macrocode}
\newcommand{\@pfbreakgap}{%
  \par {%
  \skip@\lastskip
  \nobreak
  \vskip -\ifdim\prevdepth>\maxdepth \maxdepth
          \else\ifdim\prevdepth>-1000pt\prevdepth
            \else\ifinner 0pt
              \else \pagedepth
          \fi \fi \fi
  \vskip -\skip@
  \ifdim\skip@<\pfbreakskip
    \advance\skip@ -1\skip@ \advance\skip@ 1\pfbreakskip
  \fi
  \penalty\pen@ltyabovepfbreak
  \prevdepth\z@ % added
  \vskip\skip@
  \penalty\pen@ltybelowpfbreak
  }
  \@afterindentfalse
  \@afterheading
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@spfbreakgap}
% Starred version of \cs{pfbreak}.
% \changes{v3.6h}{2010/10/06}{fixed \cs{@pfbreakgab} kudos to DA for
% the fix}
%    \begin{macrocode}
\newcommand{\@spfbreakgap}{%
  \par {%
  \skip@\lastskip
  \nobreak
  \vskip -\ifdim\prevdepth>\maxdepth \maxdepth
          \else\ifdim\prevdepth>-1000pt\prevdepth
            \else\ifinner 0pt
              \else \pagedepth
          \fi \fi \fi
  \vskip -\skip@
  \ifdim\skip@<\pfbreakskip
    \advance\skip@ -1\skip@ \advance\skip@ 1\pfbreakskip
  \fi
  \penalty\pen@ltyabovepfbreak
  \prevdepth\z@ % added
  \vskip\skip@
  \penalty\pen@ltybelowpfbreak
  }
  \@afterindenttrue
  \@afterheading
}

%    \end{macrocode}
% \end{macro}
%
%
%    While on the subject of breaks\ldots
%
% \begin{macro}{\noprelistbreak}
% Putting this immediately before a list (e.g., \Lenv{itemize}) should
% prevent a page break at that point.
% \changes{v1.2}{2002/07/27}{Added \cs{noprelistbreak}}
%    \begin{macrocode}
\newcommand*{\noprelistbreak}{\@nobreaktrue\nopagebreak}

%    \end{macrocode}
% \end{macro}
%
% \subsection{Division head styles}
%
%   The styles of the division heads should go together. As an aid the
% class supplies some ready made collections.
% \changes{v1.6180}{2008/01/30}{Added division head styles}
%
% \begin{macro}{\makeheadstyles}
% \begin{macro}{\headstyles}
% \begin{macro}{\@hds@def@ult}
% \begin{macro}{\hds@default}
% \cs{makeheadstyles}\marg{name}\marg{code} creates the \meta{name} collection 
% of division head styles, defined by \meta{code}. \cs{headstyles}\marg{name}
% makes the \meta{name} division head styles the current styles.
%    \begin{macrocode}
\newcommand{\makeheadstyles}[2]{%
  \@namedef{hds@#1}{\@hds@def@ult #2}}
\newcommand*{\headstyles}[1]{\@nameuse{hds@#1}}
%    \end{macrocode}
% \cs{@hds@def@ult} is the default set of division head styles.
%    \begin{macrocode}
\newcommand*{\@hds@def@ult}{%
% Default \cs{book} style
%    \begin{macrocode}
% book
  \renewcommand*{\beforebookskip}{\null\vfil}%
  \renewcommand*{\midbookskip}{\par\vskip 20pt}%
  \renewcommand*{\afterbookskip}{\vfil\newpage}%
  \renewcommand*{\booknamefont}{\normalfont\huge\bfseries}%
  \renewcommand*{\booknumfont}{\normalfont\huge\bfseries}%
  \renewcommand*{\booktitlefont}{\normalfont\Huge\bfseries}%
  \renewcommand*{\printbookname}{\booknamefont \bookname}%
  \renewcommand*{\booknamenum}{\space}%
  \renewcommand*{\printbooknum}{\booknumfont \thebook}%
  \renewcommand*{\printbooktitle}[1]{\booktitlefont{##1}}%
%    \end{macrocode}
% Default \cs{part} style
%    \begin{macrocode}
% part
  \renewcommand*{\beforepartskip}{\null\vfil}%
  \renewcommand*{\midpartskip}{\par\vskip 20pt}%
  \renewcommand*{\afterpartskip}{\vfil\newpage}%
  \renewcommand*{\partnamefont}{\normalfont\huge\bfseries}%
  \renewcommand*{\partnumfont}{\normalfont\huge\bfseries}%
  \renewcommand*{\parttitlefont}{\normalfont\Huge\bfseries}%
  \renewcommand*{\printpartname}{\partnamefont \partname}%
  \renewcommand*{\partnamenum}{\space}%
  \renewcommand*{\printpartnum}{\partnumfont \thepart}%
  \renewcommand*{\printparttitle}[1]{\parttitlefont{##1}}%
%    \end{macrocode}
% Default \cs{chapter} style.
%    \begin{macrocode}
  \@chs@def@ult%               default chapterstyle
%    \end{macrocode}
% Default \cs{section} style
% \changes{v1.61803398}{2009/07/17}{Added bidi support to default sec headstyle}
%    \begin{macrocode}
% section
  \setsechook{}
  \setsecindent{\z@}%
  \setbeforesecskip{-3.5ex \@plus -1ex \@minus -.2ex}%
  \setaftersecskip{2.3ex \@plus .2ex}%
  \setsecheadstyle{\Large\bfseries\memRTLraggedright}%
%    \end{macrocode}
% Default \cs{subsection} style
% \changes{v1.61803398}{2009/07/17}{Added bidi support to default subsec headstyle}
%    \begin{macrocode}
% subsection
  \setsubsechook{}%
  \setsubsecindent{\z@}%
  \setbeforesubsecskip{-3.25ex \@plus -1ex \@minus -.2ex}%
  \setaftersubsecskip{1.5ex \@plus .2ex}%
  \setsubsecheadstyle{\large\bfseries\memRTLraggedright}%
%    \end{macrocode}
% Default \cs{subsubsection} style
% \changes{v1.61803398}{2009/07/17}{Added bidi support to default subsubsec headstyle}
%    \begin{macrocode}
% subsubsection
  \setsubsubsechook{}%
  \setsubsubsecindent{\z@}%
  \setbeforesubsubsecskip{-3.25ex \@plus -1ex \@minus -.2ex}%
  \setaftersubsubsecskip{1.5ex \@plus .2ex}%
  \setsubsubsecheadstyle{\normalsize\bfseries\memRTLraggedright}%
%    \end{macrocode}
% Default \cs{paragraph} style
%    \begin{macrocode}
% paragraph
  \setparahook{}%
  \setparaindent{\z@}%
  \setbeforeparaskip{3.25ex \@plus 1ex \@minus .2ex}%
  \setafterparaskip{-1em}%
  \setparaheadstyle{\normalsize\bfseries}%
%    \end{macrocode}
% Default \cs{paragraph} style
%    \begin{macrocode}
% subparagraph
  \setsubparahook{}%
  \setsubparaindent{\parindent}%
  \setbeforesubparaskip{3.25ex \@plus 1ex \@minus .2ex}%
  \setaftersubparaskip{-1em}%
  \setsubparaheadstyle{\normalsize\bfseries}}

%    \end{macrocode}
% Set up and use the default head styles
%    \begin{macrocode}
\makeheadstyles{default}{}
\headstyles{default}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\addperiod}
% Puts a period at the end of its argument.
%    \begin{macrocode}
\newcommand*{\addperiod}[1]{#1.}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\hds@memman}
% Head styles used in the \textit{The Memoir Class} user guide. In this,
% as the later ones, only changes from the defaults need specifying.
% \changes{v1.61803398}{2009/07/17}{Added bidi support to the memman headstyles}
%    \begin{macrocode}
\makeheadstyles{memman}{%
% book changes
  \renewcommand*{\booknamefont}{\normalfont\huge\sffamily}
  \renewcommand*{\booknumfont}{\normalfont\huge\sffamily}
  \renewcommand*{\booktitlefont}{\normalfont\Huge\sffamily}
  \renewcommand*{\midbookskip}{\par\vskip 2\onelineskip}%
% part changes
  \renewcommand*{\partnamefont}{\normalfont\huge\sffamily}
  \renewcommand*{\partnumfont}{\normalfont\huge\sffamily}
  \renewcommand*{\parttitlefont}{\normalfont\Huge\sffamily}
  \renewcommand*{\midpartskip}{\par\vskip 2\onelineskip}%
% chapter
  \chapterstyle{demo3}
% section
  \setbeforesecskip{-1.333\onelineskip 
                    \@plus -0.5\onelineskip \@minus -.5\onelineskip}%
  \setaftersecskip{0.667\onelineskip \@plus 0.1\onelineskip}%
  \setsecheadstyle{\normalfont\scshape\memRTLraggedright}%
% subsection
  \setbeforesubsecskip{-0.667\onelineskip 
                       \@plus -0.25\onelineskip \@minus -0.25\onelineskip}%
  \setaftersubsecskip{0.333\onelineskip \@plus 0.1\onelineskip}%
  \setsubsecheadstyle{\normalfont\bfseries\memRTLraggedright}%
% subsubsection
  \setbeforesubsubsecskip{-0.667\onelineskip 
                          \@plus -0.25\onelineskip \@minus -0.25\onelineskip}%
  \setaftersubsubsecskip{0.333\onelineskip \@plus 0.1\onelineskip}%
  \setsubsubsecheadstyle{\normalfont\normalsize\itshape\memRTLraggedright}%
% paragraph
  \setbeforeparaskip{1.0\onelineskip 
                     \@plus 0.5\onelineskip \@minus 0.2\onelineskip}%
  \setafterparaskip{-1em}%
  \setparaheadstyle{\normalfont\normalsize\itshape\addperiod}%
% subparagraph
  \setsubparaindent{\parindent}%
  \setbeforesubparaskip{1.0\onelineskip 
                        \@plus 0.5\onelineskip \@minus 0.2\onelineskip}%
  \setaftersubparaskip{-1em}%
  \setsubparaheadstyle{\normalfont\normalsize\itshape\addperiod}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\hds@bringhurst}
% Head styles based on Bringhurst's book
% \changes{v1.61803398}{2009/07/17}{Added bidi support to bringhurst headstyles}
% \changes{c3.6k}{2012/09/18}{\cs{MakeLowercase} $\to$ \cs{MakeTextLowercase}}
% \changes{v3.8.4}{2025/08/08}{Reverted \cs{Make...case} change}
%    \begin{macrocode}
\makeheadstyles{bringhurst}{%
% chapter
\chapterstyle{bringhurst}
% section
  \setbeforesecskip{-1\onelineskip 
                    \@plus -0.5\onelineskip \@minus -.5\onelineskip}%
  \setaftersecskip{1\onelineskip \@plus 0.1\onelineskip}%
  \setsecheadstyle{\normalfont\memRTLraggedright\scshape\MakeLowercase}%
% subsection
  \setbeforesubsecskip{-1.0\onelineskip 
                       \@plus -0.25\onelineskip \@minus -0.25\onelineskip}%
  \setaftersubsecskip{1.0\onelineskip \@plus 0.1\onelineskip}%
  \setsubsecheadstyle{\sethangfrom{\noindent ####1}\normalfont\itshape\memRTLraggedright}%
% subsubsection
  \setbeforesubsubsecskip{1.0\onelineskip 
                          \@plus 0.5\onelineskip \@minus 0.2\onelineskip}%
  \setaftersubsubsecskip{-1em}%
  \setsubsubsecheadstyle{\normalfont\normalsize\scshape\MakeLowercase}%
% paragraph
  \setbeforeparaskip{1.0\onelineskip 
                     \@plus 0.5\onelineskip \@minus 0.2\onelineskip}%
  \setafterparaskip{-1em}%
  \setparaheadstyle{\normalfont\normalsize\itshape\addperiod}%
% subparagraph
  \setsubparaindent{\parindent}%
  \setbeforesubparaskip{1.0\onelineskip 
                        \@plus 0.5\onelineskip \@minus 0.2\onelineskip}%
  \setaftersubparaskip{-1em}%
  \setsubparaheadstyle{\normalfont\normalsize\itshape\addperiod}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\hds@crosshead}
% Head styles based on one of Bringhurst's suggestions.
% \changes{c3.6k}{2012/09/18}{\cs{MakeUppercase} $\to$ \cs{MakeTextUppercase}}
% \changes{v3.8.4}{2025/08/08}{Reverted \cs{Make...case} change}
%    \begin{macrocode}
\makeheadstyles{crosshead}{%
  \chapterstyle{crosshead}
% section
  \setbeforesecskip{-1.25\onelineskip 
                    \@plus -0.5\onelineskip \@minus -.5\onelineskip}%
  \setaftersecskip{0.75\onelineskip \@plus 0.1\onelineskip}%
  \setsecheadstyle{\normalfont\centering\MakeUppercase}%
% subsection
  \setbeforesubsecskip{-1.25\onelineskip 
                       \@plus -0.25\onelineskip \@minus -0.25\onelineskip}%
  \setaftersubsecskip{0.75\onelineskip \@plus 0.1\onelineskip}%
  \setsubsecheadstyle{\normalfont\centering\bfseries}%
% subsubsection
  \setbeforesubsubsecskip{-.667\onelineskip 
                          \@plus -0.25\onelineskip \@minus -0.25\onelineskip}%
  \setaftersubsubsecskip{.333\onelineskip \@plus 0.1\onelineskip}%
  \setsubsubsecheadstyle{\normalfont\normalsize\centering\scshape\MakeLowercase}%
% paragraph
  \setbeforeparaskip{-.667\onelineskip 
                     \@plus -02.5\onelineskip \@minus -0.25\onelineskip}%
  \setafterparaskip{.333\onelineskip \@plus 0.1\onelineskip}%
  \setparaheadstyle{\normalfont\normalsize\centering\itshape}%
% subparagraph
  \setsubparaindent{\parindent}%
  \setbeforesubparaskip{1.0\onelineskip 
                        \@plus 0.5\onelineskip \@minus 0.2\onelineskip}%
  \setaftersubparaskip{-1em}%
  \setsubparaheadstyle{\normalfont\normalsize\scshape\MakeLowercase}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\hds@dowding}
% Head styles based on Dowding's \textit{Finer Points}.
% \changes{c3.6k}{2012/09/18}{\cs{MakeUppercase} $\to$ \cs{MakeTextUppercase}}
% \changes{c3.6k}{2012/09/18}{\cs{MakeLowercase} $\to$ \cs{MakeTextLowercase}}
% \changes{v3.8.4}{2025/08/08}{Reverted \cs{Make...case} change}
%    \begin{macrocode}
\makeheadstyles{dowding}{%
% chapter
  \chapterstyle{dowding}
% section
  \setbeforesecskip{-2\onelineskip 
                    \@plus -0.5\onelineskip \@minus -.5\onelineskip}%
  \setaftersecskip{1\onelineskip \@plus 0.1\onelineskip}%
  \setsecheadstyle{\normalfont\centering\MakeUppercase}%
% subsection
  \setbeforesubsecskip{-1.2\onelineskip 
                       \@plus -0.25\onelineskip \@minus -0.25\onelineskip}%
  \setaftersubsecskip{0.8\onelineskip \@plus 0.1\onelineskip}%
  \setsubsecheadstyle{\normalfont\scshape\centering\MakeLowercase}%
% subsubsection
  \setbeforesubsubsecskip{-0.667\onelineskip 
                          \@plus -0.25\onelineskip \@minus -0.25\onelineskip}%
  \setaftersubsubsecskip{0.333\onelineskip \@plus 0.1\onelineskip}%
  \setsubsubsecheadstyle{\normalfont\normalsize\centering\itshape}%
% paragraph
  \setbeforeparaskip{1.0\onelineskip 
                     \@plus 0.5\onelineskip \@minus 0.2\onelineskip}%
  \setafterparaskip{-1em}%
  \setparaheadstyle{\normalfont\normalsize\itshape\addperiod}%
% subparagraph
  \setsubparaindent{\parindent}%
  \setbeforesubparaskip{1.0\onelineskip 
                        \@plus 0.5\onelineskip \@minus 0.2\onelineskip}%
  \setaftersubparaskip{-1em}%
  \setsubparaheadstyle{\normalfont\normalsize\itshape\addperiod}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\hds@komalike}
% Head styles based on KOMA script classes (\texttt{scrbook.cls}).
% \changes{v1.61803398}{2009/07/17}{Added bidi support to komalike headstyles}
%    \begin{macrocode}
\makeheadstyles{komalike}{%
% part
  \renewcommand*{\partnamefont}{\huge\sffamily\bfseries}%
  \renewcommand*{\partnumfont}{\huge\sffamily\bfseries}%
  \renewcommand*{\parttitlefont}{\huge\sffamily\bfseries}%
% chapter
  \chapterstyle{komalike}
% section
  \setbeforesecskip{-3.5ex \@plus -1ex \@minus -.2ex}%
  \setaftersecskip{2.3ex \@plus .2ex}%
  \setsecheadstyle{\normalfont\Large\sffamily\bfseries\memRTLraggedright}%
% subsection
  \setbeforesubsecskip{-3.25ex \@plus -1ex \@minus -.2ex}%
  \setaftersubsecskip{1.5ex \@plus .2ex}%
  \setsubsecheadstyle{\normalfont\large\sffamily\bfseries\memRTLraggedright}%
% subsubsection
  \setbeforesubsubsecskip{-3.25ex \@plus -1ex \@minus -.2ex}%
  \setaftersubsubsecskip{1.5ex \@plus .2ex}%
  \setsubsubsecheadstyle{\normalfont\normalsize\sffamily\bfseries\memRTLraggedright}%
% paragraph
  \setbeforeparaskip{3.25ex \@plus 1ex \@minus .2ex}%
  \setafterparaskip{-1em}%
  \setparaheadstyle{\normalfont\normalsize\sffamily\bfseries}%
% subparagraph
  \setsubparaindent{\parindent}%
  \setbeforesubparaskip{3.25ex \@plus 1ex \@minus .2ex}%
  \setaftersubparaskip{-1em}%
  \setsubparaheadstyle{\normalfont\normalsize\sffamily\bfseries}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\hds@ntglike}
% Head styles based on the NTG classes (\texttt{boek.cls}).
% \changes{c3.6k}{2012/09/18}{\cs{MakeUppercase} $\to$ \cs{MakeTextUppercase}}
% \changes{v3.8.4}{2025/08/08}{Reverted \cs{Make...case} change}
%    \begin{macrocode}
\makeheadstyles{ntglike}{%
% part
  \renewcommand*{\partnamefont}{\Large\bfseries\MakeUppercase}%
  \renewcommand*{\partnumfont}{\Large\bfseries}%
  \renewcommand*{\parttitlefont}{\Large\MakeUppercase}%
% chapter
  \chapterstyle{ntglike}
% section
  \setbeforesecskip{-2\onelineskip 
                    \@plus -1\onelineskip \@minus -.5\onelineskip}%
  \setaftersecskip{0.5\onelineskip}%
  \setsecheadstyle{\normalfont\large\bfseries}%
% subsection
  \setbeforesubsecskip{-1\onelineskip 
                       \@plus -.5\onelineskip \@minus -.25\onelineskip}%
  \setaftersubsecskip{0.01\onelineskip}%
  \setsubsecheadstyle{\normalfont\normalsize\bfseries}%
% subsubsection
  \setbeforesubsubsecskip{-1\onelineskip 
                          \@plus -.5\onelineskip \@minus -.25\onelineskip}%
  \setaftersubsubsecskip{0.01\onelineskip}%
  \setsubsubsecheadstyle{\normalfont\normalsize\slshape}%
% paragraph
  \setbeforeparaskip{3.25ex \@plus 1ex \@minus .2ex}%
  \setafterparaskip{-1em}%
  \setparaheadstyle{\normalfont\normalsize\slshape}%
% subparagraph
  \setsubparaindent{\parindent}%
  \setbeforesubparaskip{3.25ex \@plus 1ex \@minus .2ex}%
  \setaftersubparaskip{-1em}%
  \setsubparaheadstyle{\normalfont\normalsize\slshape}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\hds@tandh}
% Head styles based on Thames \& Hudson \textit{Typography}.
% \changes{v1.61803398}{2009/07/17}{Added bidi support to tandh headstyles}
% \changes{c3.6k}{2012/09/18}{\cs{MakeUppercase} $\to$ \cs{MakeTextUppercase}}
% \changes{v3.8.4}{2025/08/08}{Reverted \cs{Make...case} change}
%    \begin{macrocode}
\makeheadstyles{tandh}{%
% chapter
  \chapterstyle{tandh}
% section
  \setbeforesecskip{-2\onelineskip 
                    \@plus -0.5\onelineskip \@minus -.5\onelineskip}%
  \setaftersecskip{1\onelineskip \@plus 0.1\onelineskip}%
  \setsecheadstyle{\normalfont\memRTLraggedright\MakeUppercase}%
% subsection
  \setbeforesubsecskip{-1.2\onelineskip 
                       \@plus -0.25\onelineskip \@minus -0.25\onelineskip}%
  \setaftersubsecskip{0.8\onelineskip \@plus 0.1\onelineskip}%
  \setsubsecheadstyle{\normalfont\Large\itshape\memRTLraggedright}%
% subsubsection
  \setbeforesubsubsecskip{-0.667\onelineskip 
                          \@plus -0.25\onelineskip \@minus -0.25\onelineskip}%
  \setaftersubsubsecskip{0.333\onelineskip \@plus 0.1\onelineskip}%
  \setsubsubsecheadstyle{\normalfont\normalsize\bfseries\memRTLraggedright}%
% paragraph
  \setbeforeparaskip{1.0\onelineskip 
                     \@plus 0.5\onelineskip \@minus 0.2\onelineskip}%
  \setafterparaskip{-1em}%
  \setparaheadstyle{\normalfont\normalsize\itshape\addperiod}%
% subparagraph
  \setsubparaindent{\parindent}%
  \setbeforesubparaskip{1.0\onelineskip 
                        \@plus 0.5\onelineskip \@minus 0.2\onelineskip}%
  \setaftersubparaskip{-1em}%
  \setsubparaheadstyle{\normalfont\normalsize\itshape\addperiod}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\hds@wilsondob}
% Head styles based on Adrian Wilson's \textit{The Design of Books}.
% \changes{v1.61803398}{2009/07/17}{Added bidi support to wilsondob headstyles}
% \changes{c3.6k}{2012/09/18}{\cs{MakeUppercase} $\to$ \cs{MakeTextUppercase}}
% \changes{v3.8.4}{2025/08/08}{Reverted \cs{Make...case} change}
%    \begin{macrocode}
\makeheadstyles{wilsondob}{%
% chapter
  \chapterstyle{wilsondob}
% section
  \setbeforesecskip{-1.333\onelineskip 
                    \@plus -0.5\onelineskip \@minus -.5\onelineskip}%
  \setaftersecskip{0.667\onelineskip \@plus 0.1\onelineskip}%
  \setsecheadstyle{\normalfont\memRTLraggedright\MakeUppercase}%
% subsection
  \setbeforesubsecskip{-0.667\onelineskip 
                       \@plus -0.25\onelineskip \@minus -0.25\onelineskip}%
  \setaftersubsecskip{0.333\onelineskip \@plus 0.1\onelineskip}%
  \setsubsecheadstyle{\normalfont\Large\itshape\memRTLraggedright}%
% subsubsection
  \setbeforesubsubsecskip{-0.667\onelineskip 
                          \@plus -0.25\onelineskip \@minus -0.25\onelineskip}%
  \setaftersubsubsecskip{0.333\onelineskip \@plus 0.1\onelineskip}%
  \setsubsubsecheadstyle{\normalfont\normalsize\memRTLraggedright\scshape\MakeLowercase}%
% paragraph
  \setbeforeparaskip{1.0\onelineskip 
                     \@plus 0.5\onelineskip \@minus 0.2\onelineskip}%
  \setafterparaskip{-1em}%
  \setparaheadstyle{\normalfont\normalsize\itshape\addperiod}%
% subparagraph
  \setsubparaindent{\parindent}%
  \setbeforesubparaskip{1.0\onelineskip 
                        \@plus 0.5\onelineskip \@minus 0.2\onelineskip}%
  \setaftersubparaskip{-1em}%
  \setsubparaheadstyle{\normalfont\normalsize\itshape\addperiod}}

%    \end{macrocode}
% \end{macro}
%
%
% \subsection{Appendices}
%
% \begin{macro}{\ifanappendix}
% \begin{macro}{\anappendixtrue}
% \begin{macro}{\anappendixfalse}
% \begin{macro}{\appendix}
% In the standard \Lpack{book} class the \cs{appendix} command does the 
% following:
%    \begin{itemize}
%    \item Resets the chapter and section counters to zero
%    \item Sets \cs{@chapapp} to \cs{appendixname}.
%    \item Redefines \cs{thechapter} to produce alphabetic appendix numbers.
%    \end{itemize}
% \changes{v1.618}{2005/09/03}{Added \cs{ifanappendix} (mempatch v3.12)}
%    \begin{macrocode}
\newif\ifanappendix
  \anappendixfalse
\newcommand{\appendix}{\par
  \setcounter{chapter}{0}%
  \setcounter{section}{0}%
  \gdef\@chapapp{\appendixname}%
  \gdef\thechapter{\@Alph\c@chapter}%
  \anappendixtrue}

%    \end{macrocode}
% \end{macro}  
% \end{macro}  
% \end{macro}  
% \end{macro}  
%
%
% This class provides additional appendixing capabilities.
%
%
% \begin{macro}{\appendixpage}
% \begin{macro}{\appendixpage*}
% The command to typeset a page announcing the start of the appendices.
% It is based on the \cs{part} definition. The normal version
% makes an entry in the ToC but the starred version does not.
% \changes{v0.33}{2001/08/31}{Changed implementation of \cs{appendixpage}}
%    \begin{macrocode}
\newcommand{\appendixpage}{%
  \@ifstar{\@sapppage}{\@apppage}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\memapppageinfo}
% \begin{macro}{\memapppagestarinfo}
% \verb?\memapppageinfo{\appendixpagename}? \\
% \verb?\memapppagestarinfo{\appendixpagename}? \\
%    \begin{macrocode}
\newcommand{\memapppageinfo}[1]{}
\newcommand{\memapppagestarinfo}[1]{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@apppage}
% \cs{@apppage} typesets an appendix page and makes an entry in the ToC.
% \changes{v3.6k}{2013/04/25}{Added \cs{mempre/postaddchaptertotochook}}
%    \begin{macrocode}
\def\@apppage{%
  \@setuppart
  \mempreaddapppagetotochook
  \addappheadtotoc
  \mempostaddapppagetotochook
  \partmark{\appendixpagename}%
  \memapppageinfo{\appendixpagename}%
  {\centering
   \interlinepenalty \@M
   \normalfont
   \printparttitle{\appendixpagename}\par}%
  \@endpart}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\mempreaddapppagetotochook}
% \begin{macro}{\mempostaddapppagetotochook}
%   Hooks before and after adding something to the ToC. Does nothing
%   by default.
%    \begin{macrocode}
\newcommand\mempreaddapppagetotochook{}
\newcommand\mempostaddapppagetotochook{}

%    \end{macrocode}
%   
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@sapppage}
% \cs{@sapppage} typesets an appendix page and does not make an entry in the ToC.
%    \begin{macrocode}
\def\@sapppage{%
  \@setuppart
  \partmark{\appendixpagename}%
  \memapppagestarinfo{\appendixpagename}%
  {\centering
   \interlinepenalty \@M
   \normalfont
   \printparttitle{\appendixpagename}\par}%
  \@endpart}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\addappheadtotoc}
% This command adds an `appendices' line to the ToC. The style is the same
% as used in \Lpack{tocbibind} for the `List of figures' line. That is,
% as a Chapter heading.
% \changes{v1.61803}{2008/01/30}{Added \cs{phantomsection} to \cs{addappheadtotoc}
%                    (mempatch v4.9)}
% \changes{v3.8.4}{2025/09/16}{Replaced \cs{phantomsection} by \cs{MakeLinkTarget}}
%    \begin{macrocode}
\def\addappheadtotoc{%
  % \phantomsection
  \MakeLinkTarget[chapter]{}%
  \addcontentsline{toc}{chapter}{\appendixtocname}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@ppsavesec}
% \begin{macro}{\@pprestoresec}
% \begin{macro}{\@ppsaveapp}
% \begin{macro}{\restoreapp}
%  For the \Lenv{appendices} environment we need to save and restore the
% main document division number and the appendix number. The \cs{restoreapp}
% command is the one for the user.
%    \begin{macrocode}
\newcounter{@ppsavesec}
\newcounter{@ppsaveapp}
\setcounter{@ppsaveapp}{0}
\newcommand{\@ppsavesec}{%
  \setcounter{@ppsavesec}{\value{chapter}}}
\newcommand{\@pprestoresec}{%
  \setcounter{chapter}{\value{@ppsavesec}}}
\newcommand{\@ppsaveapp}{%
  \setcounter{@ppsaveapp}{\value{chapter}}}
\newcommand{\restoreapp}{%
  \setcounter{chapter}{\value{@ppsaveapp}}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\@resets@pp}
% Resets the appropriate sectioning counters and names. This does almost
% exactly what the default \cs{appendix} command does, except that it saves and 
% restores sectional numbering. It saves the sectional number at the start
% and restores the appendix number at the end.
%    \begin{macrocode}
% \changes{v3.7p}{2021/06/16}{Moved \cs{theHchapter} def here from
% \Lpack{memhfixc}. (discovered by Lars Hoemke, private email 20 Feb 2003)}
\newcommand{\@resets@pp}{%
  \par
  \@ppsavesec
  \setcounter{section}{0}%
  \setcounter{chapter}{0}%
  \renewcommand\@chapapp{\appendixname}%
  \renewcommand\thechapter{\@Alph\c@chapter}%
  \restoreapp
  \def\theHchapter{\Alph{chapter}}
}

%    \end{macrocode}
% \end{macro}
%
% \begin{environment}{appendices}
%  This is the heart of the package. Start it off by doing the resetting
% done by the \cs{appendix} command but also save the main counters. At the
% end of the environment save the appendix number and restore the main counters.
%    \begin{macrocode}
\newenvironment{appendices}%
  {\@resets@pp\anappendixtrue}%
  {\@ppsaveapp\@pprestoresec\anappendixfalse}

%    \end{macrocode}
% \end{environment}
%
% \begin{macro}{\setthesection}
% The user commands for specifying the numbering style for subappendices.
%    \begin{macrocode}
\newcommand{\setthesection}{\thechapter.\Alph{section}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@resets@ppsub}
% Similar to \cs{@resets@pp} except that it is for use within the 
% \Lenv{subappendices} environment; as such, it is a bit simpler.
% \changes{v3.7p}{2021/06/16}{Moved \cs{theHsection} def here instead
% of in \Lpack{memhfixc}, Problem reported by Ignasi Furio, private email 13 May 2004}
%    \begin{macrocode}
\newcommand{\@resets@ppsub}{
  \par
  \setcounter{section}{0}
  \renewcommand{\thesection}{\setthesection}
  \def\theHsection{\theHchapter.\Alph{section}}
}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ifnamesubappendix}
% \begin{macro}{\namesubappendixtrue}
% \begin{macro}{\namesubappendixfalse}
% \begin{macro}{\namedsubappendices}
% \begin{macro}{\unnamedsubappendices}
% Switch for adding an `appendix' name before subappendix numbers.
% \changes{v1.0}{2001/11/13}{Added \cs{ifnamesubappendix}}
% \changes{v1.61803}{2008/01/30}{Added \cs{namedsubappendices} and
%                                \cs{unnamedsubappendices}}
%    \begin{macrocode}
\newif\ifnamesubappendix
  \namesubappendixfalse
\newcommand*{\namedsubappendices}{\namesubappendixtrue}
\newcommand*{\unnamedsubappendices}{\namesubappendixfalse}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{environment}{subappendices}
%  The environment for subappendices. Start it off by doing the resetting
% of the \cs{section} command. 
% \changes{v1.0}{2001/11/13}{Modified subappendices environment}
%    \begin{macrocode}
\newenvironment{subappendices}{%
  \@resets@ppsub
%    \end{macrocode}
% Change the definition of \cs{addappheadtotoc} to give a \texttt{section} entry.
% \changes{v1.618}{2005/09/02}{Fixed bookmark for \cs{appendixpage} (mempatch v2.3)}
% \changes{v3.8.4}{2025/09/16}{Replaced \cs{phantomsection} by suitable \cs{MakeLinkTarget}}
%    \begin{macrocode}
\def\addappheadtotoc{%
  %\phantomsection
  \MakeLinkTarget[section]{}%
    \addcontentsline{toc}{section}{\appendixtocname}}
%    \end{macrocode}
% To implement the naming we do cunning things with the
% \cs{@seccntformat} command.
%    \begin{macrocode}
  \ifnamesubappendix
    \def\sectionname{\appendixname}
    \def\@seccntformat##1{\@ifundefined{##1name}%
                         {}{\csname ##1name\endcsname\ }%
        \csname the##1\endcsname\quad}
  \fi
%    \end{macrocode}
% We end by redefining \cs{theHsection} introduced in \cs{@resets@ppsub}
% \changes{v3.7p}{2021/06/16}{Moved redef of \cs{theHsection} here instead
% of in \Lpack{memhfixc}}
% \changes{v3.8}{2023/06/20}{Changed \cs{theHsection} to use
% \cs{the}\cs{value\{counter\}} as packages can mess up \cs{arabic}
% advise from Ulrike}
%    \begin{macrocode}
}{%
  \def\theHsection{\theHchapter.\the\value{section}}
}

%    \end{macrocode}
% \end{environment}
%
% \begin{macro}{\@formatsecmark@pp}
% Formats the page header for a redefined \cs{sectionmark}.
%    \begin{macrocode}
% unused?
% \newcommand{\@formatsecmark@pp}[1]{%
%   \MakeUppercase{\appendixname\space
%     \ifnum \c@secnumdepth >\z@
%       \thesection\quad
%     \fi
%     #1}}
%    \end{macrocode}
% \end{macro}
%
% \subsection{Appendixpage-like pages}
% \changes{v1.618}{2005/09/03}{Added \cs{newleadpage} and friends (mempatch v3.0)}
%
%
% This capability was suggested to me by Lars Madsen on 2004/11/28.
%
% \begin{macro}{\leadpagetoclevel}
% \begin{macro}{\newleadpage}
% \begin{macro}{\renewleadpage}
% \verb?\newleadpage[<page-style>]{<cmdname>}{<title>}? creates new macros 
% called \verb?\cmdname? and \verb?\cmdname*? that when called typeset a 
% page like an  Appendixpage, with a title \verb?<title>? using
% page style \verb?<page-style>? (default empty). The
% plain version adds an entry to the ToC but the starred \verb?\cmdname*? 
% does not. \cs{renewleadpage} changes the definitions.
%
%    The ToC entry style is set by \cs{leadpagetoclevel} (default chapter). To have a part-type entry: \\
% \verb?\renewcommand*{\leadpagetoclevel}{part}?. \\
% The \cs{partmark} command is used if you need to mark the title.
%    \begin{macrocode}
\newcommand*{\leadpagetoclevel}{chapter}
\newcommand*{\newleadpage}[3][empty]{%
  \@namedef{#2}{\@ifstar{\dlfm@msapppage{#1}{#2}{#3}}%
                        {\dlfm@mapppage{#1}{#2}{#3}}}}
\newcommand*{\renewleadpage}[3][empty]{%
  \@namedef{#2}{\@ifstar{\dlfm@msapppage{#1}{#2}{#3}}%
                        {\dlfm@mapppage{#1}{#2}{#3}}}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\memleadpageinfo}
% \begin{macro}{\memleadpagestarinfo}
% \verb?\memleadpageinfo{pstyle}{name}{title}? \\
% \verb?\memleadpagestarinfo{pstyle}{name}{title}? \\
%    \begin{macrocode}
\newcommand{\memleadpageinfo}[3]{}
\newcommand{\memleadpagestarinfo}[3]{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\dlfm@msapppage}
% \begin{macro}{\dlfm@mapppage}
% Implement the starred and regular versions of \verb?\(re)newleadpage?
% \changes{v3.8.4}{2025/09/16}{Use \cs{MakeLinkTarget} instead of \cs{phantomsection}}
%    \begin{macrocode}
\newcommand*{\dlfm@msapppage}[3]{%
  \@setuppart
  \partmark{#3}%
  \MakeLinkTarget[part]{}%
  \memleadpagestarinfo{#1}{#2}{#3}%
  {\centering
  \interlinepenalty \@M
  \normalfont
  \printparttitle{#3}\par
  \thispagestyle{#1}}%
  \dlfm@m@endpart{#1}}
\newcommand*{\dlfm@mapppage}[3]{%
  \@setuppart
  % \phantomsection
  \MakeLinkTarget[part]{}%
  \addcontentsline{toc}{\leadpagetoclevel}{#3}%
  \partmark{#3}%
  \memleadpageinfo{#1}{#2}{#3}%
  {\centering
  \interlinepenalty \@M
  \normalfont
  \printparttitle{#3}\par
  \thispagestyle{#1}}%
  \dlfm@m@endpart{#1}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\dlfm@m@endpart}
% Finishes off a part-like page.
%    \begin{macrocode}
\newcommand*{\dlfm@m@endpart}[1]{%
  \if@twoside
    \if@openright
      \null
      \thispagestyle{#1}%
      \newpage
    \fi
  \fi
  \if@tempswa
    \twocolumn
  \fi}

%    \end{macrocode}
% \end{macro}
%
% \subsection{Paragraphs}
%
% Much of the code in this section is taken from my \textit{Glisterings} 
% columns~\cite{GLISTER07,GLISTER08}.
% \changes{v1.6180339c}{2009/01/09}{Added several new paragraph types}
%
% \begin{macro}{\memorigdbs}
% \begin{macro}{\memorigpar}
% \begin{macro}{\atcentercr}
% \cs{memorigdbs} saves the original definition of \verb?\\? and 
% \cs{memorigpar} saves the original \cs{par}. The macro \cs{atcentercr}
% provides a user call to \cs{@centercr}. These could come in handy for
% odd paragraph shapes.
% \changes{v1.6180339c}{2009/01/09}{Added \cs{memorigdbs} and 
%          \cs{memorigpar} \cs{atcentercr}}
%    \begin{macrocode}
\let\memorigdbs\\
\let\memorigpar\par
\let\atcentercr\@centercr

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \subsubsection{Normal (block) paragraphs}
%
%
% \begin{macro}{\flushleftright}
%  Sets the paragraphing to \LaTeX's normal form.
% \changes{v1.61803}{2008/01/30}{Used \cs{@flushglue} in \cs{flushleftright} and
%          \cs{centerlastline} (mempatch v4.7)}
% \changes{v1.6180339c}{2009/01/09}{Extended \cs{flushleftright} to set all
%          the regular paragraphing controls}
%    \begin{macrocode}
\newcommand*{\flushleftright}{%
  \let\\\memorigdbs
  \leftskip\z@skip 
  \rightskip\leftskip
  \parfillskip\@flushglue
  \everypar{}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\linenottooshort}
% This declaration \cs{linenottooshort}\oarg{length} specifies paragraphs
% such that the last line is at least about \meta{length} long (the default
% is 4em).
% \changes{v1.6180339c}{2009/01/09}{Added \cs{linenottooshort} paragraph}
%    \begin{macrocode}
\newcommand*{\linenottooshort}[1][4em]{%
  \@tempdima=\hsize
  \advance\@tempdima -#1
  \leftskip\z@skip
  \rightskip\leftskip
  \parfillskip=\@tempdima \@minus \@tempdima}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\russianpar}
% Using \cs{russianpar} instead of \cs{par} to end a paragraph causes it
% to be set according to Russian typography, where the last line of a 
% multiline paragraph must be either at least as
% long as \cs{parindent} and have at least \cs{parindent} space at the
% right, or it must be flushleft and flushright.
% \changes{v1.6180339c}{2009/01/09}{Added \cs{russianpar} paragraph}
%    \begin{macrocode}
\newcommand*{\russianpar}{\ifhmode\unskip
  \strut\vadjust{}\nobreak
  \discretionary{}%
  {\hbox{\hskip2\parindent
         \vrule depth 273sp width 0sp height \ht\strutbox}}%
  {\hbox{\hskip\parindent}}%
  \hskip-2\parindent \@minus 2\parindent
  \hskip\hsize \@minus \hsize
  \kern\z@ \parfillskip\z@
  \memorigpar
  \ifdim\prevdepth=273sp
    \nobreak
    \vskip-2\baselineskip
    \hbox{\strut}%
  \fi\fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\lastlineparrule}
% \begin{macro}{\lastlinerulefill}
% Using \cs{lastlinerulefill} instead of \cs{par} to end a paragraph
% causes all short lines to be filled at the right by a rule 
% (\cs{lastlineparrule}) extending to the righthand margin.
% \changes{v1.6180339c}{2009/01/09}{Added \cs{lastlineparrule} and 
%          \cs{lastlinerulefill} paragraph}
%    \begin{macrocode}
\newcommand*{\lastlineparrule}{%
  \hrule height 0.5ex depth \@tempdimb\relax}
\newcommand*{\lastlinerulefill}{%
  \let\\\@centercr
  \@tempdimb=-0.5ex \advance\@tempdimb 0.4pt
  \unskip\nobreak\space
  \leaders\lastlineparrule\hskip\@flushglue
  \vadjust{}{\parfillskip\z@\memorigpar}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \subsubsection{Centered lines}
%
% \begin{macro}{\centerlastline}
% This declaration specifies normal paragraphs except that the last line of
% each is centered.
% \changes{v1.61803398}{2009/07/17}{Added bidi support to \cs{centerlastline}}
%    \begin{macrocode}
\newcommand*{\centerlastline}{%
  \memRTLleftskip\@flushglue
  \memRTLrightskip=\z@ plus -1fil
  \parfillskip=\z@ plus 2fil}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\leftcenterright}
% This declaration specifies paragraphs where the first line is flushleft 
% (raggedright), the
% last is flushright (raggedleft) and all inbetween are centered.
% Set \verb?\everypar{}? afterwards.
% \changes{v1.6180339c}{2009/01/09}{Added \cs{leftcenterright} paragraph}
%    \begin{macrocode}
\newcommand*{\leftcenterright}{%;
  \let\\\break
  \parindent\z@
  \leftskip\@flushglue
  \rightskip\leftskip
  \parfillskip \z@ \@plus -1fil
  \everypar={\hskip \z@ \@plus -1fil}}

%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\centerfloat}
% This is a version of \cs{centering} that can be used to center a wide
% float with respect to the text block (normally the left of a wide float
% is aligned with the left of the textblock). This can only be used for
% centering something where LaTeX knows the width (e.g., a figure or a 
% table / tabular). 
%    
%  This is a modified version of code by Robin Fairbairns 
% (CTT, \textit{Re: Centering a table: problem with rotating.sty, maybe
% a strange document class?}, 3 Jan 2009).
% \changes{v1.6180339c}{2009/01/11}{Added \cs{centerfloat}}
%    \begin{macrocode}
\newcommand*{\centerfloat}{%
  \parindent \z@
  \leftskip \z@ \@plus 1fil \@minus \textwidth
  \rightskip\leftskip
  \parfillskip \z@skip}

%    \end{macrocode}
% \end{macro}
%
% \subsubsection{Ragged}
%
% The kernel code for raggedright (in \file{ltmiscen.dtx}):
% \begin{verbatim}
% \def\raggedright{%
%   \let\\\@centercr\@rightskip\@flushglue \rightskip\@rightskip
%   \leftskip\z@skip
%   \parindent\z@}
% %% \@flushglue = 0pt plus 1fil      %% from ltalloc.dtx
% %% \z@skip = 0pt plus 0pt minus 0pt %%
% \end{verbatim}
% produces very ragged text with no paragraph indent. 
%
% \begin{macro}{\ragrparindent}
% \begin{macro}{\raggedyright}
% \cs{raggedyright}\oarg{plus} provides controllable ragged right paragraphs.
% \changes{v1.4}{2003/12/10}{Added \cs{raggedyright}}
% \changes{v1.61803398}{2009/07/17}{Added bidi support to \cs{raggedyright}}
%    \begin{macrocode}
\newdimen\ragrparindent
  \setlength{\ragrparindent}{\parindent}
\newcommand{\raggedyright}[1][2em]{%
  \let\\\@centercr\@rightskip \z@ \@plus #1\relax 
  \memRTLrightskip\@rightskip
  \memRTLleftskip\z@skip
  \parindent\ragrparindent}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\justlastraggedleft}
% This declaration specifies paragraphs where the lines are justified, 
% except for the last which is raggedleft (flushright)..
% \changes{v1.6180339c}{2009/01/09}{Added \cs{justlastraggedleft} paragraph}
% \changes{v1.61803398}{2009/07/17}{Added bidi support to \cs{justlastraggedleft}}
%    \begin{macrocode}
\newcommand*{\justlastraggedleft}{%
  \memRTLleftskip\@flushglue
  \memRTLrightskip-\memRTLleftskip
  \parfillskip\leftskip
  \parindent \z@}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\raggedrightthenleft}
% This declaration specifies paragraphs where the first line is raggedright
% (flushleft) and all the rest are raggedleft (flushright). Note that
% this alters \cs{everpar}, which may need to be reset afterwards to
% \verb?\everypar{}?.
% \changes{v1.6180339c}{2009/01/09}{Added \cs{raggedrightthenleft} paragraph}
% \changes{v1.61803398}{2009/07/17}{Added bidi support to \cs{raggedrightthenleft}}
%    \begin{macrocode}
\newcommand*{\raggedrightthenleft}{%
  \parindent \z@
  \memRTLleftskip \z@ \@plus 1fill
  \memRTLrightskip\@flushglue
  \parfillskip \z@
  \everypar{\hskip \z@ \@plus -1fill}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\raggedwrap}
% 
%   \changes{v3.8.2}{2024/01/25}{Code moved here from the verbatim
%   section. The code where it was uses has been removed, but the
%   macro might still be interesting.}
%
%   \cs{raggedwrap} is a variation on \cs{raggedright} (\cs{leftskip}
%   is set to \cs{@totalleftmargin} instead of 0pt), and seems to have
%   fixed the problem with the original code which used
%   \cs{raggedright}.  \changes{v1.61803}{2008/01/30}{Added
%   \cs{raggedwrap} (mempatch v4.4)}
%   \changes{v1.61803398}{2009/07/18}{Added bidi support to
%   \cs{raggedwrap}}
%    \begin{macrocode}
\newcommand*{\raggedwrap}{%
  \@rightskip\@flushglue
%%%  \rightskip\@rightskip
  \memRTLrightskip\@rightskip
%%%  \leftskip\@totalleftmargin
  \memRTLleftskip\@totalleftmargin
  \parindent\ragrparindent}

%    \end{macrocode}
% \end{macro}
% 
% \subsubsection{Hanging}
%
% \begin{macro}{\hangfrom}
% This is a user-level
% version of the kernel \cs{@hangfrom} macro (only the name is
% changed) as defined in \file{ltsec.dtx}.
%
% \cs{hangfrom}\marg{text} puts \meta{text} in a box and makes a hanging
% paragraph of the following material (a bit like a description item).
% \changes{v1.4}{2003/11/22}{Added \cs{hangfrom} (from patch v1.9)}
%    \begin{macrocode}
\newcommand{\hangfrom}[1]{%
  \setbox\@tempboxa\hbox{{#1}}%
  \hangindent \wd\@tempboxa\noindent\box\@tempboxa}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\hangpara}
% \cs{hangpara}\marg{indent}\marg{afternum} at the start of a 
% paragraph will make it hung. If \meta{indent} is positive the left
% will be indented, otherwise the right. If \meta{afternum}, say N,
% is positive the N+1 th lines onwards will be indented. For N negative,
% the first N lines will be indented.
%    \begin{macrocode}
\newcommand{\hangpara}[2]{\hangindent#1\hangafter#2\noindent}
%    \end{macrocode}
% \end{macro}
%
% \begin{environment}{hangparas}
% \verb?\begin{hangparas}?\marg{indent}\marg{afternum} hangs 
% a series of paragraphs.
%    \begin{macrocode}
\newenvironment{hangparas}[2]{\setlength{\parindent}{\z@}
  \everypar={\hangpara{#1}{#2}}}{\par}

%    \end{macrocode}
% \end{environment}
%
% \subsubsection{Miscellaneous}
%
% \begin{macro}{\leftspringright}
% \cs{leftspringright}\marg{leftfrac}\marg{rightfrac}\marg{lefttext}\marg{righttext}
% sets the \meta{lefttext} flushleft (raggedright) in a column \meta{leftfrac} 
% of the current textwidth and the \meta{righttext} flushright (raggedleft) 
% in a column \meta{rightfrac} of the textwidth, with space 
% (1.0 - \meta{leftfrac} - \meta{rightfrac})
% of the textwidth between them. Both \meta{leftfrac} and \meta{rightfrac}
% must be given as decimal numbers (e.g., \texttt{0.25} not \texttt{1/4}).
% \changes{v1.6180339c}{2009/01/09}{Added \cs{leftspringright} paragraph}
%    \begin{macrocode}
\newcommand{\leftspringright}[4]{%
  \@tempdimb=\hsize
  \par\noindent\hbox to\@tempdimb{%
    \vtop{\hsize=#1\@tempdimb \flushleft#3\par}\hss
    \vtop{\hsize=#2\@tempdimb \flushright#4\par}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sourceatright}
% Putting \cs{sourceatright}\oarg{length}\marg{text} at the end of a 
% paragraph will set \meta{text} flushright on the same line provided the line
% is short enough to allow \meta{length} (default 2em) between the end of the
% line and \meta{text}. If there is not enough space then \meta{text} is
% set flushright on the following line.
% \changes{v1.6180339c}{2009/01/09}{Added \cs{sourceatright} paragraph}
%    \begin{macrocode}
\newcommand*{\sourceatright}[2][2em]{{%
  \unskip\nobreak\hfil\penalty50
  \hskip#1\hbox{}\nobreak\hfil{#2}
  \parfillskip\z@\finalhyphendemerits=0\par}}

%    \end{macrocode}
% \end{macro}
%
%
% \section{Lists}
%
% \subsection{General List Parameters}
%
% The following commands are used to set the default values for the list
% environment's parameters. See the \LaTeX{} manual for an explanation
% of the meanings of the parameters.  Defaults for the list
% environment are set as follows.  First, \cs{rightmargin},
% \cs{listparindent} and \cs{itemindent} are set to 0pt.  Then, for a Kth
% level list, the command \cs{@listK} is called, where `K' denotes `i',
% '`i', ... , `vi'.  (I.e., \cs{@listiii} is called for a third-level
% list.)  By convention, \cs{@listK} should set \cs{leftmargin} to
% \cs{leftmarginK}.
%
%
% \begin{macro}{\leftmargin}
% \begin{macro}{\leftmargini}
% \begin{macro}{\leftmarginii}
% \begin{macro}{\leftmarginiii}
% \begin{macro}{\leftmarginiv}
% \begin{macro}{\leftmarginv}
% \begin{macro}{\leftmarginvi}
% For efficiency, level-one list's values are defined at top level, and
% \cs{@listi} is defined to set only \cs{leftmargin}.
%
% In two column mode the margins should be smaller than in one column typesetting.
%    \begin{macrocode}
\if@twocolumn
  \setlength{\leftmargini}{2em}
\else
  \setlength{\leftmargini}{2.5em}
\fi
%    \end{macrocode}
%    The value of \cs{leftmargin} has to be set at this outer level.
%    \begin{macrocode}
\leftmargin \leftmargini
%    \end{macrocode}
%    Lower level list margins are calculated so that they are indented
% more than the label in an outer list.
%    \begin{macrocode}
\setlength{\leftmarginii}{2.2em}
\setlength{\leftmarginiii}{1.87em}
\setlength{\leftmarginiv}{1.7em}
\if@twocolumn
  \setlength{\leftmarginv}{.5em}
  \setlength{\leftmarginvi}{.5em}
\else
  \setlength{\leftmarginv}{1em}
  \setlength{\leftmarginvi}{1em}
\fi
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\itemindent}
%    Here we set the \cs{itemindent} which is the extra indentation before
%    a label.
%    \begin{macrocode}
\setlength{\itemindent}{\z@}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\labelsep}
% \begin{macro}{\labelwidth}
%    \cs{labelsep} is the distance between the label and the text of an
%    item; \cs{labelwidth} is the width of the label.
%    \begin{macrocode}
\setlength{\labelsep}{0.5em}
\setlength{\labelwidth}{\leftmargini}
  \addtolength{\labelwidth}{-\labelsep}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@beginparpenalty}
% \begin{macro}{\@endparpenalty}
%    These penalties are inserted before and after a list or paragraph
%    environment. They are set to a bonus value to encourage page
%    breaking at these points.
% \begin{macro}{\@itempenalty}
%    This penalty is inserted between list items.
%    \begin{macrocode}
\@beginparpenalty -\@lowpenalty
\@endparpenalty   -\@lowpenalty
\@itempenalty     -\@lowpenalty

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% \begin{macro}{\everylistparindent}
% \begin{macro}{\list}
% The kernel sets \cs{listparindent} to zero within a \cs{list}, where it
% can be overridden in \cs{list}'s second argument. Here it is set to
% \cs{everyparlistindent} by default, which in turn is 0pt.
%    \begin{macrocode}
\newdimen\everylistparindent
  \everylistparindent \z@
\renewcommand*{\list}[2]{%
  \ifnum \@listdepth >5\relax
    \@toodeep
  \else
    \global\advance\@listdepth\@ne
  \fi
  \rightmargin\z@
  \listparindent\everylistparindent
  \itemindent\z@
  \csname @list\romannumeral\the\@listdepth\endcsname
  \def\@itemlabel{#1}%
  \let\makelabel\@mklab
  \@nmbrlistfalse
  #2\relax
  \@trivlist
  \parskip\parsep
  \parindent\listparindent
  \advance\linewidth -\rightmargin
  \advance\linewidth -\leftmargin
  \advance\@totalleftmargin \leftmargin
  \parshape \@ne \@totalleftmargin \linewidth
  \ignorespaces}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\parsepi}
% \begin{macro}{\topsepi}
% \begin{macro}{\itemsepi}
% \begin{macro}{\parsepii}
% \begin{macro}{\topsepii}
% \begin{macro}{\topsepiii}
% Lists may be nested and the exact layout depends on the level
% of nesting. These lengths are used to control the nesting-level
% aspects.
%    \begin{macrocode}
\newlength{\parsepi}
\newlength{\topsepi}
\newlength{\itemsepi}
\newlength{\parsepii}
\newlength{\topsepii}
\newlength{\topsepiii}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\itemsepii}
% \begin{macro}{\itemsepiii}
% \begin{macro}{\partopsepii}
% \begin{macro}{\partopsepii}
% We need some new lengths for lists to cater for non-zero \cs{parskip}.
% \changes{v1.61803}{2008/01/30}{Added \cs{itemsepii}, \cs{itemsepiii} and
%            \cs{partopsepii} (mempatch v4.6)}
%    \begin{macrocode}
\newlength{\itemsepii}
\newlength{\itemsepiii}
\newlength{\partopsepii}
\newlength{\partopsepiii}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\setnzplist}
% Common code for non-zero \cs{parskip} in lists.
%    \begin{macrocode}
\newcommand*{\setnzplist}{%
  \partopsep \p@ \@plus\z@ \@minus\p@
  \topsepi\z@
  \parsepi\parskip
  \itemsepi\z@
  \topsepii\z@
  \parsepii\parskip
  \itemsepii\z@
  \topsepiii\z@
%%    \parsepiii\parskip
  \itemsepiii\z@}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\defaultlists}
% The standard \LaTeX\ classes have list parameters that give some
% separation between lists and \cs{item}s in lists. This macro sets
% those values. This is a simplification of memoir's original, and will 
% apply to any font size.
% \changes{v1.61803}{2008/01/30}{Complete replacement of \cs{defaultlists}
%                  (mempatch 4.5)}
%    \begin{macrocode}
\newcommand*{\defaultlists}{%
  \setlength{\partopsep}{0.2\onelineskip \@plus 0.1\onelineskip 
                                         \@minus 0.1\onelineskip}%
  \parsepi = 0.3333\onelineskip \@plus 0.1667\onelineskip \@minus \p@
  \itemsepi = \parsepi
  \topsepi = 0.6667\onelineskip \@plus 0.3333\onelineskip 
                                \@minus 0.2\onelineskip
  \parsepii = 0.1667\onelineskip \@plus \p@ \@minus \p@
  \topsepii = \parsepi
  \topsepiii = \parsepii
  \everylistparindent \listparindent
%    \end{macrocode}
% Additional code to cater for non-zero \cs{parskip}s.
% \changes{v1.61803}{2008/01/30}{Modified \cs{defaultlists} for
%                    non-zero \cs{parskip} (memptach v4.6)}
%    \begin{macrocode}
  \itemsepii\parsepii
  \itemsepiii\topsepiii
  \partopsepiii \p@ \@plus\z@ \@minus\p@
  \ifm@mnzpskip
    \setnzplist
  \fi}
\defaultlists

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\firmlists}
% \begin{macro}{\firmlists*}
% \begin{macro}{\m@msfirmlists}
% \begin{macro}{\m@mfirmlists}
% These give approximately half the vertical spacing of the default lists, 
% with all spaces equal. The starred version allows slightly less space
% before and after the list when it is preceded by a blank line.
% \changes{v1.61803}{2008/01/30}{Added \cs{firmlists}, etc. (mempatch v4.5)}
%    \begin{macrocode}
\newcommand*{\firmlists}{%
  \@ifstar{\m@msfirmlists}{\m@mfirmlists}}

\newcommand*{\m@msfirmlists}{
  \setlength{\partopsep}{\z@ \@plus \p@ \@minus \p@}%
  \parsepi = 0.1667\onelineskip \@plus 0.0833\onelineskip \@minus \p@
  \itemsepi = \parsepi
  \topsepi = \parsepi
  \parsepii = 0.0833\onelineskip \@plus \p@ \@minus \p@
  \topsepii = \parsepi
  \topsepiii = \parsepii
  \everylistparindent\listparindent}

\newcommand*{\m@mfirmlists}{
  \setlength{\partopsep}{0.1\onelineskip \@plus 0.05\onelineskip 
                                         \@minus 0.05\onelineskip}%
  \parsepi = 0.1667\onelineskip \@plus 0.0833\onelineskip \@minus \p@
  \itemsepi = \parsepi
  \topsepi = \parsepi
  \parsepii = 0.0833\onelineskip \@plus \p@ \@minus \p@
  \topsepii = \parsepi
  \topsepiii = \parsepii
  \everylistparindent\listparindent}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\tightlists}
% \begin{macro}{\tightlists*}
% \begin{macro}{\m@mstightlists}
% \begin{macro}{\m@mtightlists}
% This macro sets the parameters for lists that have less open vertical
% space in them. I think that these look neater than the defaults.
% Effectively, no additional vertical space is added. 
% The starred version allows slightly no extra space
% before and after the list when it is preceded by a blank line,
% whereas the unstarred version puts half a \cs{onelineskip}
% before \emph{and} after.
% \changes{v1.61803}{2008/01/30}{Revised \cs{tightlists}, etc. (mempatch v4.5)}
% \changes{v1.61803}{2008/01/30}{Revised \cs{tightlists} for non-zero
%          \cs{parskip}(mempatch v4.6)}
%    \begin{macrocode}
\newcommand*{\tightlists}{%
  \@ifstar{\m@mstightlists}{\m@mtightlists}}

\newcommand*{\m@mstightlists}{%
  \setlength{\partopsep}{\z@ \@plus \p@ \@minus \p@}%
  \parsepi = \z@ \@plus \p@ \@minus \p@
  \itemsepi = \parsepi
  \topsepi = \z@ \@plus \p@ \@minus \p@
  \parsepii = \z@ \@plus \p@ \@minus \p@
  \topsepii = \parsepi
  \topsepiii = \parsepii
  \everylistparindent\parindent
  \ifm@mnzpskip
    \setnzplist
    \partopsepiii\partopsep
  \fi}

\newcommand*{\m@mtightlists}{%
  \setlength{\partopsep}{0.5\onelineskip \@plus \p@ \@minus \p@}%
  \parsepi = \z@ \@plus \p@ \@minus \p@
  \itemsepi = \parsepi
  \topsepi = \z@ \@plus \p@ \@minus \p@
  \parsepii = \z@ \@plus \p@ \@minus \p@
  \topsepii = \parsepi
  \topsepiii = \parsepii
  \everylistparindent\parindent
  \ifm@mnzpskip
    \setnzplist
    \partopsepiii\partopsep
  \fi}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\firmlist}
% \begin{macro}{\tightlist}
% These two macros can be used at the start of a list environment to
% reduce the vertical gaps. \cs{tightlist} removes all interior spaces
% while \cs{firmlist} only removes some.
% \changes{v0.3}{2001/07/09}{Added \cs{firmlist} and reimplemented the
% original \cs{tightlist}}
%    \begin{macrocode}
\newcommand{\firmlist}{%
  \setlength{\itemsep}{0.5\itemsep}\setlength{\parskip}{0.5\parskip}}
\newcommand{\tightlist}{%
  \setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%    The space before and after a \Lenv{trivlist} environment is controlled
% by the \cs{topsep} and \cs{partopsep} skips. There are several environments,
% such as \Lenv{center}, that are defined as a \Lenv{trivlist}.
% 
% \begin{macro}{\m@msavetopsep}
% \begin{macro}{\m@msavepartopsep}
% \begin{macro}{\savetrivseps}
% \begin{macro}{\restoretrivseps}
% Two skips to store the \cs{topsep} and \cs{partopsep} values and a means
% of setting them and restoring them.
% \changes{v1.6}{2004/01/28}{Added methods for adjusting the space around
%                            a trivlist}
%    \begin{macrocode}
\newskip\m@msavetopsep
\newskip\m@msavepartopsep
\newcommand*{\savetrivseps}{%
  \m@msavetopsep\topsep
  \m@msavepartopsep\partopsep}
\newcommand*{\restoretrivseps}{%
  \topsep\m@msavetopsep
  \partopsep\m@msavepartopsep}
%    \end{macrocode}
% Save the initial \cs{topsep} and \cs{partopsep} values.
%    \begin{macrocode}
\savetrivseps

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\zerotrivseps}
%  A macro to zero \cs{topsep} and \cs{partopsep}.
%    \begin{macrocode}
\newcommand*{\zerotrivseps}{%
  \topsep\z@
  \partopsep\z@}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\@listI}
% \begin{macro}{\@listi}
% \cs{@listI} defines top level and \cs{@listi} values of
% \cs{leftmargin}, \cs{parsep}, \cs{topsep}, and \cs{itemsep}
%
%    \begin{macrocode}
\def\@listi{\leftmargin\leftmargini
  \parsep\parsepi
  \topsep\topsepi
  \itemsep\itemsepi}
\let\@listI\@listi
%    \end{macrocode}
%    We should initialise these parameters to the standard defaults
%    \begin{macrocode}
\defaultlists
\@listi

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\@listii}
% \begin{macro}{\@listiii}
% \begin{macro}{\@listiv}
% \begin{macro}{\@listv}
% \begin{macro}{\@listvi}
%    Here are the same macros for the lower level lists.
%    \begin{macrocode}
\def\@listii{\leftmargin\leftmarginii
             \labelwidth\leftmarginii
             \advance\labelwidth-\labelsep
             \topsep\topsepii
             \parsep\parsepii
%    \end{macrocode}
% \changes{v3.7g}{2016/11/22}{Typo: \cs{itemsep} should here point at
% \cs{itemsepii}, reported by Thomas Koeppe, private email}
%    \begin{macrocode}
             \itemsep\itemsepii}

\def\@listiii{\leftmargin\leftmarginiii
              \labelwidth\leftmarginiii
              \advance\labelwidth-\labelsep
              \topsep\topsepiii
              \parsep\z@
%%%              \itemsep\topsep
%%%              \partopsep \p@ \@plus\z@ \@minus\p@
              \itemsep\itemsepiii
              \partopsep\partopsepiii}

\def\@listiv{\leftmargin\leftmarginiv
             \labelwidth\leftmarginiv
             \advance\labelwidth-\labelsep}

\def\@listv{\leftmargin\leftmarginv
            \labelwidth\leftmarginv
            \advance\labelwidth-\labelsep}

\def\@listvi{\leftmargin\leftmarginvi
             \labelwidth\leftmarginvi
             \advance\labelwidth-\labelsep}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \subsection{Enumerate}
%
%
%    The enumerate environment uses four counters: \Lcount{enumi},
%    \Lcount{enumii}, \Lcount{enumiii} and \Lcount{enumiv}, where
%    \Lcount{enumN} controls the numbering of the Nth level
%    enumeration.
%
% \begin{macro}{\theenumi}
% \begin{macro}{\theenumii}
% \begin{macro}{\theenumiii}
% \begin{macro}{\theenumiv}
%    The counters are already defined in \file{latex.dtx}, but their
%    representation is changed here.
%
%    \begin{macrocode}
\renewcommand{\theenumi}{\@arabic\c@enumi}
\renewcommand{\theenumii}{\@alph\c@enumii}
\renewcommand{\theenumiii}{\@roman\c@enumiii}
\renewcommand{\theenumiv}{\@Alph\c@enumiv}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\labelenumi}
% \begin{macro}{\labelenumii}
% \begin{macro}{\labelenumiii}
% \begin{macro}{\labelenumiv}
%    The label for each item is generated by the commands\\
%    \cs{labelenumi} \ldots\ \cs{labelenumiv}.
%    \begin{macrocode}
\newcommand{\labelenumi}{\theenumi.}
\newcommand{\labelenumii}{\theenumii)}
\newcommand{\labelenumiii}{\theenumiii.}
\newcommand{\labelenumiv}{\theenumiv.}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\p@enumii}
% \begin{macro}{\p@enumiii}
% \begin{macro}{\p@enumiv}
%    The expansion of \verb?\p@enumN\theenumN? defines the output of a
%    \cs{ref} command when referencing an item of the Nth level of an
%    enumerated list.
%    \begin{macrocode}
\renewcommand{\p@enumii}{\theenumi}
\renewcommand{\p@enumiii}{\theenumi(\theenumii)}
\renewcommand{\p@enumiv}{\p@enumiii\theenumiii}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
%    The following is taken directly from David Carlisle's 
% \Lpack{enumerate} package.
%
% START OF DAVID CARLISLE'S CODE AND COMMENTARY
%
% This package gives the enumerate environment an optional argument
% which determines the style in which the counter is printed.
%
% An occurence of one of the tokens \verb?A a I i? or \verb?1? produces the value
% of the counter printed with (respectively) \verb?\Alph \alph \Roman \roman?
% or \cs{arabic}.
%
% These letters may be surrounded by any strings involving any other
% \TeX\ expressions, however the tokens \verb?A a I i 1? must be inside a
% \verb?{ }? group if they are not to be taken as special.
%
%
% \begin{macro}{\@enlab}
% Internal token register used to build up the label command from the
% optional argument.
%    \begin{macrocode}
\newtoks\@enLab
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@enQmark}
% This just expands to a `?'. \cs{ref} will produce this, if no counter
% is printed.
%    \begin{macrocode}
\def\@enQmark{?}
%    \end{macrocode}
% \end{macro}
%
% The next four macros build up the command that will print the item
% label. They each gobble one token or group from the optional argument,
% and add corresponding tokens to the register \cs{@enLab}. They each end
% with a call to \cs{@enloop}, which starts the processing of the next
% token.
% \begin{macro}{\@enLabel}
% Add the counter to the label. \verb?#2? will be one of the `special'
% tokens \verb?A a I i 1?, and is thrown away. \verb?#1? will be a command
% like \cs{Roman}.
%    \begin{macrocode}
\def\@enLabel#1#2{%
  \edef\@enThe{\noexpand#1{\@enumctr}}%
  \@enLab\expandafter{\the\@enLab\csname the\@enumctr\endcsname}%
  \@enloop}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@enSpace}
% \begin{macro}{\@enSp@ce}
% Add a space to the label. The tricky bit is to gobble the space token,
% as you can not do this with a macro argument.
%    \begin{macrocode}
\def\@enSpace{\afterassignment\@enSp@ce\let\@memtempa= }
\def\@enSp@ce{\@enLab\expandafter{\the\@enLab\space}\@enloop}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@enGroup}
% Add a \verb?{ }? group to the label.
%    \begin{macrocode}
\def\@enGroup#1{\@enLab\expandafter{\the\@enLab{#1}}\@enloop}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@enOther}
% Add anything else to the label
%    \begin{macrocode}
\def\@enOther#1{\@enLab\expandafter{\the\@enLab#1}\@enloop}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@enloop}
% \begin{macro}{\@enloop@}
% The body of the main loop.
% Eating tokens this way instead of using \cs{@tfor} lets you see
% spaces and \textbf{all} braces. \cs{@tfor} would treat \verb?a? and
% \verb?{a}? as  special, but not \verb?{{a}}?.
%    \begin{macrocode}
\def\@enloop{\futurelet\@entemp\@enloop@}
%    \end{macrocode}
%    \begin{macrocode}
\def\@enloop@{%
  \ifx A\@entemp         \def\@memtempa{\@enLabel\Alph  }\else
  \ifx a\@entemp         \def\@memtempa{\@enLabel\alph  }\else
  \ifx i\@entemp         \def\@memtempa{\@enLabel\roman }\else
  \ifx I\@entemp         \def\@memtempa{\@enLabel\Roman }\else
  \ifx 1\@entemp         \def\@memtempa{\@enLabel\arabic}\else
  \ifx \@sptoken\@entemp \let\@memtempa\@enSpace         \else
  \ifx \bgroup\@entemp   \let\@memtempa\@enGroup         \else
  \ifx \@enum@\@entemp   \let\@memtempa\@gobble          \else
                         \let\@memtempa\@enOther
%    \end{macrocode}
%    Hook for possible extensions
%    \begin{macrocode}
                         \@enhook
%    \end{macrocode}
%
%    \begin{macrocode}
             \fi\fi\fi\fi\fi\fi\fi\fi
%    \end{macrocode}
% \end{macro}
% Process the current token, then look at the next.
%    \begin{macrocode}
  \@memtempa}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@enhook}
% Hook for possible extensions.
% Some packages may want to extend the number of special characters
% that are associated with counter representations. This feature
% was requested to enable Russian alphabetic counting, but here
% I give an example of a footnote symbol counter, triggered by \verb?*?.
%
% To enable a new counter type based on a letter, you just need
% to add a new \cs{ifx} clause by analogy with the code above.
% So for example to make \verb?*? trigger footnote symbol counting.
% a package should do the following.
%
% Initialise the hook, in case the package is loaded before
% \textsf{enumerate}.
%\begin{verbatim}
% \providecommand\@enhook{}
%\end{verbatim}
%
% Add to the hook a new \cs{ifx} clause that associates \verb?*? with the
% \cs{fnsymbol} counter command.
%\begin{verbatim}
% \g@addto@macro\@enhook{%
%   \ifx *\@entemp
%     \def\@memtempa{\@enLabel\fnsymbol}%
%   \fi}
%\end{verbatim}
% This code sequence should work whether it is loaded before or after
% this enumerate package. Any number of new counter types may be added
% in this way.
%
% At this point we just need initialise the hook, taking care not
% to over write any definitions another package may already have added.
% (PRW: as this is now in a class, it can be defined instead of
% \cs{provide}d).
%    \begin{macrocode}
%% \providecommand\@enhook{}
  \newcommand\@enhook{}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\enumerate}
% The new \Lenv{enumerate} environment. This is the first half of the
% original enumerate environment. If there is an optional argument, call
% \cs{@@enum@} to define the label commands, otherwise call
% \cs{@enum@} which is the second half of the original definition.
%    \begin{macrocode}
\def\enumerate{%
  \ifnum \@enumdepth >3 \@toodeep\else
      \advance\@enumdepth \@ne
      \edef\@enumctr{enum\romannumeral\the\@enumdepth}\fi
  \@ifnextchar[{\@@enum@}{\@enum@}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@@enum@}
% Handle the optional argument..
%    \begin{macrocode}
\def\@@enum@[#1]{%
%    \end{macrocode}
% Initialise the loop which will break apart the optional argument.
% The command to print the label is built up in \cs{@enlab}.
% \cs{@enThe} will be used to define \cs{theenum}\,$n$.
%    \begin{macrocode}
  \@enLab{}\let\@enThe\@enQmark
%    \end{macrocode}
% The \cs{@enum@} below is never expanded, it is used to detect the end
% of the token list.
%    \begin{macrocode}
  \@enloop#1\@enum@
%    \end{macrocode}
% Issue a warning if we did not find one of the `special' tokens.
%    \begin{macrocode}
  \ifx\@enThe\@enQmark\@warning{The counter will not be printed.%
   ^^J\space\@spaces\@spaces\@spaces The label is: \the\@enLab}\fi
%    \end{macrocode}
% Define \cs{labelenum}$\,n$ and \cs{theenum}$\,n$.
%    \begin{macrocode}
  \expandafter\edef\csname label\@enumctr\endcsname{\the\@enLab}%
  \expandafter\let\csname the\@enumctr\endcsname\@enThe
%    \end{macrocode}
% Set the counter to 7 so that we get the width of `vii' if roman
% numbering is in force then set \cs{leftmargin}$\,n$. to the width of the
% label plus \cs{labelsep}.
%    \begin{macrocode}
  \csname c@\@enumctr\endcsname7
  \expandafter\settowidth
            \csname leftmargin\romannumeral\@enumdepth\endcsname
            {\the\@enLab\hspace{\labelsep}}%
%    \end{macrocode}
% Finally call \cs{@enum@} which is the second half of the original
% definition.
%    \begin{macrocode}
  \@enum@}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@enum@}
% All the list parameters have now been defined, so call \cs{list}. This
% is taken straight from the original definition of \cs{enumerate}.
%    \begin{macrocode}
\def\@enum@{\list{\csname label\@enumctr\endcsname}%
           {\usecounter{\@enumctr}\def\makelabel##1{\hss\llap{##1}}}}

%    \end{macrocode}
% \end{macro}
%
% END OF DAVID CARLISLE'S CODE AND COMMENTARY
%
%
%
% \subsection{Itemize}
%
%
% \begin{macro}{\labelitemi}
% \begin{macro}{\labelitemii}
% \begin{macro}{\labelitemiii}
% \begin{macro}{\labelitemiii}
%    Itemization is controlled by the commands: \cs{labelitemi},
%    \cs{labelitemii}, etc., which define
%    the labels of the various itemization levels: the symbols used are:
%    bullet (\textbullet), bold en-dash (\textbf{\textendash}),
% centered asterisk (\textasteriskcentered), and centered dot
% (\textperiodcentered).
%
%    \begin{macrocode}
\newcommand{\labelitemi}{\textbullet}
\newcommand{\labelitemii}{\normalfont\bfseries \textendash}
\newcommand{\labelitemiii}{\textasteriskcentered}
\newcommand{\labelitemiv}{\textperiodcentered}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% It seems like a reasonable idea to give the \Lenv{itemize} environment
% an optional argument to match \Lenv{enumerate}. Fortunately this seems
% to be much simpler and I might even be able to work it out for myself.
%
% \begin{environment}{itemize}
% This is a hack at the kernel code for \Lenv{itemize}.
%    \begin{macrocode}
\renewcommand{\itemize}[1][\@empty]{%
  \ifnum \@itemdepth >\thr@@\@toodeep\else
    \advance\@itemdepth\@ne
    \ifx \@empty #1\else % optional argument
      \@namedef{labelitem\romannumeral\the\@itemdepth}{#1}%
    \fi
    \edef\@itemitem{labelitem\romannumeral\the\@itemdepth}%
    \expandafter
    \list
      \csname\@itemitem\endcsname
       {\def\makelabel##1{\hss\llap{##1}}}%
  \fi}
\let\enditemize =\endlist

%    \end{macrocode}
% \end{environment}
%
% \subsection{Description}
%
% The class defines two description environment, the standard one and a `block'
% one, and also two semi-configurable versions.
%
% \changes{v1.2}{2002/07/27}{Now two `description' environments.}
%
% \begin{environment}{description}
%    The description environment is defined here -- while the default itemize
%    and enumerate environments are defined in \file{latex.dtx}.
%
% \changes{v1.2}{2002/07/27}{The \texttt{description} environment now matches
%                            the standard layout.}
%    \begin{macrocode}
\newenvironment{description}%
               {\list{}{\labelwidth\z@ \itemindent-\leftmargin
                        \let\makelabel\descriptionlabel}}%
               {\endlist}
%    \end{macrocode}
% \end{environment}
%
% \begin{macro}{\descriptionlabel}
%    To change the formatting of the label, you must redefine
%    \cs{descriptionlabel}. 
%
%    \begin{macrocode}
\newcommand*{\descriptionlabel}[1]{\hspace\labelsep
                                   \normalfont\bfseries #1}
%    \end{macrocode}
% \end{macro}
%
% \begin{environment}{blockdescription}
%    The `block' description environment.
%
% \changes{v1.2}{2002/07/27}{Renamed original \texttt{description} environment
%                            to \texttt{blockdescription}.}
%    \begin{macrocode}
\newenvironment{blockdescription}%
               {\list{}{\labelwidth\z@ \itemindent 0.5em \labelsep 0.5em
                        \let\makelabel\blockdescriptionlabel}}%
               {\endlist}
%    \end{macrocode}
% \end{environment}
%
% \begin{macro}{\blockdescriptionlabel}
%    In order to change the formatting of the label, you must redefine 
% the macro \cs{blockdescriptionlabel}. 
%
%    \begin{macrocode}
\newcommand*{\blockdescriptionlabel}[1]{%%% \hspace\labelsep
                                   \normalfont\bfseries #1}
%    \end{macrocode}
% \end{macro}
%
% \begin{environment}{labelled}
% This is a version of the description environment which takes the
% name, without the backslash, of some \cs{labelcode} as its argument.
% For example: 
% \begin{verbatim}
% \newcommand*{\sflabel}[1]{\hspace\labelsep \normalfont\sffamily #1}
% \begin{labelled}{sflabel}
%   \item[label] using a sans font for the labels 
% \end{verbatim}
% \changes{v1.6180339f}{2009/04/25}{Added labelled environment}
%    \begin{macrocode}
\newenvironment{labelled}[1]%
  {\list{}{\labelwidth\z@ \itemindent-\leftmargin
           \def\m@malabel{\@nameuse{#1}} \let\makelabel\m@malabel}}%
  {\endlist}

%    \end{macrocode}
% \end{environment}
%
% \begin{environment}{flexlabelled}
% \verb?\begin{flexlabelled}{labelcode}{labelwidth}{labelsep}{itemindent}{leftmargin}{rightmargin}?
% lets you specify some of the parameters for a description-like list.
% The first argument is as for the labelled environment. The others are all
% lengths for the various parameters; a \verb?*? instead of a length means 
% that that argument is to be ignored.
% \changes{v1.6180339f}{2009/04/25}{Added flexlabelled environment}
%    \begin{macrocode}
\newenvironment{flexlabelled}[6]%
  {\list{}{\nametest{#2}{*}%
           \ifsamename\else \labelwidth #2  \fi
           \nametest{#3}{*}%
           \ifsamename\else \labelsep #3 \fi
           \nametest{#4}{*}%
           \ifsamename\else \itemindent #4 \fi
           \nametest{#5}{*}%
           \ifsamename\else \leftmargin #5 \fi
           \nametest{#6}{*}%
           \ifsamename\else  \rightmargin #6 \fi
           \def\m@malabel{\@nameuse{#1}} \let\makelabel\m@malabel}}%
  {\endlist}

%    \end{macrocode}
% \end{environment}
%
%
% \subsection{Quotation}
%
% \begin{environment}{quotation}
%   The quotation environment is defined by making clever use of
%   the list environment's parameters. The lines in the environment
%   are set smaller than \cs{textwidth}. The first line of a paragraph
%   inside this environment is indented.
%
%    \begin{macrocode}
\newenvironment{quotation}%
               {\list{}{\listparindent 1.5em%
                        \itemindent    \listparindent
                        \rightmargin   \leftmargin
                        \parsep        \z@ \@plus\p@}%
                \item[]}%
               {\endlist}
%    \end{macrocode}
% \end{environment}
%
% \subsection{Quote}
%
%
% \begin{environment}{quote}
%   The quote environment is like the quotation environment except
%   that paragraphs are not indented.
%
%    \begin{macrocode}
\newenvironment{quote}%
               {\list{}{\rightmargin\leftmargin}%
                \item[]}%
               {\endlist}
%    \end{macrocode}
% \end{environment}
%
% \subsection{Theorem}
%
%    This document class does not define it's own theorem environments,
%    the defaults, supplied by \file{latex.dtx} are available.
%
% \subsection{Listing of symbols and abbreviations}
%
%    Another element is the listing of symbols
%    and abbreviations. 
%
% \begin{environment}{symbols}
% \begin{macro}{\symbollabel}
%    \begin{macrocode}
\newcommand{\symbollabel}[1]{{#1 \hfill}}
%    \end{macrocode}
% \end{macro}
%    \begin{macrocode}
\newenvironment{symbols}{\list{}%
    {\itemindent 0em \leftmargin 8em
     \labelsep 1em \labelwidth 5em
     \let\makelabel\symbollabel}}%
    {\endlist}
%    \end{macrocode}
% \end{environment}
%
% \begin{macro}{\symboldef}
%    Within a \Lenv{symbols} environment the command 
%    \cs{symboldef}\marg{symbol}\marg{meaning}
%    is used to specify and explain each symbol or abbreviation.
%    \begin{macrocode}
\newcommand{\symboldef}[2]{\item[#1] #2}
%    \end{macrocode}
% \end{macro}
%
% \section{Abstracts}
%
% Books usually do not have abstracts, but I decided to add in the code 
% from the \Lpack{abstract} 
% package~\cite{ABSTRACT}.
% \changes{v0.3}{2001/07/09}{Added code for abstracts}
%
%
% We just have the \Lpack{report} or \Lpack{article} style for the
% abstract with no \Lopt{titlepage} option. The original code,
% from \file{classes.dtx} for this is:
% \begin{verbatim}
% \newenvironment{abstract}{%
%   \if@twocolumn
%     \section*{\abstractname}
%   \else
%     \small
%     \begin{center}%
%       {\bfseries \abstractname\vspace{-.5em}\vspace{\z@}}%%
%     \end{center}%
%     \quotation
%   \fi}%
%   {\if@twocolumn\else\endquotation\fi}
% \end{verbatim}
%
%
%    The following \cs{if...} commands are for implementing various options.
% \begin{macro}{\if@bsonecol}
% \begin{macro}{\ifadd@bstotoc}
% \begin{macro}{\ifnumber@bs}
% \begin{macro}{\if@bsrunin}
%    \begin{macrocode}
\newif\if@bsonecol
  \@bsonecoltrue
\newif\ifadd@bstotoc
  \add@bstotocfalse
\newif\ifnumber@bs
  \number@bsfalse
\newif\if@bsrunin
  \@bsruninfalse

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\abstractcol}
% \begin{macro}{\abstractintoc}
% \begin{macro}{\abstractnum}
% \begin{macro}{\abstractrunin}
% These are the use-level commands for setting the options. If
% the abstract is runin, then it must not be numbered otherwise
% adding it to the ToC might result in something peculiar.
%    \begin{macrocode}
\newcommand{\abstractcol}{\@bsonecolfalse}
\newcommand{\abstractintoc}{\add@bstotoctrue}
\newcommand{\abstractnum}{\number@bstrue\@bsruninfalse}
\newcommand{\abstractrunin}{\@bsrunintrue\number@bsfalse}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% 
%    The next set of macros comprise the 
% implementation of the \Lenv{abstract} environment.
%
% \begin{macro}{\abstractnamefont}
% \begin{macro}{\abstracttextfont}
%    These two macros are for specifying the fonts for typesetting the
% abstract's title and text. They are initialised for the default case
% (i.e., no class options).
%    \begin{macrocode}
\newcommand{\abstractnamefont}{\normalfont\small\bfseries}
\newcommand{\abstracttextfont}{\normalfont\small}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\abscolnamefont}
% \begin{macro}{\abscoltextfont}
%    These two macros are for specifying the fonts for typesetting the
% abstract's title and text in a two column document where the abstarct
% is part of a column. 
% \changes{v1.61803}{2008/01/30}{Added \cs{abscolnamefont} and 
%                    \cs{abscoltextfont} (mempatch v4.8)}
%    \begin{macrocode}
\newcommand{\abscolnamefont}{\normalfont\Large\bfseries}
\newcommand{\abscoltextfont}{\normalfont}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\absnamepos}
% \begin{macro}{\abstitleskip}
%    \cs{absnamepos} specifies the environment in which the abstract's title
% name will be typeset, and the length \cs{abstitleskip} is an adjustement
% to the vertical space between the title and the abstract's text. These
% are initialised for the default case.
%    \begin{macrocode}
\newcommand{\absnamepos}{center}
\newlength{\abstitleskip} \setlength{\abstitleskip}{-0.5em}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\absleftindent}
% \begin{macro}{\abs@leftindent}
% \begin{macro}{\absrightindent}
% \begin{macro}{\absparindent}
% \begin{macro}{\absparsep}
%    The abstract's text is typeset as a single item list, called 
% \texttt{@bstr@ctlist}. These lengths set the left and right margin indents, the
% paragraph indentation, and the inter-paragraph vertical space. Their
% initial values are all class option-dependent.
% \changes{v1.618}{2005/09/03}{Added \cs{abs@leftindent} per Lars Madsen (mempatch v3.0)}
%    \begin{macrocode}
\newlength{\absleftindent} 
  \absleftindent=\leftmargin
\newdimen\abs@leftindent
  \abs@leftindent=\leftmargin
\newlength{\absrightindent}
  \absrightindent=\leftmargin
\newlength{\absparindent}
\newlength{\absparsep}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\abslabeldelim}
% \begin{macro}{\@bslabeldelim}
% The contents of \cs{abslabeldelim} are typeset after a run-in heading.
%    \begin{macrocode}
\newcommand{\abslabeldelim}[1]{\def\@bslabeldelim{#1}}
\abslabeldelim{}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@bsrunintitle}
% This macro typeset the run-in heading.
%    \begin{macrocode}
\newcommand{\@bsrunintitle}{%
  \hspace*{\abstitleskip}{\abstractnamefont\abstractname\@bslabeldelim}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\setup@bstract}
%    Now arrange to set all the class option-dependent values.
% \changes{v1.618}{2005/09/03}{Used \cs{abs@leftindent} in \cs{setup@bstract} (mempatch v3.0)}
% \changes{v1.61803}{2008/01/30}{Changed \cs{setup@bstract} to cater for
%                    \cs{abscolnamefont}, etc., and don't set 
%                    \cs{absrightindent} to \cs{absleftindent}.}
%    \begin{macrocode}
\newcommand{\setup@bstract}{%
  \abs@leftindent=\absleftindent
  \if@twocolumn
%    \end{macrocode}
% Values for the \Lopt{twocolumn} class option.
%    \begin{macrocode}
    \if@bsonecol 
    \else
      \abs@leftindent=\z@
      \absrightindent=\z@
      \renewcommand*{\abstractnamefont}{\abscolnamefont}
      \renewcommand*{\abstracttextfont}{\abscoltextfont}
      \renewcommand*{\absnamepos}{flushleft}
      \setlength{\abstitleskip}{-2ex}
    \fi
  \fi}

%    \end{macrocode}
% \end{macro}
%
%    \begin{macrocode}
\AtBeginDocument{\setlength{\absparindent}{\parindent}
                 \setlength{\absparsep}{\parskip}}

%    \end{macrocode}
%
% \begin{environment}{@bstr@ctlist}
%    The abstract's text is typeset within the \Lenv{@bstr@ctlist} list environment.
% \changes{v1.618}{2005/09/03}{Used \cs{abs@leftindent} in \cs{@bstr@ctlist} (mempatch v3.0)}
%    \begin{macrocode}
\newenvironment{@bstr@ctlist}{%
  \list{}{%
          %%\topsep        \z@
          \partopsep     \z@
          \listparindent \absparindent
          \itemindent    \listparindent
          \leftmargin    \abs@leftindent
          \rightmargin   \absrightindent
          \parsep        \absparsep}%
  \item\relax}
  {\endlist}

%    \end{macrocode}
% \end{environment}
%
% \begin{macro}{\put@bsintoc}
%    This macro adds the abstract's title to the ToC. It does nothing if
% the abstract is being numbered.
% \changes{v3.8.4}{2025/09/16}{Replaced \cs{phantomsection} by \cs{MakeLinkTarget}}
%    \begin{macrocode}
\newcommand{\put@bsintoc}{%
  \ifadd@bstotoc
    \ifnumber@bs\else
      % \phantomsection
      \MakeLinkTarget[chapter]{}%
      \addcontentsline{toc}{chapter}{\abstractname}
    \fi
  \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\num@bs}
%    This macro generates a numbered abstract heading.
%    \begin{macrocode}
\newcommand{\num@bs}{\chapter{\abstractname}}

%    \end{macrocode}
% \end{macro}
%
% \begin{environment}{abstract}
%  At last we are in position to define the \Lenv{abstract} environment. This
% follows very much along the lines of the standard class definitions, but with
% macros inserted at strategic points.
%
% The \Lopt{twocolumn} option and the default case. These use the same code
% as any style differences are embedded in the new macros.
%    \begin{macrocode}
\newenvironment{abstract}{%
  \setup@bstract
  \if@bsrunin\else
    \ifnumber@bs \num@bs \else
      \begin{\absnamepos}\abstractnamefont\abstractname\end\absnamepos%
      \vspace{\abstitleskip}%
    \fi
  \fi
  \put@bsintoc%
  \begin{@bstr@ctlist}\if@bsrunin\@bsrunintitle\fi\abstracttextfont}%
  {\par\end{@bstr@ctlist}}

%    \end{macrocode}
% \end{environment}
%
% \begin{environment}{onecolabstract}
%  An environment for typesetting a single column abstract, 
% particularly as the optional argument to the \cs{twocolumn} command.
%    \begin{macrocode}
\newenvironment{onecolabstract}{%
  \begin{@twocolumnfalse}\begin{abstract}}{%
  \end{abstract}\end{@twocolumnfalse}}

%    \end{macrocode}
% \end{environment}
%
% \begin{macro}{\thanks}
% \begin{macro}{\@bs@thanks}
%    We have to keep the contents of the \cs{thanks} commands as normally these
% are emptied by the \cs{maketitle} command. I do this by extending the definition
% of the \cs{thanks} (from \file{ltsect.dtx}) command, 
% so that \cs{@bs@thanks} has a copy of the contents
% of \cs{@thanks}.
% \changes{v3.8.3}{2024/02/02}{Changed using \cs{addtoiargdef} to \cs{xapptocmd} }
%    \begin{macrocode}
 % \addtoiargdef{\thanks}{}{%
 %   \protected@xdef\@bs@thanks{\@bs@thanks
 %     \protect\footnotetext[\the\c@footnote]{#1}}%
 %   }
\xapptocmd\thanks{%
   \protected@xdef\@bs@thanks{\@bs@thanks
    \protect\footnotetext[\the\c@footnote]{#1}}%
}{}{\typeout{Patch to \string\thanks\space failed, please inform maintainer}}
\let\@bs@thanks\@empty

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\saythanks}
% This macro typesets any \cs{thanks} commands \emph{after} using 
% \texttt{onecolabstract}. 
%    \begin{macrocode}
\newcommand{\saythanks}{\begingroup
  \renewcommand{\thefootnote}{\fnsymbol{footnote}}\@bs@thanks
  \endgroup\global\let\@bs@thanks\@empty}
  
%    \end{macrocode}
% \end{macro}
%
%
% \section{Verse}
%
% The class provides a more flexible \Lenv{verse} environment than the 
% standard classes. This is based on the \Lpack{verse} 
% package~\cite{VERSE}.
% \changes{v1.0}{2001/10/30}{Complete rewrite of verse typesetting}
%
% \subsection{Environments}
%
%    Before proceeding with the main, here are some macros for aspects
% of line numbering.
%
% \begin{macro}{\c@vslineno}
% \begin{macro}{\c@poemline}
% \begin{macro}{\c@modulo@vs}
% \begin{macro}{\c@memfvsline}
% We need counters for stanza and poem lines. The \texttt{memfvsline}
% counter is for adjusting the starting line for verse line numbers. 
% \changes{v1.1}{2002/03/10}{Added poemline and modulo@vs counters}
% \changes{v1.61803}{2008/01/30}{Added memfvsline counter (mempatch v4.9)}
%    \begin{macrocode}
\newcounter{vslineno}
\newcounter{poemline}
\newcounter{modulo@vs}
\newcounter{memfvsline}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% 
% \changes{v3.8.3}{2024/02/05}{folly deleted the outcommented code for \cs{poemline}, have been outcommented for years.}
% 
% \begin{macro}{\linenumberfont}
% \begin{macro}{\vlvnumfont}
%  Set line numbering font(s).
%    \begin{macrocode}
\newcommand{\linenumberfont}[1]{\def\vlvnumfont{#1}}
%%% \linenumberfont{\small\rmfamily}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\ifbvcountlines}
% \begin{macro}{\bvcountlinestrue}
% \begin{macro}{\bvcountlinesfalse}
% Looking ahead, TRUE for (boxed) verbatim line numbers to be printed. Default
% is not to print them. Not that \cs{linenumberfrequency} twiddles with this.
%    \begin{macrocode}
\newif\ifbvcountlines%  TRUE to print line numbers of (boxed) verbatim lines
  \bvcountlinesfalse

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\linenumberfrequency}
% \begin{macro}{\linemodnum}
% Set numbering intervals (number modulo). Default is modulus 0.
%    \begin{macrocode}
\newcommand{\linenumberfrequency}[1]{%
  \ifnum #1< \@ne
    \def\linemodnum{0\relax}
    \bvcountlinesfalse
  \else
    \def\linemodnum{#1\relax}
    \bvcountlinestrue
  \fi}

%%%%\linenumberfrequency{0}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\setverselinenums}
% \cs{setverselinenums}\marg{firstline}\marg{startnumsat} sets the first line
% number to \meta{firstline} and the first line number to be printed is
% \meta{startnumsat}. Use within the \Lenv{verse} environment before the
% first verse. Note that \\
% \verb?firstline <= startnumsat < firstline + linenumberfrequency?
% \changes{v1.61803}{2008/01/30}{Added \cs{setverselinenums} (mempatch v4.9)}
%    \begin{macrocode}
\newcommand*{\setverselinenums}[2]{%
  \c@poemline #1\relax \advance\c@poemline \m@ne
  \refstepcounter{poemline}%
  \ifnum\z@<\linemodnum%   we are printing line numbers
    \@tempcnta #2\relax
    \divide\@tempcnta\linemodnum
    \multiply\@tempcnta\linemodnum
    \c@memfvsline #2\relax
    \advance\c@memfvsline-\@tempcnta
  \fi}

%    \end{macrocode}
% \end{macro} 
%
% \changes{v1.1}{2002/03/24}{Added \cs{getmodulo@vs}}
% \changes{v1.2}{2002/07/27}{Using \cs{getthelinenumber} instead of \cs{getmodulo@vs}}
%
% \begin{macro}{\getthelinenumber}
% \cs{getthelinenumber}\marg{counter}\marg{start} returns \cs{thecounter} 
% if it is exactly divisible by \cs{linenumberfrequency}, provided this is 
% not zero. \meta{start} is the first number.
% \changes{v1.61802}{2008/01/30}{Generalised \cs{getthelinenumber} to cater
%          for set of first line number.}
%    \begin{macrocode}
\newcommand{\getthelinenumber}[2]{%
  \ifnum\@ne>\linemodnum%  no line numbers
  \else
    \ifnum\@ne=\linemodnum% every line numbered
      \@nameuse{the#1}%
    \else
      \@tempcnta=\@nameuse{c@#1}%
      \advance\@tempcnta -\@nameuse{c@#2}%
      \divide\@tempcnta \linemodnum
      \multiply\@tempcnta \linemodnum
      \advance\@tempcnta \@nameuse{c@#2}%
      \ifnum\@tempcnta=\@nameuse{c@#1}\@nameuse{the#1}\fi
    \fi
  \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ifaltindent}
% This should be set TRUE for indenting alternate lines.
%    \begin{macrocode}
\newif\ifaltindent
  \altindentfalse
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ifpattern}
% This should be set TRUE for indenting lines according to a pattern.
%    \begin{macrocode}
\newif\ifpattern
  \patternfalse
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ifstarpattern}
% This should be set TRUE for indenting lines according in a \Lenv{patverse*}
% environment.
% \changes{v1.1}{2002/03/8}{Added \cs{ifstarpattern}}
%    \begin{macrocode}
\newif\ifstarpattern
  \starpatternfalse

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\vleftskip}
% \begin{macro}{\vrightskip}
% Skips to the left and right of a line of verse.
% \changes{v1.1}{2002/03/24}{Added \cs{vleftskip} and \cs{vrightskip}}
% \changes{v1.2}{2002/07/27}{Changed defaults for \cs{vleftskip} and \cs{vrightskip}}
%    \begin{macrocode}
\newlength{\vleftskip}
  \setlength{\vleftskip}{3em}
\newlength{\vrightskip}
  \setlength{\vrightskip}{1em}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\stanzaskip}
% Skip between stanzas.
% \changes{v1.2}{2002/07/07}{Added \cs{stanzaskip}}
%    \begin{macrocode}
\newlength{\stanzaskip}
  \setlength{\stanzaskip}{\onelineskip}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\flagverse}
% \cs{flagverse}\marg{flag} inserts \meta{flag} at the left (of a line).
% \changes{v1.1}{2002/03/24}{Added \cs{flagverse}}
% \changes{v1.61803398}{2009/07/17}{Added bidi suport to \cs{flagverse}}
%    \begin{macrocode}
\newcommand{\flagverse}[1]{%
%%%  \hskip-\vleftskip\llap{#1}\hskip\vleftskip\ignorespaces}
  \hskip-\memRTLvleftskip\llap{#1}\hskip\memRTLvleftskip\ignorespaces}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\versewidth}
% The length \cs{versewidth} is a convenience length for the user.
%    \begin{macrocode}
\newlength{\versewidth}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\vgap}
% \begin{macro}{\vin}
% \begin{macro}{\vindent}
% The length \cs{vgap} is used as the basis for spacing. \cs{vin} makes
% a horizontal space of \cs{vgap} and \cs{vindent} is the indentation
% of wrapped lines.
%    \begin{macrocode}
\newlength{\vgap} \setlength{\vgap}{1.5em}
\newcommand{\vin}{\hspace*{\vgap}}
\newlength{\vindent} \setlength{\vindent}{2\vgap}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\vinphantom}
% Macro to leave blank space coresponding to a string.
% \changes{v1.4}{2003/02/27}{Added \cs{vinphantom} (patch 1.1)}
%    \begin{macrocode}
\newcommand{\vinphantom}[1]{\leavevmode\phantom{#1}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\vleftofline}
% Macro to insert something immediately to the left of the start 
% of the line.
% \changes{v1.618}{2005/09/14}{Added \cs{vleftofline}}
%    \begin{macrocode}
\newcommand*{\vleftofline}[1]{\leavevmode\llap{#1}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\vleftmargin}
% Length to adjust the default left margin within a verse environment.
% \changes{v1.618}{2005/09/18}{Added \cs{vleftmargin}}
%    \begin{macrocode}
\newdimen\vleftmargin
  \vleftmargin=\leftmargini

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\verselinebreak}
% Break a verse line by inserting \cs{newline}. 
% \changes{v1.1}{2002/03/28}{Modified \cs{verselinebreak}}
% \changes{v1.61803}{2008/01/30}{Removed extraneous space from \cs{verselinebreak} (mempatch v4.4, Aaron Rendahl)}
%    \begin{macrocode}
\newcommand{\verselinebreak}[1][\z@]{\newline\hspace*{#1}\ignorespaces}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\incr@vsline}
% Increment the line counters.
% \changes{v1.1}{2002/03/24}{Added poemline counter to \cs{incr@vsline}}
%    \begin{macrocode}
\newcommand{\incr@vsline}{%
  \refstepcounter{poemline}%
  \stepcounter{vslineno}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@vsifbang}
% Like the kernel \cs{@ifstar} except it looks for an exclamation mark!
% \changes{v1.1}{2002/03/24}{Added \cs{@vsifbang}}
%    \begin{macrocode}
\newcommand{\@vsifbang}[1]{\@ifnextchar !{\@firstoftwo{#1}}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@vsifgt}
% Like the kernel \cs{@ifstar} except it looks for a \verb?>? character.
% \changes{v1.1}{2002/03/28}{Added \cs{@vsifgt}}
%    \begin{macrocode}
\newcommand{\@vsifgt}[1]{\@ifnextchar >{\@firstoftwo{#1}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\verselinenumbersright}
% \begin{macro}{\verselinenumbersleft}
% \begin{macro}{\@vstypelinenum}
% Declarations for setting line numbers at the right (the default)
% or the left..
% \changes{v1.61803}{2008/01/30}{Added \cs{verselinenumbersright} and
%          \cs{verselinenumbersleft} (mempatch v4.4, v4.9)}
%    \begin{macrocode}
\newcommand*{\verselinenumbersright}{\def\@vstypelinenum{\@vslnumright}}
\newcommand*{\verselinenumbersleft}{\def\@vstypelinenum{\@vslnumleft}}
\verselinenumbersright

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@vslnumright}
% \begin{macro}{\@vslnumleft}
%   Internal code for right/left line numbers. This was reimplemented in 2024,
%   to be used in hooks instead of being added at the end of lines.
%   \changes{v1.61803398}{2009/07/17}{Added bidi support to \cs{@vslnumright}
%   and \cs{@vslnumleft}}
%   \changes{v3.7g}{2018/02/28}{Added \cs{nobreak} to both
%   \cs{@vslnumright} and \cs{@vslnumleft}, reported on
%   \protect\url{https://tex.stackexchange.com/a/415939/3929}, to avoid strange
%   double line breaks}
%   \changes{v3.8.3}{2024/02/06}{Reimplemented as they are no longer added at the end of the line}
%    \begin{macrocode}
\newcommand*{\@vslnumright}{%
  %\nobreak%
  %\hfill\rlap{%\kern\vrightskip\kern\rightmargin%
  %            \kern\memRTLvrightskip\kern\rightmargin%
  %            \vlvnumfont\getthelinenumber{poemline}{memfvsline}}
  \rlap{%
    \hspace{\dimexpr-\@totalleftmargin+\textwidth+\memRTLvrightskip}%
    {\vlvnumfont\getthelinenumber{poemline}{memfvsline}}%
  }%
}
\newcommand*{\@vslnumleft}{%
  % \nobreak%
  % \hfill\rlap{%\kern-\textwidth\kern-\vrightskip%
  %            \kern-\textwidth\kern-\memRTLvrightskip%
  %            \vlvnumfont\getthelinenumber{poemline}{memfvsline}}
  \llap{%
    \llap{\vlvnumfont\getthelinenumber{poemline}{memfvsline}}%
    \hspace{\dimexpr\@totalleftmargin+\memRTLvrightskip}%
  }%
}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@vscentercr}
% This puts the poem line number in the margin, increments
% the line numbers, and then deals with the options. It is based
% on the kernel \cs{@centercr}.
% This has to handle various forms of the \verb?\\? command: \verb?\\?,
% \verb?\\*?, \verb?\\!?, and \verb?\\>?, together with an optional length argument.
% \changes{v1.1}{2002/03/28}{Major rewrite of \cs{@vscentercr} and friends}
% \changes{v1.2}{2002/07/27}{Changed \cs{@vscentercr} to use general
%                linenumbering}
% \changes{v1.61803}{2008/01/30}{Changed \cs{@vscentercr} for left/right numbers
%                    (mempatch v4.4)}
% \changes{v3.8.3}{2024/02/06}{Removed the line numbering from \cs{@vscentercr}, they are now added via hooks}
%    \begin{macrocode}
\newcommand{\@vscentercr}{%
  \ifhmode \unskip\else \@nolnerr\fi
  % \@vstypelinenum% outcommented 2024/02/06
%    \end{macrocode}
% For \verb?>? call \cs{verselinebreak} to process it.
%    \begin{macrocode}
  \@vsifgt{\verselinebreak}{%
    \incr@vsline
%    \end{macrocode}
% If the call is \verb?\\*...? call \cs{@vsxcentercr} to handle the \verb?*...?.
% If the call is \verb?\\!?, do nothing.
% If the call is \verb?\\![...]?, call \cs{@vsicentercr} to handle the \verb?[...]?.
% Otherwise, call \cs{@vsxcentercr}.
%    \begin{macrocode}
    \par\@ifstar{\nobreak\@vsxcentercr}{%
%    \end{macrocode}
%    \begin{macrocode}
      \@vsifbang{\@ifnextchar[ {\@vsicentercr}{}}{\@vsxcentercr}}}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@vsxcentercr}
% Processes \verb?\\*?, and either calls cs{@vsicentercr} to handle a \verb?[length]?,
% or \cs{start@vsline}.
% \changes{v1.1}{2002/03/24}{Added \cs{@vsxcentercr}}
%    \begin{macrocode}
\newcommand{\@vsxcentercr}{\addvspace{-\parskip}%
  \@ifnextchar[ {\@vsicentercr}{\start@vsline}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@vsicentercr}
% Processes \verb?(\\...)[length]? and then calls \cs{start@vsline}.
% \changes{v1.1}{2002/03/24}{Added \cs{@vsicentercr}}
%    \begin{macrocode}
\def\@vsicentercr[#1]{\vskip #1\ignorespaces \start@vsline}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\start@vsline}
% This is called at the start of every verse line except the first.
% \changes{v1.1}{2002/03/28}{Added \cs{ifstarpattern} to \cs{start@vsline}}
% \changes{v1.61}{2004/03/21}{Used counter for vslineno, not \cs{thevslineno}
%                in \cs{start@vsline}}
%    \begin{macrocode}
\newcommand{\start@vsline}{%
  \ifaltindent\ifodd\c@vslineno\else\vin\fi\fi%
  \ifpattern\get@vsindent\fi%
  \ifstarpattern\getstar@vsindent\fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\theHpoemline}
% For the \Lpack{hyperref} package need a way of distinguishing
% lines of a poem. See the thread \textit{PDFTEX/Hyperef hates memoir verse
% environment?} on \ctt{} October 2002.
% \changes{v1.3}{2002/11/14}{Added verse counter and \cs{theHpoemline}}
% \changes{v3.7.19}{2022/10/25}{Changing \cs{theH...} definitions to
% \cs{def} for better compability with future hyperref}
%    \begin{macrocode}
\newcounter{verse}
\setcounter{verse}{0}
\def\theHpoemline{\theverse.\thepoemline}

%    \end{macrocode}
% \end{macro}
% 
% \begin{environment}{verse}
% The extended \Lenv{verse} environment. It sets the verse line counter,
% then defines the particular list environment adjusting the margins
% to center according to the length parameter. If the length parameter
% is at least the \cs{linewidth} then the `centering' defaults to
% the original \Lenv{verse} layout.
% \changes{v1.1}{2001/08/03}{Initialise the line counter to 1, not 0, in
%                all cases}
% \changes{v1.1}{2002/03/28}{Changes to verse environment for line numbering}
% \changes{v1.3}{2002/11/14}{Changes to verse environment for hyperref}
% \changes{v1.4}{2002/02/27}{Let verses wider than the \cs{linewidth}
%                            take the full width (patch(1.1)}
% \changes{v1.618}{2005/09/03}{Fix vertical spacing in the verse environment (mempatch v3.3)}
%    \begin{macrocode}
\newenvironment{verse}[1][\linewidth]{%
  \refstepcounter{verse}%
  \setcounter{poemline}{0}\refstepcounter{poemline}%
  \setcounter{vslineno}{1}%
  \let\\=\@vscentercr
  \list{}{\itemsep     \z@
          \itemindent  -\vindent
          \listparindent\itemindent
          \leftmargin   \vleftmargin
          \parsep       \stanzaskip
          \ifdim #1<\linewidth%   %% short line
            \rightmargin        \z@
            \leftmargin         \linewidth
            \advance\leftmargin -#1\relax
            \advance\leftmargin -0.5\leftmargin
            \advance\leftmargin \vindent
          \else
            \ifdim #1>\linewidth%  %% long line
              \rightmargin \z@
              \leftmargin  \vindent
            \else%                   %% default
              \rightmargin \leftmargin
              \advance\leftmargin \vindent
            \fi
          \fi}
  \item[]}{\endlist}

%    \end{macrocode}
% \end{environment}
% Then we use the env and paragraph hooks to add support for line
% numbers, the idea was suggested by Ulrike Fischer in chat. It is
% also listed as an example in \cite{SOURCE2E}.
% 
% \changes{v3.8.3}{2024/02/06}{Added the hooks to handle line numbers.}
%    \begin{macrocode}
\AddToHook{env/verse/begin}{%
  \AddToHook{para/begin}[memoir/versenum]{\@vstypelinenum}} 
\AddToHook{env/verse/end}{\RemoveFromHook{para/begin}[memoir/versenum]}

%    \end{macrocode}
%
% \begin{environment}{altverse}
% This sets \cs{altindenttrue} (afterwards false) and initialises the line counter.
% \changes{v1.1}{2002/03/28}{Added \cs{starpatternfalse} to altverse}
%    \begin{macrocode}
\newenvironment{altverse}%
  {\starpatternfalse\patternfalse\altindenttrue
   \setcounter{vslineno}{1}}%
  {\altindentfalse}

%    \end{macrocode}
% \end{environment}
%
%
% \subsection{Patterns}
%
%    The pattern code is based on the idea of converting a string of
% digits to an array of digits, and then being able to access the
% digit at a particular position in the array.
%
%
% \begin{macro}{\ifbounderror}
% A flag set TRUE if an attempt is made to access an array element outside
% the array limits.
%    \begin{macrocode}
\newif\ifbounderror
  \bounderrorfalse
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ifinteger}
%  A flag to indicate if a `number' is an integer (TRUE) or not (FALSE).
%    \begin{macrocode}
\newif\ifinteger

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\c@chrsinstr}
% A counter for the number of characters.
%    \begin{macrocode}
\newcounter{chrsinstr}  % CHARactersINSTRing

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\newarray}
% \cs{newarray}\marg{arrayname}\marg{low}\marg{high} defines
% an array called \meta{arrayname} (no backslash e.g. \verb?MyArray?), 
% with low and high limts \meta{low} and \meta{high}.
%    \begin{macrocode}
\newcommand{\newarray}[3]{%
  \@nameedef{#1-low}{#2}%
  \@nameedef{#1-high}{#3}%
  \ifnum #3<#2
    \@memerror{Limits for array #1 are in reverse order}{\@ehc}%
  \fi}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\stringtoarray}
% \cs{stringtoarray}\marg{arrayname}\marg{string} puts each character
% from \meta{string} sequentially into the \meta{arrayname} array, starting
% with \meta{low} = 1. It checks for an empty \meta{string} and handles that
% specially.
%    \begin{macrocode}
\newcommand{\stringtoarray}[2]{%
  \def\@vsarrayname{#1}%
  \protected@edef\the@vsstring{#2}%
  \newarray{\@vsarrayname}{1}{1}%
  \@ifmtarg{#2}{%
    \c@chrsinstr \z@
    \@namedef{\@vsarrayname-1}{}
  }{%
    \c@chrsinstr \@ne
    \expandafter\@vsstringtoarray \the@vsstring\@vsend
  }}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\@vsstringtoarray}
% Recursively adds characters to the array \cs{@vsarrayname}, incrementing
% the array's high limit.
%    \begin{macrocode}
\def\@vsstringtoarray #1#2\@vsend{%
  \@namedef{\@vsarrayname-\the\c@chrsinstr}{#1}
  \@nameedef{\@vsarrayname-high}{\the\c@chrsinstr}
  \@ifmtarg{#2}{%
    \def\@vsinext{}%
  }{%
    \advance\c@chrsinstr \@ne
    \def\@vsinext{%
      \@vsstringtoarray #2\@vsend%
    }%
  }
  \@vsinext}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\setarrayelement}
% \cs{setarrayelement}\marg{arrayname}\marg{index}\marg{value} sets
% the \meta{arrayname} array's element at \meta{index} to \meta{value}.
%    \begin{macrocode}
\newcommand{\setarrayelement}[3]{%
  \checkarrayindex{#1}{#2}%
  \@nameedef{#1-#2}{#3}}
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\getarrayelement}
% \cs{getarrayelement}\marg{arrayname}\marg{index}\marg{value}
% defines the parameterless macro \meta{value} (e.g., \cs{result}) to be
% the value at \meta{index} in the \meta{arrayname} array.
%    \begin{macrocode}
\newcommand{\getarrayelement}[3]{%
  \checkarrayindex{#1}{#2}%
  \protected@edef#3{\@nameuse{#1-#2}}}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\checkarrayindex}
% \cs{checkarrayindex}\marg{arrayname}\marg{index} checks that
% the \meta{index} of the \meta{arrayname} array is valid. \cs{ifbounderror}
% is set FALSE if everything is OK, otherwise it is set TRUE.
%    \begin{macrocode}
\newcommand{\checkarrayindex}[2]{%
  \bounderrorfalse
  \expandafter\ifx\csname #1-low\endcsname\relax%
    \ifpattern\else
      \@memerror{No array called #1}{\@ehc}%
    \fi
    \bounderrortrue
  \fi
  \ifnum #2<\@nameuse{#1-low}\relax%
    \ifpattern\else
      \@memerror{Index #2 outside limits for array #1}{\@ehc}%
    \fi
    \bounderrortrue
  \fi
  \ifnum #2>\@nameuse{#1-high}\relax%
    \ifpattern\else
      \@memerror{Index #2 outside limits for array #1}{\@ehc}%
    \fi
    \bounderrortrue
  \fi}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\arraytostring}
% \cs{arraytostring}\marg{arrayname}\marg{string} converts the
% characters in the \meta{arrayname} array into the parameterless macro
% \meta{string} (e.g., \cs{MyString}).
%    \begin{macrocode}
\newcommand{\arraytostring}[2]{%
  \def#2{}%
  \c@chrsinstr = \@nameuse{#1-low}%
  \@vsarraytostring{#1}{#2}}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\@vsarraytostring}
% \cs{@vsarraytostring}\marg{arrayname}\marg{string} recursively
% adds the (character) elements from \meta{arrayname} to \meta{string}.
%    \begin{macrocode}
\newcommand{\@vsarraytostring}[2]{%
  \ifnum\c@chrsinstr>\@nameuse{#1-high}\else
    \protected@edef#2{#2\@nameuse{#1-\thechrsinstr}}%
    \advance\c@chrsinstr\@ne%
    \@vsarraytostring{#1}{#2}%
  \fi}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\checkifinteger}
% \cs{checkifinteger}\marg{num} checks if \meta{num} is an integer.
% If it is, then \cs{ifinteger} is set TRUE, otherwise it is set FALSE.
% (Code based on Donald Arseneau's \Lpack{cite} package).
%    \begin{macrocode}
\newcommand{\checkifinteger}[1]{%
  \protected@edef\@vsa{#1}%
  \ifcat _\ifnum9<1\gobm{#1} _\else A\fi
    \integertrue%
  \else
    \integerfalse%
  \fi}
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\gobm}
% \cs{gobm}\marg{num} is defined as \meta{num}. It could be defined as: \\
% \verb?\newcommand{\gobm}[1]{\ifx-#1\expandafter\gobm\else#1\fi}? \\
% which would remove a leading minus sign (hyphen) from its argument
% (\verb?gobm? = gobble minus sign).
% (Code from a posting to \ctt{} by Donald Arseneau on 1997/07/21).
%    \begin{macrocode}
\newcommand{\gobm}[1]{#1}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\indentpattern}
% \cs{indentpattern}\marg{digits} stores \meta{digits} for use as
% a verse indentation pattern.
%    \begin{macrocode}
\newcommand{\indentpattern}[1]{%
  \stringtoarray{Array@vs}{#1}}
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\get@vsindent}
% \cs{get@vsindent} gets the indent pattern digit for the \cs{thevslineno},
% then uses this to specify the line indentation as \verb?digit*\vgap?.
% \changes{v1.61}{2004/03/21}{Changed \cs{get@vsindent} to use counter
% value number instead of \cs{thevslineno}}
%    \begin{macrocode}
\newcommand{\get@vsindent}{%
  \getarrayelement{Array@vs}{\number\value{vslineno}}{\@vspat}%
  \ifbounderror
    \arraytostring{Array@vs}{\@vsp@t}%
    \@memwarn{%
      Index `\thevslineno' for pattern `\@vsp@t' is out of bounds}%
    \def\@vspat{0}%
  \else
    \checkifinteger{\@vspat}%
    \ifinteger\else
      \arraytostring{Array@vs}{\@vsp@t}%
      \@memwarn{%
       `\@vspat' at index `\thevslineno' in pattern `\@vsp@t' 
       is not a digit}%
      \def\@vspat{0}%
    \fi
  \fi
  \ifcase\@vspat\else\hspace*{\@vspat\vgap}\fi}
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\getstar@vsindent}
% \cs{getstar@vsindent} gets the indent pattern digit for the \Lenv{patverse*}
% environment,
% then uses this to specify the line indentation as \verb?digit*\vgap?.
% It lets the pattern repeat by resetting the \texttt{vslineno} counter.
% \changes{v1.1}{2002/03/28}{Added \cs{getstar@vsindent}}
%    \begin{macrocode}
\newcommand{\getstar@vsindent}{%
  \expandafter\ifx\csname Array@vs-high\endcsname\relax
    \@memerror{A pattern has not been specified}{\@ehc}
  \else
    \ifnum\c@vslineno>\@nameuse{Array@vs-high}%
      \setcounter{vslineno}{1}%
     \fi
     \get@vsindent
  \fi}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{environment}{patverse}
% The environment for setting verse line indents according to a pattern.
% It starts by setting \cs{ifpattern} TRUE, any other flags to FALSE,
% and initialises the line number. It ends by setting \cs{ifpattern} FALSE.
% \changes{v1.1}{2002/03/28}{Added \cs{starpatternfalse} to patverse}
%    \begin{macrocode}
\newenvironment{patverse}%
  {\starpatternfalse\patterntrue\altindentfalse
   \setcounter{vslineno}{1}}%
  {\patternfalse}

%    \end{macrocode}
% \end{environment}
%
% \begin{environment}{patverse*}
% The environment for setting verse line indents according to a repeating
% pattern.
% It starts by setting \cs{ifstarpattern} TRUE, any other flags to FALSE,
% and initialises the line number. It ends by setting \cs{ifstarpattern} FALSE.
% \changes{v1.1}{2002/03/28}{Added patverse* environment}
%    \begin{macrocode}
\newenvironment{patverse*}%
  {\starpatterntrue\patternfalse\altindentfalse
   \setcounter{vslineno}{1}}%
  {\starpatternfalse}

%    \end{macrocode}
% \end{environment}
%
%
% \subsection{Titles}
%
% \begin{macro}{\poemtitle}
% Typeset a poem title (like \cs{section} or other). The actual work
% is done by \cs{@vsptitle} (plain) or \cs{@vssptitle} (starred).
%    \begin{macrocode}
\newcommand{\poemtitle}{\par%
  \secdef\@vsptitle\@vssptitle}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\poemtoc}
% The kind of entry \cs{poemtitle} is to make in the ToC.
%    \begin{macrocode}
\newcommand{\poemtoc}{section}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\mempoeminfo}
% \begin{macro}{\mempoemstarinfo}
% \verb?\mempoeminfo{title}? \\
% \verb?\mempoemstarinfo{title}? \\
% \changes{v1.61803}{2008/01/30}{Made \cs{mempoeminfo} and fiends \cs{long}
%                   (mempatch v4.9)}
%    \begin{macrocode}
\newcommand{\mempoeminfo}[1]{}
\newcommand{\mempoemstarinfo}[1]{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@vsptitle}
% Typeset a \cs{poemtitle}.
% \changes{v1.3}{2002/11/14}{Added \cs{phantomsection} to \cs{@vsptitle}}
% \changes{v1.4}{2003/11/16}{Added \cs{M@gettitle} to \cs{@vsptitle}}
% \changes{v3.8.4}{2025/09/16}{Replaced \cs{phantomsection} by suitable \cs{MakeLinkTarget}}
%    \begin{macrocode}
\long\def\@vsptitle[#1]#2{%
  % \phantomsection
  \M@gettitle{#1}%
  \MakeLinkTarget[\poemtoc]{}%
  \addcontentsline{toc}{\poemtoc}{#1}%
  \mempoeminfo{#1}%
  \poemtitlemark{#1}%
  \@vstypeptitle{#2}%
  \@afterheading}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@vssptitle}
% Typeset a \cs{poemtitle*}.
% \changes{v1.4}{2003/11/16}{Added \cs{M@gettitle} to \cs{@vssptitle}}
% \changes{v3.8.4}{2025/09/16}{Added a \cs{MakeLinkTarget}}
%    \begin{macrocode}
\long\def\@vssptitle#1{%
  \M@gettitle{#1}%
  \MakeLinkTarget[\poemtoc]{}%
  \mempoemstarinfo{#1}%
  \@vstypeptitle{#1}%
  \@afterheading}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@vstypeptitle}
% This \emph{really} typesets the title.
%    \begin{macrocode}
\newcommand{\@vstypeptitle}[1]{%
  \vspace{\beforepoemtitleskip}%
  {\poemtitlefont #1\par}%
  \vspace{\afterpoemtitleskip}%
}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\poemtitlefont}
% \begin{macro}{\poemtitlemark}
% Sets the appearance to the title of a poem, and something for a header.
%    \begin{macrocode}
\newcommand{\poemtitlefont}{\normalfont\large\bfseries\centering}
\newcommand{\poemtitlemark}[1]{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\beforepoemtitleskip}
% \begin{macro}{\afterpoemtitleskip}
% Lengths before and after a poem title, using approximately \cs{section} 
% values.
%    \begin{macrocode}
\newlength{\beforepoemtitleskip}
  \setlength{\beforepoemtitleskip}{3.5ex \@plus 1ex \@minus .2ex}
\newlength{\afterpoemtitleskip}
  \setlength{\afterpoemtitleskip}{2.3ex \@plus.2ex}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\if@numptitle}
% \begin{macro}{\@numptitletrue}
% \begin{macro}{\@numptitlefalse}
% \begin{macro}{\NumberPoemTitle}
% \begin{macro}{\PlainPoemTitle}
% Following the \cs{NumberPoemTitle} declaration \cs{PoemTitle}s are numbered.
% The \cs{PlainPoemTitle} declaration produces unnumbered titles.
%    \begin{macrocode}
\newif\if@numptitle
\newcommand*{\NumberPoemTitle}{\@numptitletrue}
\newcommand*{\PlainPoemTitle}{\@numptitlefalse}
\NumberPoemTitle

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\c@poem}
% \begin{macro}{\thepoem}
% \begin{macro}{\theHpoem}
% Counter for poem titles.
% \changes{v3.8}{2023/06/20}{Changed \cs{theHpoem} to
% \cs{providecommand} per request of the kernel team}
%    \begin{macrocode}
\newcounter{poem}\setcounter{poem}{0}
\renewcommand*{\thepoem}{\@arabic\c@poem}
\providecommand*{\theHpoem}{\the\value{poem}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\poemtitlestarmark}
% \begin{macro}{\poemtitlepstyle}
% \begin{macro}{\poemtitlestarpstyle}
% \cs{poemtitlemark}\marg{poemf@rhdr} is used for marks for a \cs{PoemTitle} and 
% \cs{poemtitlestarmark}\marg{poemf@hdr} is for marks for \cs{PoemTitle*}. 
% The \cs{poemtitlepstyle} and \cs{poemtitlestarpstyle} macros are provided
% as hooks so that, for example, pagestyles can be set for the regular
% and starred versions of \cs{PoemTitle}. By default these macros do nothing.
%    \begin{macrocode}
\newcommand*{\poemtitlestarmark}[1]{}
\newcommand*{\poemtitlepstyle}{}
\newcommand*{\poemtitlestarpstyle}{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\PoemTitle}
%    The command to produce a article style chapter-like (numbered) poem title.
% \changes{v1.618}{2005/09/09}{Added \cs{PoemTitle}}
%    \begin{macrocode}
\newcommand\PoemTitle{%
  \par
  \@afterindentfalse
  \@ifstar{\@m@msPoemTitle}{\@m@mPoemTitle}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@m@mPoemTitle}
% \begin{macro}{\poemt@c}
% Intermediate and support macros for the extra optional argument
% to \cs{PoemTitle}. Have to do this long windedly otherwise dear old
% \Lpack{hyperref} barfs.
%    \begin{macrocode}
\newcommand{\@m@mPoemTitle}[1][]{%
  \def\poemt@c{#1}% capture first optional arg
  \@ifnextchar[{\@PoemTitle}{\@PoemTitle[]}%
}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\memPoemTitleinfo}
% \begin{macro}{\memPoemTitlestarinfo}
% \verb?\memPoemTitleinfo{num}{toc}{head}{full}? \\
% \verb?\memPoemTitlestarinfo{short}{full}?
%    \begin{macrocode}
\newcommand{\memPoemTitleinfo}[4]{}
\newcommand{\memPoemTitlestarinfo}[2]{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@PoemTitle}
% \begin{macro}{\poemf@rtoc}
% \begin{macro}{\poemf@rhdr}
% \cs{@PoemTitle}\oarg{tocmark}\marg{title}
% typesets the title of a \cs{PoemTitle}. 
% There is a number for \cs{@numptitletrue} and \cs{@mainmattertrue}.
% \changes{v3.8.4}{2025/09/16}{Replaced \cs{phantomsection} with \cs{MakeLinkTarget}
% in a better place}
%    \begin{macrocode}
\def\@PoemTitle[#1]#2{%
  %\phantomsection
  \ifx\poemt@c\@empty % no optional args
    \def\poemf@rtoc{#2}%
    \def\poemf@rhdr{#2}%
  \else                  % at least one opt arg
    \let\poemf@rtoc\poemt@c
    \ifx\@empty#1\@empty
      \let\poemf@rhdr\poemt@c
    \else
      \def\poemf@rhdr{#1}%
    \fi
  \fi
  \m@m@Andfalse
  \if@numptitle
    \if@mainmatter
      \m@m@Andtrue
    \fi
  \fi
  \ifm@m@And
    \refstepcounter{poem}%
  \else
    \MakeLinkTarget[poem]{}%
  \fi
%    \end{macrocode}
% Store the (short) title via \cs{poemtitlemark} and call
% \cs{\@makePoemTitlehead} to do the typesetting.
%    \begin{macrocode}
  \@makePoemTitlehead{#2}%
  \@afterheading
  \poemtitlemark{\poemf@rhdr}%
  \poemtitlepstyle
%    \end{macrocode}
% Add the title to the ToC.
%    \begin{macrocode}
  \ifm@m@And
    \addcontentsline{toc}{\poemtoc}{%
      \protect\numberline{\thepoem}\poemf@rtoc}%
    \memPoemTitleinfo{\thepoem}{\poemf@rtoc}{\poemf@rhdr}{#2}%
  \else
    \addcontentsline{toc}{\poemtoc}{\poemf@rtoc}%
    \memPoemTitleinfo{}{\poemf@rtoc}{\poemf@rhdr}{#2}%
  \fi
%    \end{macrocode}
% Add hook for title referencing.
% \changes{v3.70.20}{2023/07/24}{Redef of \cs{M@gettitle} requires
% expansion for macro arguments}
%    \begin{macrocode}
  \ifheadnameref\ExpandArgs{V}\M@gettitle\poemf@rhdr\else\ExpandArgs{V}\M@gettitle\poemf@rtoc\fi}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\@makePoemTitlehead}
% This \emph{really} typesets a \cs{PoemTitle}. Leave some whitespace.
%    \begin{macrocode}
\def\@makePoemTitlehead#1{{%
  \PoemTitleheadstart
  \parindent \z@ \normalfont
%    \end{macrocode}
% If there is a number, typeset it, otherwise call \cs{printPoemTitlenonum}.
%    \begin{macrocode}
   \ifm@m@And
     \printPoemTitlenum 
     \afterPoemTitlenum
   \else
     \printPoemTitlenonum
   \fi
%    \end{macrocode}
% Typeset the title.
%    \begin{macrocode}
   \interlinepenalty\@M
   \printPoemTitletitle{#1}% 
   \afterPoemTitle}}

%    \end{macrocode}
% \end{macro}
%
%
%
% \begin{macro}{\@PTchs@def@ult}
% This sets up all the definitions used in \cs{@makePoemTitlehead}
% and \cs{@makesPoemTitlehead}.
% \begin{macro}{\PoemTitleheadstart}
% \begin{macro}{\printPoemTitlenum}
% \begin{macro}{\afterPoemTitlenum}
% \begin{macro}{\printPoemTitlenonum}
% \begin{macro}{\printPoemTitletitle}
% \begin{macro}{\afterPoemTitle}
%    \begin{macrocode}
\newcommand{\@PTchs@def@ult}{%
  \def\PoemTitleheadstart{\vspace{\beforePoemTitleskip}}
  \def\printPoemTitlenum{\PoemTitlenumfont \thepoem}
  \def\afterPoemTitlenum{\par\nobreak\vskip \midPoemTitleskip}
  \def\printPoemTitlenonum{}
  \def\printPoemTitletitle##1{\PoemTitlefont ##1}
  \def\afterPoemTitle{\par\nobreak\vskip \afterPoemTitleskip}}
\@PTchs@def@ult

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% 
% \begin{macro}{\PoemTitlenumfont}
% \begin{macro}{\PoemTitlefont}
% Fonts for setting the Poem Title number and title.
%    \begin{macrocode}
\newcommand*{\PoemTitlenumfont}{\normalfont\large\centering}
\newcommand*{\PoemTitlefont}{\normalfont\large\centering}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\beforePoemTitleskip}
% \begin{macro}{\midPoemTitleskip}
% \begin{macro}{\afterPoemTitleskip}
% Lengths separating the various parts of a Poem Title heading.
%    \begin{macrocode}
\newlength{\beforePoemTitleskip}
  \setlength{\beforePoemTitleskip}{1\onelineskip}
\newlength{\midPoemTitleskip}
  \setlength{\midPoemTitleskip}{0pt}
\newlength{\afterPoemTitleskip}
  \setlength{\afterPoemTitleskip}{1\onelineskip}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\@m@msPoemTitle}
% This deals with the optional argument for starred PoemTitles.
%    \begin{macrocode}
\newcommand{\@m@msPoemTitle}[2][\@empty]{%
  \@sPoemTitle{#2}%
  \ifx \@empty#1
    \def\poemf@rhdr{#2}%
  \else   % opt arg
    \def\poemf@rhdr{#1}%
  \fi
  \poemtitlestarmark{\poemf@rhdr}%
  \poemtitlestarpstyle
  \memPoemTitlestarinfo{\poemf@rhdr}{#2}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@sPoemTitle}
% \cs{@sPoemTitle}\marg{long} typesets the title of a 
% \cs{PoemTitle*}. It is easier than the \cs{@PoemTitle} as there is no number
% or ToC entry to worry about.
%    \begin{macrocode}
\newcommand{\@sPoemTitle}[1]{%
  \@makesPoemTitlehead{#1}%
  \@afterheading
  \M@gettitle{#1}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@makesPoemTitlehead}
% This \emph{really} typesets a \cs{PoemTitle*}, and is similar to 
% \cs{@makePoemTitlehead}.
%    \begin{macrocode}
\def\@makesPoemTitlehead#1{{%
  \PoemTitleheadstart
  \parindent \z@ \normalfont
  \printPoemTitlenonum
  \interlinepenalty\@M
  \printPoemTitletitle{#1}
  \afterPoemTitle}}

%    \end{macrocode}
% \end{macro}
%
%
%
%
% \section{Setting parameters for existing environments}
%
% \subsection{Array and tabular}
%
% \begin{macro}{\arraycolsep}
%    The columns in an array environment are separated by
%    2\cs{arraycolsep}.
%    \begin{macrocode}
\setlength\arraycolsep{5\p@}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\tabcolsep}
%    The columns in an tabular environment are separated by
%    2\cs{tabcolsep}.
%    \begin{macrocode}
\setlength\tabcolsep{6\p@}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\arrayrulewidth}
%    The width of rules in the array and tabular environments is given
%    by\\ \cs{arrayrulewidth}.
%    \begin{macrocode}
\setlength\arrayrulewidth{.4\p@}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\doublerulesep}
%    The space between adjacent rules in the array and tabular
%    environments is given by \cs{doublerulesep}.
%    \begin{macrocode}
\setlength\doublerulesep{2\p@}
%    \end{macrocode}
% \end{macro}
%
% \subsection{Tabbing}
%
% \begin{macro}{\tabbingsep}
%    This controls the space that the \verb?\'? command puts in. (See
%    \LaTeX{} manual for an explanation.)
%    \begin{macrocode}
\setlength\tabbingsep{\labelsep}

%    \end{macrocode}
% \end{macro}
%
% \subsection{Minipage}
%
% \begin{macro}{\@minipagerestore}
%    The macro \cs{@minipagerestore} is called upon entry to a minipage
%    environment to set up things that are to be handled differently
%    inside a minipage environment. In the standard styles it does
%    nothing, as was the case originally for memoir.
%
% Memoir extends it to support verbatim footnotes (see later) in minipages
% and also for abnormal parskips (see later).
% \changes{v1.61803}{2008/01/30}{Collected \cs{@minipagerestore} modifications together}
%    \begin{macrocode}
\newcommand{\@minipagerestore}{%
%    \end{macrocode}
% For \cs{verbfootnote} to work in a minipage we have to use 
% \cs{@verbmpfootnotetext} instead of \cs{@verbfootnotetext}.
%    \begin{macrocode}
  \let\@verbfootnotetext\@verbmpfootnotetext
%    \end{macrocode}
% The next is for enabling the extended footnotes in a minipage.
%    \begin{macrocode}
  \m@mdoextrafeetmini
%    \end{macrocode}
% And this is for abnormal parskips.
%    \begin{macrocode}
  \ifm@mnzpskip \parskip=\m@mabparskip\fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@mpfootins}
%    Minipages have their own footnotes; \verb?\skip\@mpfootins? plays
%    the same r\^ole for footnotes in a minipage as \verb?\skip\footins? does
%    for ordinary footnotes.
%
%    \begin{macrocode}
\skip\@mpfootins = \skip\footins

%    \end{macrocode}
% \end{macro}
%
% \subsection{Framed boxes}
%
% \begin{macro}{\fboxsep}
%    The space left by \cs{fbox} and \cs{framebox} between the box and the
%    text in it.
% \begin{macro}{\fboxrule}
%    The width of the rules in the box made by \cs{fbox} and \cs{framebox}.
%    \begin{macrocode}
\setlength\fboxsep{3\p@}
\setlength\fboxrule{.4\p@}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \subsection{Equation and eqnarray}
%
% \begin{macro}{\theequation}
%    The equation counter will be reset at beginning of a new chapter
%    and the equation number will be prefixed by the chapter number.
%
%    This code  must follow the \cs{chapter} definition, or more exactly
%    the definition of the chapter counter.
%    \begin{macrocode}
\@addtoreset{equation}{chapter}
\renewcommand{\theequation}{%
  \ifnum \c@chapter>\z@ \thechapter.\fi \@arabic\c@equation}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\jot}
%    \cs{jot} is the extra space added between lines of an eqnarray
%    environment. The default value is used.
%    \begin{macrocode}
% \setlength\jot{3pt}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@eqnnum}
%    The macro \cs{@eqnnum} defines how equation numbers are to appear in
%    equations. Again the default is used.
%
%    \begin{macrocode}
% \def\@eqnnum{(\theequation)}

%    \end{macrocode}
% \end{macro}
%
%
% \section{Array and tabularx}
%
% \subsection{Array}%
%
% Here ealier versions of the class had an embedded copy of the
% \Lpack{array} package. Now replaced by requiring the packge instead.
%    \begin{macrocode}
\RequirePackage{array}[2018/04/30]
%    \end{macrocode}
%
% \subsubsection{Class additions to Array}
% 
% \begin{macro}{\m@mold@addamp}
% \begin{macro}{\m@m@addamp}
% \begin{macro}{\@addamp}
%
%    In the preamble a \verb?&? has to be inserted between any two columns;
%    before the first column there should not be a \verb?&?. As the user
%    preamble may start with a \verb?|? we have to remember somehow
%    if we have already inserted a \verb?#? (i.e.\ a column). This is done
%    with the boolean variable \cs{if@firstamp} that we test in
%    \cs{@addamp}, the macro that inserts the \verb?&?.
%
% \begin{PW}
%    PW: Later on, for horizontal lines in `continuous' tabulars,
% I need to know how many columns there are in a tabular. I need a modified
% kernel's \cs{@addamp} to do this and use the kernel's \cs{@curtab}
% (a counter used in tabbing) to store the number of columns.
%
% \cs{m@mold@addamp} stores the kernel's definition of \cs{@addamp}, and
% \cs{m@m@addamp} is the revised definition.
% \end{PW}
%
% \changes{v3.7r}{2022/06/20}{Fixed sporious spaces}
%    \begin{macrocode}
\newif \@iffirstamp
\let\m@mold@addamp\@addamp
\newcommand*{\m@m@addamp}{%
  \if@firstamp 
    \@firstampfalse
    \global\@curtab\@ne
  \else
    \@addtopreamble{&}% 
    \global\advance\@curtab\@ne  
  \fi}
\let\@addamp\m@m@addamp

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%



% \subsection{D column specifiers} \label{sec:dcolumns}
%
%
% Here ealier versions of the class had an embedded copy of the
% \Lpack{cdolumn} package. Now replaced by requiring the packge instead.
%    \begin{macrocode}
\RequirePackage{dcolumn}[2014/10/28]
%    \end{macrocode}
% The embeded copy is outcommented for now and will be removed in a
% later version.
%
% \changes{v3.7h}{2018/09/06}{Outcommented the embedded copy of
% \Lpack{dcolumn} and replaced it with requiring the \Lpack{dcolumn} package
% instead.}
%
%
%
% \subsection{Support for delimeters}
%
% Here ealier versions of the class had an embedded copy of the
% \Lpack{dearray} package. Now replaced by requiring the packge instead.
%    \begin{macrocode}
\RequirePackage{delarray}[2014/10/28]
%    \end{macrocode}
% The embeded copy is outcommented for now and will be removed in a
% later version.
%
%
%
% \subsection{The tabularx environment}
%
% Here ealier versions of the class had an embedded copy of the
% \Lpack{tabularx} package. Now replaced by requiring the packge instead.
%    \begin{macrocode}
\RequirePackage{tabularx}[2016/02/03]
%    \end{macrocode}
%  
% \subsection{Fear's rules}
%
%    Simon Fear disapproves of the default \LaTeX{} table rules and
% wrote the \Lpack{booktabs} package~\cite{BOOKTABS} to provide
% better horizontal rules. Like many typographers, he abhors vertical rules.
%
%
% \begin{macro}{\bktabrule}
% The rules in this section are based on \verb?\hrule \@height#1? but this 
% does not 
% work for continuous tabulars. Provide a version of this that
% can be \cs{let} when necessary.
%    \begin{macrocode}
\newcommand*{\bktabrule}[1]{%
  \hrule \@height#1}

%    \end{macrocode}
% \end{macro}
%
% As of Summer 2023 we instead load \Lpack{booktabs} directly and
% remove it from emulation. The only change from the class code and
% the current \Lpack{booktabs} code was using \cmd{\bktabrule} which
% never seem to be changed at all.
% \changes{v3.8}{2023/07/28}{Replaced booktabs embedding by loading
% \Lpack{booktabs}}
%    \begin{macrocode}
\RequirePackage{booktabs}[2020/01/12]
%    \end{macrocode}
% 
%
% \subsection{Continuous tabulars}
%
%    The standard \texttt{tabular} environment is wrapped inside a box
% (see \verb?\@tabular?),
% which means that it cannot break across pages. Equivalent environments
% are provided which are not boxed and so can continue across page 
% boundaries.
%
% \begin{macro}{\ctableftskip}
% \begin{macro}{\ctabrightskip}
% These skips are inserted at the left and right of continuous tabulars
% so that their horizontal location can be specified.
%    \begin{macrocode}
\newskip\ctableftskip \ctableftskip=\fill
\newskip\ctabrightskip \ctabrightskip=\fill

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\ctabular*}
% \begin{macro}{\@ctabularstar}
% This starts off the \texttt{ctabular*} continuous tabular environment.
% The default location is centered. NOTE: This is not for release.
%    \begin{macrocode}
\expandafter\def\csname ctabular*\endcsname{%
  \@ifnextchar[ {\@ctabularstar}{\@ctabularstar[c]}}
\def\@ctabularstar[#1]#2{\global\@curtab\@ne
  \ctableftskip\fill
  \ctabrightskip\fill
  \if l#1% left
    \ctableftskip\z@ 
  \else
    \if r#1% right
       \ctabrightskip\z@
    \fi
  \fi
  \setlength\dimen@{#2}%
  \xdef\@halignto{to\the\dimen@}\NC@tabular}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\ctabular}
% \verb?\ctabular? is similar to \verb?\ctabular*? except that the
% width is known to be \verb?\hsize?.
%    \begin{macrocode}
\newcommand*{\ctabular}[1][c]{\global\@curtab\@ne
  \ctableftskip\fill
  \ctabrightskip\fill
  \if l#1% left
    \ctableftskip\z@ 
  \else
    \if r#1% right
      \ctabrightskip\z@
    \fi
  \fi
  \gdef\@halignto{to\hsize}\NC@tabular}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\NC@tabular}
% \verb?\NC@tabular?
%    \begin{macrocode}
\newcommand*{\NC@tabular}{%
  \par
  \addvspace{\topsep}
  \col@sep\tabcolsep
  \let\d@llarbegin\begingroup
  \let\d@llarend\endgroup
  \@NCtabarray}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@NCialign}
%    \begin{macrocode}
\newcommand*{\@NCialign}{\everycr{}\tabskip\ctableftskip\halign}

%    \end{macrocode}
% \end{macro}
%  
% \begin{macro}{\@NCtabarray}
% Effectively a modified version of \verb?\@array? 
%    \begin{macrocode}
\newcommand*{\@NCtabarray}[1]{%
  \@tempdima \ht\strutbox
  \advance\@tempdima\extrarowheight
  \setbox \@arstrutbox \hbox{\vrule
    \@height \arraystretch \@tempdima
    \@depth \arraystretch \dp\strutbox
    \@width\z@}%
  \begingroup
%%    \@mkpream{@{\hspace{\@totalleftmargin}}#1@{}}%
    \@mkpream{#1}%
    \xdef\@preamble{\@NCialign \@halignto
                    \bgroup & \tabskip\z@
                      \@arstrut
                      \@preamble
                      \tabskip\ctabrightskip
                      \cr}%
  \endgroup
  \let\@sharp ##\let\protect\relax
  \lineskip\z@
  \baselineskip\z@
  \let\\\@arraycr
  \let\tabularnewline\\%
  \let\par\@empty
  \ctabsetlines
  \@preamble
}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\endctabular}
% \begin{macro}{\endctabular*}
% End the environments.
%    \begin{macrocode}
\def\endctabular{%
  \crcr \egroup
  \gdef\@preamble{}%
  \addvspace{\topsep}
  \noindent}
\expandafter\let\csname endctabular*\endcsname=\endctabular

%    \end{macrocode}
% \end{macro}
% \end{macro}
%  
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
% \subsubsection{Horizontal lines}
%
%   The standard \cs{hline} can produce odd results when used with
% continuous tabulars, but \cs{hhline} or \cs{cline} are OK. 
% I want a version of \cs{hline}
% that works with continuous tabulars and has an adjustable width
% (i.e., thickness). This will be based on a modified \cs{cline}
%
% For reference, here are the essentials of the kernel's definitions.
% \begin{verbatim}
% \def\hline{%
%    \noalign{\ifnum0=`}\fi\hrule \@height \arrayrulewidth \futurelet
%    \reserved@a\@xhline}
% \def\@xhline{%
%    \ifx\reserved@a\hline
%      \vskip\doublerulesep
%      \vskip-\arrayrulewidth
%    \fi
%    \ifnum0=`{\fi}}
% \def\cline#1{\@cline#1\@nil}
% \def\@cline#1-#2\@nil{%
%   \omit
%   \@multicnt#1%
%   \advance\@multispan\m@ne
%   \ifnum\@multicnt=\@ne\@firstofone{&\omit}\fi
%   \@multicnt#2%
%   \advance\@multicnt-#1%
%   \advance\@multispan\@ne
%   \leaders\hrule\@height\arrayrulewidth\hfill
%   \cr
%   \noalign{\vskip-\arrayrulewidth}}
% \end{verbatim}
%
% \begin{macro}{\memcline}
% \begin{macro}{\m@m@cline} 
% This is a version of the kernel \cs{cline} code that provides
% a variable width.
%    \begin{macrocode}
\newcommand*{\memcline}[2]{\m@m@cline[#1]#2\@nil}
\def\m@m@cline[#1]#2-#3\@nil{%
  \omit
  \@multicnt#2%
  \advance\@multispan\m@ne
  \ifnum\@multicnt=\@ne\@firstofone{&\omit}\fi
  \@multicnt#3%
  \advance\@multicnt-#2%
  \advance\@multispan\@ne
  \leaders\hrule\@height #1\hfill  % <- variable \@height value
  \cr
  \noalign{\vskip- #1}}            % <- variable \@height value

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\memhline}
% \begin{macro}{\m@mhline}
% A version of \cs{hline}, based on \cs{memcline}, taking a 
% rule width as argument. It draws a \cs{memcline} from the
% first to the last (\cs{@curtab}) column.
%    \begin{macrocode}
\newcommand*{\memhline}[1][\arrayrulewidth]{\memcline{#1}{1-\@curtab}}
\newcommand*{\m@mhline}{\cline{1-\@curtab}}
%    \end{macrocode}
%\end{macro}
%\end{macro}
%
% Fear's rules also do not play well within continuous tabulars.
%
% \begin{macro}{\m@m@BTnormal}
% Special version of \cs{@BTnormal}
%    \begin{macrocode}
\def\m@m@BTnormal{%
  \ifnum0=`{\fi}   % closes the \noalign
  \multispan{\@curtab} \leaders\bktabrule{\@thisrulewidth}\hfill\cr
  \noalign{\ifnum0=`}\fi
  \futurenonspacelet\@tempa\@BTendrule}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\ctabsetlines}
% Continuous tabulars cannot use the standard horizontal lines.
%    \begin{macrocode}
\def\ctabsetlines{%
  \let\hline\m@mhline
  \let\@BTnormal\m@m@BTnormal}

%    \end{macrocode}
% \end{macro}
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
% \subsection{Automated tabulations}
%
%
% It can be convenient, especially while drafting a document, to have
% a list of items put into a tabular without having to mark the ends
% of the rows. 
%
% The following is based on plain \TeX{} code given on pages 307--308 of
% \textit{TeX for the Impatient}~\cite{bk:Impatient}, which provides
% code for typesetting in columns.
%
% 
% \begin{macro}{\abovecolumnspenalty}
% \begin{macro}{\@linestogo}
% \begin{macro}{\@cellstogo}
% \begin{macro}{\@cellsincolumn}
% \begin{macro}{\crtok}
% Counters and such.
%    \begin{macrocode}
\newcount\abovecolumnspenalty
  \abovecolumnspenalty=10000
\newcount\@linestogo           % lines remaining to be procesed
\newcount\@cellstogo           % cells remaining in column or row
\newcount\@cellsincolumn         % number of lines per column
\newtoks\crtok
  \crtok = {\cr}%

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@mincolumnwidth}
% \begin{macro}{\c@lleftskip}
% \begin{macro}{\c@lrightskip}
% More things
%   \begin{macrocode}
\newdimen\@mincolumnwidth
\let\c@lleftskip\hfil   % left skip within a column
\let\c@lrightskip\hfil % right skip within a column

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\preautotab}
% \begin{macro}{\postautotab}
% Hooks into the auto tabulations.
%    \begin{macrocode}
\let\preautotab\relax
\let\postautotab\relax

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\autocols}
% \cs{autocols}\oarg{width}\marg{pos}\marg{num}\marg{style}\marg{comma separated list}
% arranges the elements in the \meta{comma separated list} into \meta{num}
% columns, the elements filling each column before moving to the next.
% That is, the elements are ordered top to bottom and left to right.
%    \begin{macrocode}
\newcommand{\autocols}[5][0pt]{\par\begingroup
  \ctabsetlines
%    \end{macrocode}
% Set the table position
%    \begin{macrocode}
  \if l#2 
    \raggedright
  \else
    \if r#2
      \raggedleft
    \else
      \centering
    \fi
  \fi
%    \end{macrocode}
% Set the column position style
%    \begin{macrocode}
  \let\c@lleftskip\hfil
  \let\c@lrightskip\hfil
  \if l#4 
    \let\c@lleftskip\relax
  \else
    \if r#4
      \let\c@lrightskip\relax
    \fi
  \fi
%    \end{macrocode}
% Count the number of entries and the minimum width (max entry width)
% for the columns.
%    \begin{macrocode}
  \@mincolumnwidth\z@
  \TX@cols=#3
  \@curtab=#3
  \@linestogo\z@
  \@for\@tempa:=#5\do{
    \advance\@linestogo\@ne
    \settowidth{\@tempdima}{\@tempa}
    \ifdim\@tempdima>\@mincolumnwidth
      \@mincolumnwidth=\@tempdima
    \fi
  }
  \advance\@mincolumnwidth\tabcolsep
  \linespercol
%    \end{macrocode}
% Specify what is to be done after every entry
%    \begin{macrocode}
  \def\@endcolumnactions{%
    \global\advance\@linestogo\m@ne
    \ifnum\@cellstogo<\tw@
      \global\advance\TX@cols\m@ne
      \ifnum\TX@cols>\z@\linespercol\fi
      \the\crtok
    \else 
        &\global\advance\@cellstogo\m@ne
    \fi}%
%    \end{macrocode}
% Calculate the width of the columns
%    \begin{macrocode}
  \ifdim #1 > \z@
    \TX@col@width=#1
    \divide\TX@col@width \TX@cols
  \else
    \TX@col@width=\@mincolumnwidth
  \fi
  \penalty\abovecolumnspenalty
  \noindent% usually not a paragraph
%    \end{macrocode}
% Create most of the preamble by looping to add \cs{@cellsincolumn}-1 slots,
% then the last one which is different.
%    \begin{macrocode}
  \def\@preamble{}%
  \begingroup
    \let\@sharp\relax
    \ifnum\@cellsincolumn>\@ne
      \loop
        \g@addto@macro{\@preamble}{%
          \hb@xt@ \TX@col@width{%
               \c@lleftskip\strut\@sharp\c@lrightskip} &}%
        \advance\@cellsincolumn\m@ne
      \ifnum\@cellsincolumn>\@ne
      \repeat
    \fi
    \g@addto@macro{\@preamble}{%
      \hb@xt@ \TX@col@width{\c@lleftskip\strut\@sharp\c@lrightskip}}%
  \endgroup
  \let\@sharp ##
%    \end{macrocode}
% Start the \cs{valign}
%    \begin{macrocode}
  \tabskip\ctableftskip
%%  \tabskip\z@
  \valign \bgroup
    \tabskip\z@
    \@preamble
    \tabskip\ctabrightskip\cr
%    \end{macrocode}
% Add all the entries then finish off.
%    \begin{macrocode}
    \@for\@tempa:=#5\do{
      \@tempa\unskip\space\@endcolumnactions}%
    \the\crtok \egroup \par \endgroup}
  
%    \end{macrocode}
% \end{macro}
%  
%
% \begin{macro}{\linespercol}
% \cs{linespercol} calculates the maximum number of lines that go into
% a column, where there are \cs{TX@cols} columns and \cs{@linestogo}
% lines, so that the columns are balanced as well as possible. The result
% is \cs{@cellstogo}
%    \begin{macrocode}
\newcommand*{\linespercol}{%
  \@cellsincolumn=\@linestogo
  \divide\@cellsincolumn \TX@cols
  \@cellstogo=\@cellsincolumn
  \multiply\@cellstogo \TX@cols
  \@tempcnta=\@linestogo
  \advance\@tempcnta -\@cellstogo
  \ifnum \@tempcnta>\z@
    \advance\@cellsincolumn \@ne
  \fi
  \global\@cellstogo=\@cellsincolumn}

%    \end{macrocode}
% \end{macro}
%  
%
% \begin{macro}{\autorows}
% \cs{autorows}\oarg{width}\marg{pos}\marg{num}\marg{style}\marg{comma separated list}
% arranges the elements in the \meta{comma separated list} into \meta{num}
% columns, the elements filling each row before moving to the next.
% That is, the elements are ordered left to right and top to bottom.
% By default, each column is the same width, enough for the widest entry.
% If \meta{width} is a negative length (e.g., -1pt) the columns are set 
% to their natural 
% widths. If \meta{width} is positive (e.g., \cs{textwidth}), column widths 
% are equal widths so that the overal width is \meta{width}.
% The sideways location of thre tabular is \meta{pos} (l, c, or r), and
% the column style id \meta{style} (l, c, or r).
%    \begin{macrocode}
\newcommand{\autorows}[5][0pt]{\par\begingroup
 \ctabsetlines
%    \end{macrocode}
% Set the table position
%    \begin{macrocode}
  \ctableftskip\fill
  \ctabrightskip\fill
  \if l#2 
    \ctableftskip\z@
  \else
    \if r#2
      \ctabrightskip\z@
    \fi
  \fi
%    \end{macrocode}
% Set the column position style
%    \begin{macrocode}
  \let\c@lleftskip\hfil
  \let\c@lrightskip\hfil
  \if l#4 
    \let\c@lleftskip\relax
  \else
    \if r#4
      \let\c@lrightskip\relax
    \fi
  \fi
%    \end{macrocode}
% Count the number of entries and the minimum width (max entry width)
% for the columns.
%    \begin{macrocode}
  \TX@cols=#3\relax
  \@curtab=#3\relax
  \@cellstogo = \TX@cols
  \@mincolumnwidth\z@
  \@linestogo\z@
  \@for\@tempa:=#5\do{%
    \advance\@linestogo\@ne
    \settowidth{\@tempdima}{\@tempa}
    \ifdim\@tempdima>\@mincolumnwidth
      \@mincolumnwidth=\@tempdima
    \fi}%
  \advance\@mincolumnwidth\tabcolsep
%    \end{macrocode}
% Specify what is to be done after every entry
%    \begin{macrocode}
  \def\@endcolumnactions{%
    \global\advance\@linestogo\m@ne
    \global\advance\@cellstogo\m@ne
    \ifnum\@cellstogo<\@ne
      \global\@cellstogo=\TX@cols
      \the\crtok
    \else 
      & 
    \fi}%
%    \end{macrocode}
% Calculate the width of the columns
%    \begin{macrocode}
  \ifdim #1>\z@
    \TX@col@width=#1
  \else
    \TX@col@width=\hsize
  \fi
  \divide\TX@col@width \TX@cols
  \ifdim #1=\z@
    \TX@col@width=\@mincolumnwidth
  \fi
  \penalty\abovecolumnspenalty
  \noindent % usually not a paragraph
  \vskip -\z@ % don't know why we need this, but looks bad without it
%    \end{macrocode}
% Create most of the preamble by looping to add \cs{@cellsincolumn}-1 slots,
% then the last one which is different.
%    \begin{macrocode}
  \def\@preamble{}%
  \begingroup
    \let\@sharp\relax
    \ifnum\TX@cols>\@ne
      \loop
        \ifdim #1<\z@
          \g@addto@macro{\@preamble}{%
            \strut\c@lleftskip\@sharp\c@lrightskip &}%
        \else
          \g@addto@macro{\@preamble}{%
            \hb@xt@ \TX@col@width{%
                    \strut\c@lleftskip\@sharp\c@lrightskip} &}%
        \fi
        \advance\TX@cols\m@ne
      \ifnum\TX@cols>\@ne
      \repeat
    \fi
    \ifdim #1<\z@
      \g@addto@macro{\@preamble}{%
        \strut\c@lleftskip\@sharp\c@lrightskip}%
    \else
      \g@addto@macro{\@preamble}{%
        \hb@xt@ \TX@col@width{\strut\c@lleftskip\@sharp\c@lrightskip}}%
    \fi
  \endgroup
  \let\@sharp ##
%    \end{macrocode}
% Start the \verb?\halign?
%    \begin{macrocode}
  \tabskip\ctableftskip
  \halign to \hsize \bgroup
    \tabskip\z@
    \@preamble
%%    \tabskip\ctabrightskip\cr \preautotab
    \tabskip\ctabrightskip\cr 
%    \end{macrocode}
% Add all the entries then finish off.
%    \begin{macrocode}
    \@for\@tempa:=#5\do{%
      \@tempa\unskip\space\@endcolumnactions}%
%%    \the\crtok \postautotab \the\crtok \egroup \endgroup \par
    \the\crtok \egroup \endgroup \par}
  
%    \end{macrocode}
% \end{macro}
%  
%
%
%
% \section{Floating objects}
%
%    The file \file{latex.dtx} only defines a number of tools with
%    which floating objects can be defined. This is done in the
%    document class. It needs to define the following macros for each
%    floating object of type \texttt{TYPE} (e.g., \texttt{TYPE} =
%    figure).
%
%    \begin{description}
%    \item[\texttt{\bslash fps@TYPE}]
%        The default placement specifier for floats of type
%        \texttt{TYPE}.
%
%    \item[\texttt{\bslash ftype@TYPE}]
%        The type number for floats of type \texttt{TYPE}.  Each
%        \texttt{TYPE} has associated a unique positive \texttt
%        {TYPE} number, which is a power of two.  E.g., figures might
%        have type number 1, tables type number 2, programs type
%        number 4, etc.
%
%    \item[\texttt{\bslash ext@TYPE}]
%        The file extension indicating the file on which the contents
%        list for float type \texttt{TYPE} is stored.  For example,
%        \cs{ext@figure} = `lof'.
%
%    \item[\texttt{\bslash fnum@TYPE}]
%        A macro to generate the figure number for a caption. For
%        example, \cs{fnum@TYPE} == `Figure \cs{thefigure}'.
%
%    \item[\texttt{\bslash @makecaption}{\meta{num}}{\meta{text}}]
%        A macro to make a caption, with \meta{num} the value produced
%        by \cs{fnum@...} and \meta{text} the text of the caption. It
%        can assume it's in a \cs{parbox} of the appropriate width.
%        This will be used for \emph{all} floating objects.
%
%    \end{description}
%
%    The actual environment that implements a floating object such as
%    a figure is defined using the macros \cs{@float} and \cs{end@float},
%    which are defined in \file{latex.dtx}.
%
%    An environment that implements a single column floating object is
%    started with \verb?\@float{TYPE}?\oarg{placement} of type
%    \texttt{TYPE} with \meta{placement} as the placement specifier.
%    The default value of \meta{PLACEMENT} is defined by \cs{fps@TYPE}.
%
%    The environment is ended by \cs{end@float}.  E.g., \cs{figure} ==
%    \verb?\@float{figure}?, \cs{endfigure} == \cs{end@float}.
%
%
% \subsection{Floats}
%
% To define a float environment, say \Lenv{fenv}, the following macros must be defined:
% \begin{itemize}
% \item \cs{fps@fenv} The default placement specifier (normally \verb?tbp?). 
% \item \cs{ftype@fenv} The type number which is an integer and a power of 2.
% \item \cs{ext@fenv} The file extension for the contents list.
% \item \cs{c@fenv} A counter for the environment (for caption numbering).
% \item \cs{fnum@fenv} A macro to generate the caption `number'.
% \item \cs{l@fenv} A macro to produce an entry in a list of\ldots.
% \item \cs{flegtocfenv} A macro to write a \cs{namedlegend} title to a listof file.
% \item \cs{flegfenv} A macro to typeset the name of a \cs{namedlegend}.
% \item \cs{toclevel@fenv} Holding a bookmark level (required if the
%       \Lpack{hyperref} package will be used).
% \end{itemize}
%
% \begin{macro}{newflo@tctr}
% A counter for the type number of a new float. Normally
% figures are of type 1, tables type 2, and the next float type is then 4, and so
% on. 
%    \begin{macrocode}
\newcounter{newflo@tctr}
  \setcounter{newflo@tctr}{1}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\newfloat}
% \cs{newfloat}oarg{within}\marg{fenv}\marg{ext}\marg{capname}
% creates the commands for a new float environment, \meta{fenv} (aka \texttt{X}),
% using \meta{ext} (aka \texttt{Z}) as the
% file extension and \meta{capname} for the caption name.
% \changes{v1.61803}{2008/01/30}{Changed setting of \cs{ftype@X} in 
%        \cs{newfloat} to correctly assign float numbers, courtesy Flavian 
%        Lambert (mempatch v4.9)}
%    \begin{macrocode}
\newcommand{\newfloat}[4][\@empty]{%
%    \end{macrocode}
% \begin{macro}{\ftype@X}
%  Define the float type, set it to the float counter, and increase
% the counter afterwards.
%    \begin{macrocode}
%%%  \@namedef{ftype@#2}{\value{newflo@tctr}}
%%%  \addtocounter{newflo@tctr}{\value{newflo@tctr}}
  \expandafter\edef\csname ftype@#2\endcsname{\the\c@newflo@tctr}%
  \advance\c@newflo@tctr \c@newflo@tctr
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\c@X}
% Create the counter for the caption, which must not have been previously
% defined.
%    \begin{macrocode}
  \@ifundefined{c@#2}{% counter is not defined
    \ifx \@empty#1\relax
      \newcounter{#2}
    \else
      \newcounter{#2}[#1]
      \expandafter\edef\csname the#2\endcsname{%
  \expandafter\noexpand\csname the#1\endcsname.\noexpand\arabic{#2}}
    \fi}{}
  \setcounter{#2}{0}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ext@X}
% \begin{macro}{\c@Zdepth}
% Define \cs{ext@X} for the file extension and set the new \verb?Zdepth? 
% depth counter to 1.
%    \begin{macrocode}
  \@namedef{ext@#2}{#3}%     file extension
  \@ifundefined{c@#3depth}{\newcounter{#3depth}}{}
  \setcounter{#3depth}{1}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\fps@X}
% \begin{macro}{\fnum@X}
% \begin{macro}{\flegX}
% \begin{macro}{\flegtocX}
% \cs{fps@X} is the default float placement specification, \cs{fnum@X}
% typesets the caption name and number, and \cs{flegX} and \cs{flegtocX} are for
% named legends.
%    \begin{macrocode}
  \@namedef{fps@#2}{tbp}                     % position
  \@namedef{fnum@#2}{#4~\@nameuse{the#2}}    % caption naming
  \@namedef{fleg#2}{#4}                      % legend naming
  \@namedef{flegtoc#2}##1{}                  % legend name in ToC

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{environment}{X}
% \begin{environment}{X*}
% Finally define the new float environment, in both normal and starred
% forms. We also al an internal macro that can be used to globally
% adjust floats, e.g. making all tables in small size.
% We would like to be able to insert adjustments inside the
% floats. But the manner in which \cs{@float} works makes it
% impossible for us to simple insert this into the definitions of the
% floats. 
%    \begin{macrocode}
  \newenvironment{#2}{\@float{#2}}{\end@float}
  \newenvironment{#2*}{\@dblfloat{#2}}{\end@dblfloat}
%    \end{macrocode}
% \end{environment}
% \end{environment}
%
% This ends the definition of \cs{newfloat}.
%    \begin{macrocode}
} % end \newfloat

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@xfloat}
%   Was adjusted earlier.
% \end{macro}
%
% \begin{macro}{\setfloatlocations}
% \cs{setfloatlocations}\marg{float}\marg{locs} sets the defualt locations
% for the \meta{float} class of floats (e.g., \texttt{figure}) to \meta{locs}
% (initially \texttt{tbp}). For tables you might want to use: \\
% \verb?\setfloatlocations{table}{htbp}?
% \changes{v1.61803}{2008/01/30}{Added \cs{setfloatlocations} (mempatch v4.9)}
%    \begin{macrocode}
\newcommand*{\setfloatlocations}[2]{\@namedef{fps@#1}{#2}}

%    \end{macrocode}
% \end{macro}
% \changes{v3.6h}{2011/02/01}{Added \cs{setfloatadjustment}}
% \begin{macro}{\setfloatadjustment}
% \cs{setfloatadjustment}\marg{float}\marg{code} can be used to
% globally add internal adjustments to all floats of a certain
% type. For example to typeset the contents of all tables in
% \cs{small} use \verb|\setfloatadjustment{table}{\small}|.
%    \begin{macrocode}
\newcommand*\setfloatadjustment[2]{\@namedef{#1adjustment}{#2}}      

%    \end{macrocode}
% 
% \end{macro}
%
%
% To define subcaptions for use in a new float environment, say \texttt{fenv}, the
% following macros must be defined:
% \begin{itemize}
% \item A new counter \texttt{subfenv} for subcaption numbering.
% \item A new counter \texttt{extdepth}, where \texttt{ext} is the file extension
%       for the contents list of \texttt{fenv}, for setting the contents depth.
% \item \cs{thesubfenv} for the formatting of the subcaption number.
% \item \cs{@thesubfenv} for typesetting the number.
% \item \cs{@@thesubfenv} for alternative label reference.
% \item \cs{p@subfenv} for prepending to the subcaption number when it is referenced.
% \item \cs{ext@subfenv} the file extension for the contents list.
% \item \cs{l@subfenv} for formatting the contents list entry.
% \item \cs{@makesubfloatcaption} for typesetting the subcaption.
% \item \cs{toclevel@subfenv} for hyperref bookmarks
% \end{itemize}
%
% \begin{macro}{\newsubfloat}
% \cs{newsubfloat}\marg{fenv} creates the commands for a new
% subfloat for \meta{fenv} (aka \texttt{X}).
%    \begin{macrocode}
\newcommand{\newsubfloat}[1]{%
%    \end{macrocode}
% Call \verb?\newlistentry[X]{subX}{extX}{1}? to get most of the work done.
%    \begin{macrocode}
  \newlistentry[#1]{sub#1}{\@nameuse{ext@#1}}{1}
%    \end{macrocode}
%
% \begin{macro}{\ext@subX}
% \begin{macro}{\thesubX}
% \begin{macro}{\@thesubX}
% \begin{macro}{\@@thesubX}
% \begin{macro}{\p@subX}
% \begin{macro}{\toclevel@subX}
% And now for the rest of the commands for subcaptions.
% \changes{v1.1}{2002/03/10}{Added \cs{@namedef} of \cs{@@thesubenv}
%                to \cs{newsubfloat}}
% \changes{v1.1}{2002/03/10}{Added \cs{@namedef} of \cs{toclevel@subenv}
%                to \cs{newsubfloat}}
%    \begin{macrocode}
  \@namedef{ext@sub#1}{\csname ext@#1\endcsname}
  \@namedef{thesub#1}{(\alph{sub#1})}
  \@namedef{@thesub#1}{\@nameuse{thesub#1}%
            \if@tightsubcap\hskip\subfloatlabelskip\else\space\fi}
  \@namedef{@@thesub#1}{\@nameuse{thesub#1}}
  \@namedef{p@sub#1}{\csname the#1\endcsname}
  \@namedef{toclevel@sub#1}{1}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% By permission of Steven Douglas Cochran the class provides similar 
% functionality as the \Lpack{subfigure} package~\cite{SUBFIGURE}.
% This requires some changes to be made to \cs{@float} and \cs{end@float}.
%
% \begin{macro}{\ifdonemaincaption}
% This is set TRUE after the \cs{(cont)caption} has been called in a float.
% \changes{v1.1}{2002/03/10}{Changed \cs{if@contmaincaption} to
%          \cs{ifdonemaincaption}}
%    \begin{macrocode}
\newif\ifdonemaincaption
  \donemaincaptionfalse

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@float}
% \begin{macro}{\@dbfloat}
% \begin{macro}{\@memresetsubcounter}
%   The kernel \cs{@float} and \cs{@dblfloat} macros are redefined to
%   set \cs{ifdonemaincaption} to FALSE, and also to zero the subfloat
%   counter, if it is defined.  Ignasi Furi\`{o}
%   reported (Private email 2003/10/17) that floats embedded in text created an extra
%   space. This was caused by a missing \verb?%?.
%   \changes{v1.4}{2003/11/22}{Deleted spaces from \cs{@float} and
%   \cs{@dblfloat} (from patch v1.9)}
%  Axel Sommerfeldt (Private email, 2013/05/10) asked for the subcounter reset to be factored out into
%  a macro and provided the code. 
%    \begin{macrocode}
\let\@memoldfloat\@float
\renewcommand{\@float}[1]{\donemaincaptionfalse
  \@memresetsubcounter{#1}%
  \@memoldfloat{#1}}
\let\@memolddblfloat\@dblfloat
\renewcommand{\@dblfloat}[1]{\donemaincaptionfalse
  \@memresetsubcounter{#1}%
  \@memolddblfloat{#1}}
\newcommand{\@memresetsubcounter}[1]{%
  \@ifundefined{c@sub#1}{}{\csname c@sub#1\endcsname = 0\relax}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\end@float}
% \begin{macro}{\end@dblfloat}
% We add extra functionality to the end of floats via cmd hooks.
% \changes{v3.8.4}{2025/09/23}{Changed let+redef to cmd hooks.}
%    \begin{macrocode}
 %\let\@memoldefloat\end@float
 %\def\end@float{%
 % \@memlistsubcaptions{\@captype}\@memoldefloat}
 % \let\@memoldedblfloat\end@dblfloat
 % \def\end@dblfloat{%
 %  \@memlistsubcaptions{\@captype}\@memoldedblfloat}
 \AddToHook{cmd/end@float/before}{\@memlistsubcaptions{\@captype}}
 \AddToHook{cmd/end@dblfloat/before}{\@memlistsubcaptions{\@captype}}
 
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%   \changes{v3.8.4}{2025/09/23}{Ooold reference to problems with
%   fixltx2e removed, have been redundant since 2015.}
%   
% \changes{v3.6h}{2011/02/01}{Added \cs{FloatBlock}}
% \subsubsection{Float blockage}
%
% This is basically a slightly modified copy of \cs{FloatBarrier} from
% the \Lpack{placeins} package by Donald Arseneau, renamed such that
% both can be used in the same document. We could have emulated the
% \Lpack{placeins} package, but people might use it with options, so,
% since the code is so short we just copy it. Kudos to Donald Arseneau.
% For more defaults see
% \cite{PLACEINS}. 
% \begin{macro}{\FloatBlock}
% \begin{macro}{\FloatBlockAllowAbove}
% \begin{macro}{\FloatBlockAllowBelow}
% The two \cs{XAllowY} macros is our way of supporting the
% \Lpack{placeins} package options.
%    \begin{macrocode}
\def\mem@fb@botlist{\@botlist}
\def\mem@fb@topblock{\suppressfloats[t]}
%    \end{macrocode}
% \changes{v3.7d}{2015/03/12}{\cs{\@dbldeferlist} may be removed in a
% comming LaTeX kernel update}
%    \begin{macrocode}
\def\FloatBlock{\par\begingroup \let\@elt\relax
 \edef\@tempa{\mem@fb@botlist\@deferlist\@dbldeferlist}%
 \ifx\@tempa\@empty 
 \else
    \ifx\@fltovf\relax % my indicator of recursion
       \if@firstcolumn 
         \clearpage 
       \else 
         \null\newpage\FloatBlock
       \fi
    \else 
       \newpage \let\@fltovf\relax 
       \FloatBlock % recurse once only
 \fi\fi \endgroup
 \mem@fb@topblock}
\newcommand*\FloatBlockAllowAbove{\def\mem@fb@topblock{}}
\newcommand*\FloatBlockAllowBelow{\def\mem@fb@botlist{}}
      
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \begin{macro}{\setFloatBlockFor}
%   This can be used to add \cs{FloatBLock} into various sectional
%   macros. Supported: \cs{chapter} (when in article mode) and all
%   sectional macros made using \cs{@startsection}.
%    \begin{macrocode}
\newcommand\setFloatBlockFor[1]{%
  \@namedef{#1block}{\FloatBlock}}
%    \end{macrocode}
%   
% \end{macro}
%
% \subsubsection{Margin floats}
%
% The next two constructions are inspired by \texttt{tufte-common.def}
% by Bil Kleb, Bill Wood, and Kevin Godby and provide a manner to
% insert figures or tables into the margin. Note that the
% \cs{setfloatadjustment} also applies here.
% \begin{macro}{\mem@margin@floatbox}
% Box to save the contents of a margin float in.
%    \begin{macrocode}
\newsavebox{\mem@margin@floatbox}
%    \end{macrocode}
% \end{macro}
%    % \begin{environment}{mem@margin@float}
% \begin{environment}{marginfigure}
% \begin{environment}{margintable}
% \begin{macro}{\marginfloatmarginmacro}
% Since the two environments only differ in `name' a constructor is used.
% Since these margin floats are wrapped inside another type of float
% (\cs{marginpar}) they may cause problems when used combined with
% regular floats (the float order may be wrong). For that reason the
% margin float throws a \cs{FloatBlock} before issuing the \cs{marginpar}.
%    \begin{macrocode}
\newcommand\marginfloatmarginmacro{\marginpar}
\newenvironment{mem@margin@float}[2][-1.2ex]%
  {\FloatBlock% 
  \begin{lrbox}{\mem@margin@floatbox}%
  \begin{minipage}{\marginparwidth}%
    \def\@captype{#2}%
    \hbox{}\vspace*{#1}%
    \@nameuse{margin#2adjustment}%
    \@nameuse{margin#2captionadjustment}%
    \noindent%
  }
  {\end{minipage}%
  \end{lrbox}%
  \marginfloatmarginmacro{\usebox{\mem@margin@floatbox}}%
  }
%    \end{macrocode}
% The  two environment is then just two applications of the
% constructor. The option can be used to move the margins float up and down. 
%    \begin{macrocode}
\newenvironment{marginfigure}[1][-1.2ex]{%
  \begin{mem@margin@float}[#1]{figure}}
  {\end{mem@margin@float}}
\newenvironment{margintable}[1][-1.2ex]{%
  \begin{mem@margin@float}[#1]{table}}
  {\end{mem@margin@float}}
\setfloatadjustment{marginfigure}{\centering}
\setfloatadjustment{margintable}{\centering}
      
%    \end{macrocode}
% \end{macro}
% \end{environment}
% \end{environment}
% \end{environment}
% \begin{macro}{\setmarginfloatcaptionadjustment}
% Because of the very narrow margin area, it may be fruitful to
% reconfigure the caption style when used in a margin float. This can
% be done globally for all captions (e.g. if all floats are margin
% floats, or just for margin floats.
%    \begin{macrocode}
\newcommand*\setmarginfloatcaptionadjustment[2]{%
  \@namedef{margin#1captionadjustment}{#2}}
      
%    \end{macrocode}
% \end{macro}
% \changes{v3.6h}{2011/02/06}{Added these two macros}
% \begin{macro}{\setmpjustification}
% \begin{macro}{\mpjustification}
%  Can be just to use and configure a specialized justification. It
%  follows the \verb?\marginpar? placement, and make use of the first
%  argument when at the left of the text block and the other when at
%  the right. It makes use of an internal setting from within
%  \verb?\marginparmargin?, thus that need to have been executed.
%    \begin{macrocode}
\newcommand\setmpjustification[2]{%
  \@namedef{mem@mp@justification}{%
    \ifm@msetmp\else\@memerror{In order to use
      \string\marginCmdAdjust,^^J%  
      please make sure to specify into which margin the^^J%
      \string\marginpar\space should go, using \string\marginparmargin}{}\fi
    \m@mwhich@margin{\m@mmpar@margin}% 
     \ifmemtortm #2 \else #1\fi}%
}
%    \end{macrocode}
% Default value
%    \begin{macrocode}
\newcommand\mpjustification{%
  \@nameuse{mem@mp@justification}}
\setmpjustification{\raggedleft}{\raggedright}
      
%    \end{macrocode}
%  
% \end{macro}
% \end{macro}
%
% \subsection{Captions}
%
%    The caption styling 
% is accomplished by redefining the \cs{@makecaption}
% command. First, though, define and initialise the user-level commands.
%
% \begin{macro}{\if@contcw}
% \begin{macro}{\if@conthang}
% \begin{macro}{\if@contindent}
% For use when checking caption width and captioning styles styles.
%    \begin{macrocode}
\newif\if@contcw
\newif\if@conthang
\newif\if@contindent

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\captiondelim}
% \begin{macro}{\@contdelim}
%  For the caption delimiter.
%    \begin{macrocode}
\newcommand{\captiondelim}[1]{\def\@contdelim{#1}}
\captiondelim{: }

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\captionnamefont}
% \begin{macro}{\@contnfont}
% The font for the caption name.
%    \begin{macrocode}
\newcommand{\captionnamefont}[1]{\def\@contnfont{#1}}
\captionnamefont{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\captiontitlefont}
% \begin{macro}{\@conttfont}
% The font for the caption title.
%    \begin{macrocode}
\newcommand{\captiontitlefont}[1]{\def\@conttfont{#1}}
\captiontitlefont{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\captionstyle}
% \begin{macro}{\@contcstyle}
% The paragraphing style for the caption.
%    \begin{macrocode}
\newcommand*{\captionstyle}[1]{\def\@contcstyle{#1}}
\captionstyle{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\captionstyle}
% \begin{macro}{\@memcshort}
% \begin{macro}{\@memcnom}
% \begin{macro}{\@contcshortstyle}
% \begin{macro}{\@contcstyle}
% The paragraphing style for the caption.
%
% I had email from J{\o}rgen Larsen  2003/04/09,
% asking for separate controls for the short and long captions. \\
%  \cs{captionstyle}\oarg{short}\marg{normal}.
% \changes{v1.4}{2003/11/22}{Extended \cs{captionstyle} (from patch v1.5)}
% \changes{v3.6h}{2011/01/16}{Removed sporadic spaces}
%    \begin{macrocode}
\renewcommand{\captionstyle}{%
  \@ifnextchar[{\@memcshort}{\@memcnorm}}
\def\@memcshort[#1]#2{%
  \def\@contcshortstyle{#1}%
  \def\@contcstyle{#2}}
\def\@memcnorm#1{%
  \def\@contcshortstyle{#1}%
  \def\@contcstyle{#1}}
\captionstyle{}
  
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\@contcwidth}
% \begin{macro}{\captionwidth}
% \begin{macro}{\changecaptionwidth}
% \begin{macro}{\normalcaptionwidth}
% The macros for dealing with the caption width.
%    \begin{macrocode}
\newlength{\@contcwidth}
\newcommand{\captionwidth}[1]{\setlength{\@contcwidth}{#1}}
\captionwidth{\linewidth}
\newcommand{\changecaptionwidth}{\@contcwtrue}
\newcommand{\normalcaptionwidth}{\@contcwfalse}
\normalcaptionwidth

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@contindw}
% \begin{macro}{\hangcaption}
% \begin{macro}{\indentcaption}
% \begin{macro}{\normalcaption}
% The macros for hanging and indented captions.
%    \begin{macrocode}
\newlength{\@contindw}
\newcommand{\hangcaption}{\@conthangtrue\@contindentfalse}
\newcommand{\indentcaption}[1]{\setlength{\@contindw}{#1}%
  \@conthangfalse\@contindenttrue}
\newcommand{\normalcaption}{\@conthangfalse\@contindentfalse}
\normalcaption

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\precaption}
% \begin{macro}{\@contpre}
% \begin{macro}{\postcaption}
% \begin{macro}{\@contpost}
% \begin{macro}{\midbicaption}
% \begin{macro}{\@contmidbi}
% The macros for the pre- and post-caption text/commands, and
% for the mid-caption command for bilingual captions.
%    \begin{macrocode}
\newcommand{\precaption}[1]{\def\@contpre{#1}}
\precaption{}
\newcommand{\postcaption}[1]{\def\@contpost{#1}}
\postcaption{}
\newcommand{\midbicaption}[1]{\def\@contmidbi{#1}}
\midbicaption{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\captiontitlefinal}
% \cs{captiontitlefinal}\marg{stuff} will put \meta{stuff} immediately
% at the end of a \cs{caption}'s title text but it will not appear
% in the LoF/LoT/etc. For example \\
% \verb?\captiontitlefinal{.}? \\
% The code was supplied by Frederic Connes.
% \changes{v1.61803}{2008/01/30}{Added \cs{captiontitlefinal} (mempatch v4.4)}
%    \begin{macrocode}
\newcommand*{\captiontitlefinal}[1]{\def\@contfinal{#1}}
  \captiontitlefinal{}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\abovecaptionskip}
% \begin{macro}{\belowcaptionskip}
% Vertical space above and below a caption. Make them sum to an
% integral number of lines.
%    \begin{macrocode}
\newlength{\abovecaptionskip}
  \setlength{\abovecaptionskip}{0.5\onelineskip}
\newlength{\belowcaptionskip}
  \setlength{\belowcaptionskip}{0.5\onelineskip}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\caption}
% For subfloat support, the (kernel) \cs{caption} macro needs to note that it
% has been called.
%    \begin{macrocode}
\let\@memoldcaption\caption
\def\caption{\donemaincaptiontrue\@memoldcaption}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\memcaptioninfo}
% \verb?\memcaptioninfo{type}{\thetypenum}{short}{long}?
% \changes{v1.618}{2005/09/10}{Added \cs{memcaptioninfo}}
%    \begin{macrocode}
\newcommand{\memcaptioninfo}[4]{}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@caption}
% For title referencing support, the (kernel) \cs{@caption} macro needs 
% to store the title.
% \changes{v1.618}{2005/09/03}{Added braces around second argument of \cs{@memold@caption} (per Dan Luecking, mempatch v3.0)}
%    \begin{macrocode}
\let\@memold@caption\@caption
\long\def\@caption#1[#2]#3{%
  \M@gettitle{#2}%
  \memcaptioninfo{#1}{\csname the#1\endcsname}{#2}{#3}%
  \@memold@caption{#1}[{#2}]{#3}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@makecaption}
%  This is a reimplementation of the kernel \cs{@makecaption} command.
% As well as including the caption typesetting commands it enables
% captions that include forced newlines (e.g., by \verb?\\?).
%
% The first part is due to Donald Arseneau from postings to the \ctt{}
% newsgroup and Email discussions. The \cs{topskip} strut is used
% whenever the caption is the first part of the float. This means,
% among other things, that if a caption comes at the top of a page,
% then the first line of the caption will be aligned with the normal
% first line of a page. The \cs{abovecaptionskip} is only used when
% there is something above the caption in the current float.
% \changes{v0.31}{2001/07/24}{Changed \cs{@tempa} to \cs{@memtempa} in \cs{@makecaption}}
% \changes{v1.0a}{2002/02/12}{Added extra centering code in \cs{@makecaption}}
% \changes{v1.4}{2003/11/22}{Added separate short/long styles in \cs{@makecaption}
%                             (from patch v1.5)}
% \changes{v1.61803}{2008/01/30}{Added \cs{@contfinal} to \cs{@makecaption}
%         (mempatch v4.4)}
%
% Axel Sommerfelt\footnote{Private email discussion} suggested to
% split \cs{@makecaption} into two macros, such that the caption
% formatting and the space above and below are separate. This enables
% us to use the formatting macro (\cs{@@makecaption}) to format, say,
% \Lpack{longtable} captions.
% \changes{v3.6k}{2013/05/13}{Split \cs{@makecaption} into
% \cs{@makecaption} and \cs{@@makecaption}} 
%    \begin{macrocode}
\long\def\@makecaption#1#2{\let\@memtempa\relax
  \ifdim\prevdepth>-99\p@ \vskip\abovecaptionskip
  \else \def\@memtempa{\vbox to\topskip{}}\fi
%    \end{macrocode}
% Inserting \cs{@@makecaption} to format the actual caption.
%    \begin{macrocode}
  \@@makecaption{#1}{#2}%
%    \end{macrocode}
% Then add the below caption spacing.
%    \begin{macrocode}
  \vskip\belowcaptionskip}

%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\@@makecaption}
% Next the rest of the caption code as \cs{@@makecaption}.
%    \begin{macrocode}
\long\def\@@makecaption#1#2{%
%    \end{macrocode}
% \begin{macro}{\@contfnote}
% \begin{macro}{\@contfmark}
% The caption title will be typeset twice, firstly to measure its width
% and secondly to actually typeset it. To avoid problems caused by
% a footnote in the caption getting processed twice, we temporarily
% disable the expected relevant commands.
% \changes{v3.6h}{2011/01/20}{Provided the same for \cs{pagentote}}
%    \begin{macrocode}
  \let\@contfnote\footnote \renewcommand{\footnote}[2][]{}
  \let\@contfmark\footnotemark \renewcommand{\footnotemark}[1][]{}
  \let\@contpnote\pagenote\renewcommand\pagenote[2][]{}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% Now measure the width of the total caption, not forgetting to take account
% of the font specifications, and then restore the footnoting. 
% \changes{v3.6k}{2013/05/13}{Font grouping, suggested by Axel Sommerfelt}
%    \begin{macrocode}
  \sbox\@tempboxa{{\@contnfont #1\@contdelim}\@conttfont #2\@contfinal}
  \let\footnote\@contfnote
  \let\footnotemark\@contfmark
  \let\pagenote\@contpnote
%    \end{macrocode}
% If the caption is less than one
% line, then the whole caption needs to be centered on the page (otherwise
% the short caption may be typeset flushleft).
%    \begin{macrocode}
  \ifdim\wd\@tempboxa<\linewidth \centering \fi
  \if@contcw
%    \end{macrocode}
% For typesetting at anything other than the normal width, put the caption
% into a \cs{parbox} of the specified width. This must be centered.
% \changes{v3.6h}{2010/12/06}{Align inner parbox at top
% line. Vertically centered parbox cause different spacing when
% \cs{changecaptionwidth} compared when it is not used.}
%    \begin{macrocode}
    \centering
    \parbox[t]{\@contcwidth}{%
%    \end{macrocode}
% Henrik Holm (email on 2002/02/10) proposed adding the next line to center short, narrow captions.
%    \begin{macrocode}
    \ifdim\wd\@tempboxa<\@contcwidth \centering \fi
  \fi
%    \end{macrocode}
% Hanging and indenting doesn't apply to short captions, so do these
% now.
% \changes{v1.6180339f}{2009/06/25}{Short captions no longer hang or indent}
%    \begin{macrocode}
  \ifdim\wd\@tempboxa<\linewidth
    \@contpre
    {\@contnfont #1\@contdelim}\@memtempa
    {\@contcshortstyle \@conttfont #2\@contfinal\par}
  \else
    \if@conthang
%    \end{macrocode}
% For a hanging caption we have to measure the width of the caption name,
% then typeset the whole caption in a hanging paragraph.
% \changes{v1.1}{2002/03/10}{Changed code for hangcaption in \cs{@makecaption}}
%    \begin{macrocode}
      \sbox\@tempboxa{\@contnfont #1\@contdelim}
      \@contpre%
      {\@contcstyle\hangindent=\wd\@tempboxa
       \noindent\box\@tempboxa\@memtempa \@conttfont #2\@contfinal\par}
    \else
      \if@contindent
%    \end{macrocode}
% An indented caption is similar, except the amount of indentation is
% kept in \cs{@contindw}.
%    \begin{macrocode}
        \@contpre%
        {\@contnfont #1\@contdelim}\@memtempa 
        {\@contcstyle\hangindent=\@contindw
                     \hangafter=\@ne\@conttfont #2\@contfinal\par}% <- v1.4 
      \else
%    \end{macrocode}
% For the normal style, just typeset the caption.
%    \begin{macrocode}
        \@contpre%
        {\@contnfont #1\@contdelim}\@memtempa 
        {\@contcstyle \@conttfont #2\@contfinal\par}
      \fi
    \fi
  \fi
%    \end{macrocode}
% Finish off the typesetting by processing the post-text,  and if not using
% the normal width then close off the \cs{parbox}, and lastly put in some
% vertical space. 
% \changes{v3.6k}{2013/05/13}{Removed the below vertical skip}
%    \begin{macrocode}
  \@contpost
  \if@contcw
    \par
    }  % end of the \parbox
  \fi
  }

%    \end{macrocode}
% \end{macro}
%
%
%
% \subsubsection{Continuation captions and legends}
%
% \begin{macro}{\contcaption}
%    \cs{contcaption}\marg{text} is a user-level command. 
%    It is a simplified
%    version of the normal \cs{caption} command as it doesn't have to deal
%    with numbering or list of \dots entries. 
%
%    However, Brent Lievers\footnote{in \ctt{} thread
%    \textit{Figures}, 2003/11/14.} requested that \cs{label} should
%    pick up the correct caption number after a \cs{contcaption}.
% \changes{v1.4}{2003/11/22}{Extended \cs{contcaption} (from patch v1.9)} 
%    \begin{macrocode}
\newcommand{\contcaption}{%
  \addtocounter{\@captype}{\m@ne}\refstepcounter{\@captype}%
  \@contcaption\@captype}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\@@contcaption}
% \begin{macro}{\@contcaption}
%    \cs{@contcaption} is the workhorse for the \cs{contcaption} command. In turn,
% it uses the \cs{@makecaption} command (defined in the usual classes)
% to do most of its work. It
% uses the number of the previous \cs{caption} command in the same
% type of float and its implementation includes much of the code
% used in the \LaTeX{} \cs{@caption} command.
% 
%    First specify \cs{@@contcaption}\marg{type}\marg{title}
% to save some repetitive code.
%    \begin{macrocode}
\long\def\@@contcaption#1#2{%
  \par
  \begingroup
     \@parboxrestore
     \if@minipage
       \@setminipage
     \fi
     \normalsize
     \@makecaption{\csname fnum@#1\endcsname}{\ignorespaces #2}\par
  \endgroup}

%    \end{macrocode}
% \end{macro}
%
% Now for \cs{@contcaption}\marg{type}\marg{title}. 
% It has to flush out any subcaptions at the 
% appropriate time, as well as typesetting the caption.
% ^^A Why is \@memlistsubcaptions being executed here? We
% ^^A it should be enough to do it at the end of the floats.
% ^^A Works fine if they are removed
%    \begin{macrocode}
\long\def\@contcaption#1#2{%
  \if@contbotsub
    \@memlistsubcaptions{#1}%
    \@@contcaption{#1}{#2}%
  \else
    \@@contcaption{#1}{#2}%
    \@memlistsubcaptions{#1}%
  \fi}

%    \end{macrocode}
% \end{macro}    
%
%
% \begin{macro}{\memlegendinfo}
% \begin{macro}{\legend}
%    The macro \cs{legend}\marg{text}is intended
% to be used in a float environment for an `anonymous' caption, but can be
% used anywhere.
%
%    The implementation is similar to the \cs{caption} command but we have
% to eliminate printing of a delimeter.
% \changes{v1.4}{2003/11/16}{Added \cs{M@gettitle} to \cs{legend}}
% \changes{v1.618}{2005/09/10}{Added \cs{memlegendinfo}}
%    \begin{macrocode}
\newcommand{\memlegendinfo}[1]{}
\newcommand{\legend}[1]{%
  \M@gettitle{#1}%
  \memlegendinfo{#1}%
  \par
  \begingroup
     \@parboxrestore
     \if@minipage
       \@setminipage
     \fi
     \normalsize
     \captiondelim{\mbox{}}
     \@makecaption{}{\ignorespaces #1}\par
  \endgroup}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\namedlegend}
% \begin{macro}{\memnamedlegendinfo}
% \cs{namedlegend}\oarg{short-title}\marg{long-title} is like the
% \cs{caption} command except that it does not number the caption.
%
% \cs{memnamedlegendinfo}\marg{type}\marg{short-title}\marg{long-title}
% \changes{v1.618}{2005/09/10}{Added \cs{memnamedlegendinfo}}
%    \begin{macrocode}
\newcommand{\namedlegend}{\@dblarg{\@legend\@captype}}
\newcommand{\memnamedlegendinfo}[3]{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@legend}
% \cs{@legend}\marg{type}\oarg{short-title}\marg{long-title}
% is the workhorse for the \cs{namedlegend} command. In turn, it calls
% \cs{@makelegend}. It requires two commands to have been defined, namely
% \cs{flegtoctype} and \cs{flegtype}. The command \cs{flegtoctype}\marg{text}
% is responsible for writing a title text to the appropriate listof file.
% \cs{flegtype} is responsible for typeseting the name of the legend.
% \changes{v1.4}{2003/11/16}{Added \cs{M@gettitle} to \cs{@legend}}
%    \begin{macrocode}
\long\def\@legend#1[#2]#3{%
  \M@gettitle{#2}%
  \memnamedlegendinfo{#1}{#2}{#3}%
  \par
  \csname flegtoc#1\endcsname{#2}%
  \begingroup
    \@parboxrestore
    \if@minipage
      \@setminipage
    \fi
    \normalsize
    \@makecaption{\csname fleg#1\endcsname}{\ignorespaces #3}\par
  \endgroup}

%    \end{macrocode}
% \end{macro}
%
%
% \subsubsection{Non-float captions}
%
% \begin{macro}{\newfixedcaption}
% \begin{macro}{\renewfixedcaption}
% \begin{macro}{\providefixedcaption}
% These commands are defined in terms of their \verb?\...command? counterparts.\\
% Call as \verb?\...fixedcaption?\oarg{capcommand}\marg{command}\marg{env}
%    \begin{macrocode}
\newcommand{\newfixedcaption}[3][\caption]{%
  \newcommand{#2}{\def\@captype{#3}#1}}
\newcommand{\renewfixedcaption}[3][\caption]{%
  \renewcommand{#2}{\def\@captype{#3}#1}}
\newcommand{\providefixedcaption}[3][\caption]{%
  \providecommand{#2}{\def\@captype{#3}#1}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \subsubsection{Bilingual captions}
%
%    The bilingual caption commands all use internal grouping so
% that any changes are kept local. This has the unfortunate side-effect
% that any \cs{label} command must be within the grouping otherwise the
% wrong number is picked up. To make the coding, if not necessarily the 
% use, of the commands simpler, I have not used the traditional style
% of square brackets for optional caption text arguments. Instead, empty
% `required' arguments are used as the implementation means. 
%
% \begin{macro}{\membitwonumcaptioninfo}
% \begin{macro}{\membionenumcaptioninfo}
% \begin{macro}{\membicaptioninfo}
% \verb?\membitwonumcaptioninfo{type}{\thetypenum}?\marg{short1}\marg{long1}\\
%  \hspace*{2in} \marg{name2}\marg{short2}\marg{long2} \\
% \verb?\membionenumcaptioninfo{type}{\thetypenum}?\marg{short1}\marg{long1}\\
%  \hspace*{2in} \marg{name2}\marg{short2}\marg{long2} \\
% \verb?\membicaptioninfo{type}{\thetypenum}?\marg{short1}\marg{long1}\\
%  \hspace{2in} \marg{name2}\marg{long2} \\
% \changes{v1.618}{2005/09/10}{Added \cs{membitwonumcaptioninfo},
%   \cs{membitwonumcaptioninfo} and \cs{membicaptioninfo}}
%    \begin{macrocode}
\newcommand{\membitwonumcaptioninfo}[7]{}
\newcommand{\membionenumcaptioninfo}[7]{}
\newcommand{\membicaptioninfo}[6]{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\bitwonumcaption}
%  The 6 arguments are: optional label, short and long in language 1, 
% name in
% language 2, and short and long in language 2. Both texts are put
% into the List of as numbered entries.
%    \begin{macrocode}
\newcommand{\bitwonumcaption}[6][\@empty]{%
  \begingroup
  \let\memcaptioninfo\@gobblefour
%    \end{macrocode}
% Check if the first language argument is vacuous, then call
% the normal \cs{caption} for language 1.
%    \begin{macrocode}
  \@ifmtarg{#2}{\def\m@mscapi{#3}\caption{#3}}%
               {\def\m@mscapi{#2}\caption[#2]{#3}}%
%    \end{macrocode}
% Do the optional labeling.
%    \begin{macrocode}
  \ifx \@empty #1\else
    \label{#1}%
  \fi
%    \end{macrocode}
% Remove any extra spacing between the captions, and set the
% NAME for the second caption. Use a command to transfer
% the NAME to the renewal code to avoid circularity if
% for example, we are trying to redefine \cs{tablename} as
% \cs{tablename}. Decrement the caption counter.
%    \begin{macrocode}
  \setlength{\abovecaptionskip}{0pt}%
  \setlength{\belowcaptionskip}{0pt}%
  \edef\@memtempc{#4}%
  \expandafter\renewcommand\csname \@captype name\endcsname{\@memtempc}%
  \addtocounter{\@captype}{-1}%
%    \end{macrocode}
%   To avoid duplicate targets (hyperref) we need to locally change
%   \cs{theH\cs{captype}}. Due to a bug in \Lpack{hyperref} cannot
%   just use \cs{LinkTargetOff}
% \changes{v3.8.4}{2025/09/19}{Added fix}
%    \begin{macrocode}
  \ExpandArgs{c}\edef{theH\@captype}{\csname theH\@captype\endcsname-bitwonum-#4}%
%    \end{macrocode}
% Now repeat for the second language caption.
%    \begin{macrocode}
  \@contmidbi
  \@ifmtarg{#5}{\def\m@mscapii{#6}\caption{#6}}%
               {\def\m@mscapii{#5}\caption[#5]{#6}}%
  \membitwonumcaptioninfo{\@captype}{\@nameuse{the\@captype}}%
                         {\m@mscapi}{#3}{#4}{\m@mscapii}{#6}%
  \endgroup}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\bionenumcaption}
%  The 6 arguments are: optional labelling,
%  short and long in language 1, name in
% language 2, and short and long in language 2. Both texts are put
% into the List of, but only the first is numbered.
%    \begin{macrocode}
\newcommand{\bionenumcaption}[6][\@empty]{%
  \begingroup
  \let\memcaptioninfo\@gobblefour
%    \end{macrocode}
% Check if the first language argument is vacuous, then call
% the normal \cs{caption} for language 1.
%    \begin{macrocode}
  \@ifmtarg{#2}{\def\m@mscapi{#3}\caption{#3}}%
               {\def\m@mscapi{#2}\caption[#2]{#3}}%
%    \end{macrocode}
% Do the optional labeling.
%    \begin{macrocode}
  \ifx \@empty #1\else
    \label{#1}%
  \fi
%    \end{macrocode}
% Do the between captions code.
%    \begin{macrocode}
  \setlength{\abovecaptionskip}{0pt}%
  \setlength{\belowcaptionskip}{0pt}%
  \edef\@memtempc{#4}%
  \expandafter\renewcommand\csname \@captype name\endcsname{\@memtempc}
%    \end{macrocode}
% Use a continuation caption for the second language, not forgetting
% to add the appropriate unnumbered text to the List.
%    \begin{macrocode}
  \@contmidbi
  \contcaption{#6}%
  \@ifmtarg{#5}{%
    \def\m@mscapii{#6}%
    \addcontentsline{\csname ext@\@captype\endcsname}{\@captype}%
      {\protect\numberline{}{\ignorespaces #6}}}{%
    \def\m@mscapii{#5}%
    \addcontentsline{\csname ext@\@captype\endcsname}{\@captype}%
      {\protect\numberline{}{\ignorespaces #5}}}%
  \membionenumcaptioninfo{\@captype}{\@nameuse{the\@captype}}%
                         {\m@mscapi}{#3}{#4}{\m@mscapii}{#6}%
  \endgroup}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\bicaption}
%  The 5 arguments are: optional labelling, 
% short and long in language 1, name in
% language 2, and long in language 2. 
% Only the first text is put into the List.
%    \begin{macrocode}
\newcommand{\bicaption}[5][\@empty]{%
  \begingroup
  \let\memcaptioninfo\@gobblefour
%    \end{macrocode}
% Check if the first language argument is vacuous, then call
% the normal \cs{caption} for language 1.
%    \begin{macrocode}
  \@ifmtarg{#2}{\def\m@mscapi{#3}\caption{#3}}%
               {\def\m@mscapi{#2}\caption[#2]{#3}}%
%    \end{macrocode}
% Do the optional labeling.
%    \begin{macrocode}
  \ifx \@empty #1\else
    \label{#1}%
  \fi
%    \end{macrocode}
% Do the between captions code and 
% finally just use \cs{contcaption} for the
% second language.
%    \begin{macrocode}
  \setlength{\abovecaptionskip}{0pt}%
  \setlength{\belowcaptionskip}{0pt}%
  \edef\@memtempc{#4}
  \expandafter\renewcommand\csname \@captype name\endcsname{\@memtempc}%
  \@contmidbi
  \contcaption{#5}%
  \membicaptioninfo{\@captype}{\@nameuse{the\@captype}}%
                   {\m@mscapi}{#3}{#4}{#5}%
  \endgroup}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\bicontcaption}
%  The 3 arguments are long in language 1, name in
% language 2, and long in language 2.
%    \begin{macrocode}
\newcommand{\bicontcaption}[3]{%
  \begingroup
%    \end{macrocode}
% Call \cs{contcaption} for language 1.
%    \begin{macrocode}
  \contcaption{#1}%
%    \end{macrocode}
% Do the between captions code and use \cs{contcaption} for the second
% language.
%    \begin{macrocode}
  \setlength{\abovecaptionskip}{0pt}%
  \setlength{\belowcaptionskip}{0pt}%
  \edef\@memtempc{#2}%
  \expandafter\renewcommand\csname \@captype name\endcsname{\@memtempc}%
  \@contmidbi
  \contcaption{#3}%
  \endgroup}

%    \end{macrocode}
% \end{macro}
%
%
%
% \subsubsection{Support for the \Lopt{subfigure} package like functionality}
%
% Much of the code in this section is based on the \Lpack{subfigure}
% package code, by kind permission of its author, Steven Douglas Cochran.
% To try and avoid clashes with the real \Lpack{subfigure} code I have
% used different macro names, especially when I have copied the code.
%
% \begin{macro}{\subcaptionstyle}
% \begin{macro}{\@contsubcstyle}
% The paragraphing style for subcaptions.
%    \begin{macrocode}
\newcommand{\subcaptionstyle}[1]{\def\@contsubcstyle{#1}}
\subcaptionstyle{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\if@shortsubcap}
% \begin{macro}{\if@hangsubcap}
% \begin{macro}{\shortsubcaption}
% \begin{macro}{\hangsubcaption}
% \begin{macro}{\normalsubcaption}
%  For dealing with short and hanging subcaptions. 
% Analagous to the \Lpack{subfigure} \texttt{nooneline} and \texttt{hang} options.
% The default is normal subcaptions.
%    \begin{macrocode}
\newif\if@shortsubcap
\newif\if@hangsubcap
\newcommand*{\shortsubcaption}{\@shortsubcaptrue}
\newcommand*{\hangsubcaption}{\@hangsubcaptrue}
\newcommand*{\normalsubcaption}{\@shortsubcapfalse\@hangsubcapfalse}
\normalsubcaption

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\subfloattopskip}
% \begin{macro}{\subfloatcapskip}
% \begin{macro}{\subfloatcaptopadj}
% \begin{macro}{\subfloatbottomskip}
% \begin{macro}{\subfloatlabelskip}
% \begin{macro}{\subfloatcapmargin}
% These \cs{subfloat...} lengths are analagous to the \Lpack{subfigure} 
% \cs{subfig...} lengths.
%    \begin{macrocode}
\newskip\subfloattopskip
\newskip\subfloatcapskip
\newskip\subfloatcaptopadj
\newskip\subfloatbottomskip
\newskip\subfloatlabelskip
\newdimen\subfloatcapmargin
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\if@tightsubcap}
% \begin{macro}{\loosesubcaptions}
% \begin{macro}{\tightsubcaptions}
% Unlike the \Lpack{subfigure} package the class provides no options for
% subcaptions. These macros provide the \Lpack{subfigure} loose/tight
% option functions. Set the default to tight.
%    \begin{macrocode}
\newif\if@tightsubcap
\newcommand{\loosesubcaptions}{%
  \subfloattopskip = 10\p@
  \subfloatcapskip  = 10\p@
  \subfloatcaptopadj = \z@
  \subfloatbottomskip = 10\p@
  \subfloatlabelskip = 0.33em
  \subfloatcapmargin = 10\p@
  \@tightsubcapfalse
}

\newcommand{\tightsubcaptions}{%
  \subfloattopskip = 5\p@
  \subfloatcapskip  = \z@
  \subfloatcaptopadj = 3\p@
  \subfloatbottomskip = 5\p@
  \subfloatlabelskip = 0.33em \@plus 0.07em \@minus 0.03em
  \subfloatcapmargin = \z@
  \@tightsubcaptrue
}
\tightsubcaptions

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\subcaptionsize}
% \begin{macro}{\@subcapsize}
% \begin{macro}{\subcaptionlabelfont}
% \begin{macro}{\@subcaplabelfont}
% \begin{macro}{\subcaptionfont}
% \begin{macro}{\@subcapfont}
% These macros set the size and fonts for the subcaptions. Set the defaults
% to \cs{footnotesize}, and the normal roman font.
%    \begin{macrocode}
\newcommand*{\subcaptionsize}[1]{\def\@subcapsize{#1}}
\newcommand*{\subcaptionlabelfont}[1]{\def\@subcaplabelfont{#1}}
\newcommand*{\subcaptionfont}[1]{\def\@subcapfont{#1}}
\subcaptionsize{\footnotesize}
\subcaptionlabelfont{\normalfont}
\subcaptionfont{\normalfont}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@contkeep}
% \begin{macro}{\@contset}
% \begin{macro}{\subconcluded}
% \cs{@contkeep} stores
% the current subfloat number in counter \verb?@contsubnum? and 
% \cs{@contset} sets the subfloat number to the value of \verb?@contsubnum?.
% \cs{subconcluded} sets the subfloat number to zero. 
%    \begin{macrocode}
  \newcounter{@contsubnum}
  \newcommand{\@contkeep}{%
    \setcounter{@contsubnum}{\value{sub\@captype}}}
  \newcommand{\@contset}{%
    \setcounter{sub\@captype}{\value{@contsubnum}}}
  \newcommand{\subconcluded}{%
    \setcounter{sub\@captype}{0}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
%
% \begin{macro}{\if@contbotsub}
% A flag indicating whether the subcaption is to be at the bottom or
% top of the subfloat; TRUE for the subcaption at the bottom.
%    \begin{macrocode}
\newif\if@contbotsub
  \@contbotsubtrue

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\mem@addto@label}
%   In earlier versions of the code (pre 2025) we would mess with
%   \cs{label} inside the various sub commands. This is not a good
%   idea, as others may do that as well. Better to directly use the
%   \cs{label} hook instead. By default this hook does nothing.
% \changes{v3.8.4}{2025/09/22}{Added}
%    \begin{macrocode}
\AddToHookWithArguments{label}{\mem@addto@label@hook{#1}}
\let\mem@addto@label@hook\@gobble
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\memsub@addto@label@hook}
%   This is the version of the hook we actually want to run inside sub
%   captions and friends.  Inside a group we set
%   \cs{@currentlabelname} and \cs{@currentlabel} to something
%   appropriate. Then \emph{manually} add a label entry. TODO: make
%   the name inside \cs{@currentlabelname} configurable.
% \changes{v3.8.4}{2025/09/22}{Added}
%    \begin{macrocode}
\newcommand\memsub@addto@label@hook[1]{%
  \begingroup%
  \protected@edef\@currentlabelname{%
    Sub\@captype\space%
    \@nameuse{p@sub\@captype}%
    \@nameuse{thesub\@captype}%
  }%
  \protected@edef\@currentlabel{\@nameuse{@@thesub\@captype}}%
  \protected@write\@auxout{}%
  {%
    \string\newlabel{sub@#1}{%
      {\@currentlabel}%
      {\thepage}%
      {\@currentlabelname}%x
      {\@currentHref}%
      {\@kernel@reserved@label@data}%
    }%
  }%
  \endgroup%
}
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\subcaption}
% \cs{subcaption}\oarg{list-entry}\marg{caption} is a generic
% subcaption. There is no \Lpack{subfigure} equivalent.
% 
% \changes{v3.7i}{2019/10/24}{Added a \cs{par} to the start. This can
% get rid of sporadic spaces caused by hyperref changing \cs{refstepcounter}}
% \changes{v3.8}{2023/08/02}{Added \cs{mem@step@subcounter} instead
% of refstep}
% \changes{v3.8.4}{2025/09/22}{Changed how we add the extra label}
%    \begin{macrocode}
\newcommand{\subcaption}{%
  \par
  \bgroup
    % \let\label=\memsub@label
    \let\mem@addto@label@hook\memsub@addto@label@hook
    \ifdonemaincaption\else
      \advance\csname c@\@captype\endcsname\@ne
    \fi
    \mem@step@subcounter%
    \@ifnextchar [%
      {\@memsubcap{sub\@captype}}%
      {\@memsubcap{sub\@captype}[\@empty]}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@memsubcap}
% This handles the optional argument to \cs{subcaption}. It sets \cs{@tempdima}
% to \cs{hsize} as later on \cs{@makesubfloatcaption} uses this.
% \changes{v1.1a}{2002/04/28}{Added \cs{@tempdima} to \cs{@memsubcap}}
%    \begin{macrocode}
\long\def\@memsubcap#1[#2]#3{%
  \@tempdima=\hsize
  \vskip\subfloatcapskip
  \ifx \@empty #2
    \@memsubcaption{#1}{#3}{#3}%
  \else
    \@memsubcaption{#1}{#2}{#3}%
  \fi
  \vskip\subfloatcapskip
  \egroup}
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\@memsubcaption}
% \cs{@memsubcaption}\marg{type}\marg{list-entry}\marg{caption}
% typesets a subcaption. This is a copy of the \Lpack{subfigure} 
% \cs{@subcaption} macro.
%    \begin{macrocode}
\newcommand{\@memsubcaption}[3]{%
  \ifx \relax#2\relax \else
    \bgroup
      \let\label\@gobble
      \let\protect\string
      \def\@memsubcaplabel{\@nameuse{@@the#1}}%
      \xdef\@memsubfigcaptionlist{%
        \@memsubfigcaptionlist,%
  {\protect\numberline{\@memsubcaplabel}\noexpand{\ignorespaces #2}}}%
    \egroup
  \fi
  \@makesubfloatcaption{\@nameuse{@the#1}}{#3}}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\contsubcaption}
% \cs{contsubcaption}\oarg{caption} is the continued version of
% \cs{subcaption}.
% \changes{v3.8}{2023/08/02}{Added \cs{mem@step@subcounter} instead
% of refstep}
% \changes{v3.8.4}{2025/09/22}{Changed how we add the extra label}
%    \begin{macrocode}
\newcommand{\contsubcaption}{%
  \bgroup%
    % \let\label=\memsub@label
    \let\mem@addto@label@hook\memsub@addto@label@hook
    \@contset%
    \mem@step@subcounter%
    \@ifnextchar [%
      {\@memsubcap{sub\@captype}}%
      {\@memsubcap{sub\@captype}[\@empty]}}
%    \end{macrocode}
% \end{macro}
%
%
% \begin{environment}{subfloat}
% The \Lpack{subfigure} documentation suggests a way of defining a \Lenv{subfloat}
% environment. This is a trivial implementation because the \cs{subcaption}
% and \cs{contsubcaption} commands are provided by the class, and can be used
% within a \Lenv{subfloat}.
%    \begin{macrocode}
\newenvironment{subfloat}{}{}

%    \end{macrocode}
% \end{environment}
%
% \begin{macro}{\mem@step@subcounter}
%   \changes{v3.7i}{2019/10/24}{Added}
%  Utility macro to save some typing.
% \changes{v3.8}{2023/08/02}{Added
% \Lhook{memoir/subcaption/aftercounter} hook}
%    \begin{macrocode}
\newcommand\mem@step@subcounter{%
  \refstepcounter{sub\@captype}\@contkeep%
  \UseHook{memoir/subcaption/aftercounter}%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\subbottom}
% \begin{macro}{\@memsubbody}
%    \cs{subbottom}\oarg{list-entry}\oarg{subcaption}\marg{text}
% typesets a subcaption below the \meta{text}. Most of the  work is
% performed by the \cs{@memsubbody} macro.
% \changes{v3.8.4}{2025/09/22}{Changed how we add extra label in \cs{@memsubbody}}
%    \begin{macrocode}
\newcommand{\subbottom}{%
  \@contbotsubtrue
  \@memsubbody}

\newcommand{\@memsubbody}{%
  \bgroup
  % \let\label=\memsub@label
  \let\mem@addto@label@hook\memsub@addto@label@hook
  \ifdonemaincaption\else
    \advance\csname c@\@captype\endcsname\@ne
  \fi
%    \end{macrocode}
% To help with hyperref target placement (hyperref usually uses
% \cs{refstepcounter} to make the anchors) we move the counter
% business into \cs{@memsubfloat} instead. This way they come right at
% the top.
%    \begin{macrocode}
% \changes{v3.7i}{2019/10/24}{Moved \cs{refstepcounter}}
  % \refstepcounter{sub\@captype}\@contkeep%
  \leavevmode
  \@ifnextchar [%
    {\@memsubfig}%
    {\@memsubfig[\@empty]}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\contsubbottom}
% \begin{macro}{\@memcontsubbody}
%     These are the continued versions of \cs{subbottom} and \cs{@memsubbody}.
% \changes{v3.8.4}{2025/09/22}{Changed how we add the extra label}
% \begin{macrocode}
\newcommand{\contsubbottom}{%
  \@contbotsubtrue
  \@memcontsubbody}

\newcommand{\@memcontsubbody}{%
  \bgroup
  % \let\label=\memsub@label
  \let\mem@addto@label@hook\memsub@addto@label@hook
  \@contset
% To help with hyperref target placement (hyperref usually uses
% \cs{refstepcounter} to make the anchors) we move the counter
% business into \cs{@memsubfloat} instead. This way they come right at
% the top.
%    \begin{macrocode}
% \changes{v3.7i}{2019/10/24}{Moved \cs{refstepcounter}}
  % \refstepcounter{sub\@captype}\@contkeep%
  \leavevmode
  \@ifnextchar [%
    {\@memsubfig}%
    {\@memsubfig[\@empty]}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\subtop}
% \begin{macro}{\contsubtop}
%  These are similar to \cs{subbottom} and \cs{contsubbottom} except that they
% put the subcaption on top of the \meta{text}.
%    \begin{macrocode}
\newcommand{\subtop}{%
  \@contbotsubfalse
  \@memsubbody}

\newcommand{\contsubtop}{%
  \@contbotsubfalse
  \@memcontsubbody}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \changes{v1.1a}{2002/04/28}{Deleted \cs{@contsubfloat} as it was not used}
%
% \begin{macro}{\@memsubfig}
% This is a revised version of the \Lpack{subfigure} \cs{@subfigure} command
% --- just the called macro names are changed.
%    \begin{macrocode}
\def\@memsubfig[#1]{%
  \@ifnextchar [%
    {\@memsubfloat{sub\@captype}[#1]}%
    {\@memsubfloat{sub\@captype}[\@empty #1][#1]}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@memsubfloat}
%    This is a modified version of the \Lpack{subfigure} \cs{@subfloat}
% command Essentially the \verb?\csname if#1topcap\endcsname? constructs are
% replaced by \cs{if@contbotsub}. 
% \changes{v3.6k}{2011/05/16}{This ought to be long}
% ^^A #1: subcaptype; #2: for list; #3: subtitle incl label; #4 contents
%    \begin{macrocode}
\long\def\@memsubfloat#1[#2][#3]#4{%
  \@tempcnta=\@ne
  \if@tightsubcap
    \if@minipage
      \@tempcnta=\z@
    \else
      \ifdim\lastskip=\z@
        \@tempcnta=\@ne
      \else
        \@tempcnta=\tw@
      \fi
    \fi
  \fi
  \if@contbotsub
    \def\subfig@top{\subfloattopskip}%
    \def\subfig@bottom{\subfloatbottomskip}%
  \else
    \def\subfig@top{\subfloatbottomskip}%
    \def\subfig@bottom{\subfloattopskip}%
  \fi
%    \end{macrocode}
% We move the refstep business here to help \Lpack{hyperref} get
% better anchors.
% \changes{v3.7i}{2019/10/24}{moved counter stepping, additionally
% changed \cs{vtop} to \cs{vbox}, otherwise we align the images at the
% top}
% \changes{v3.8.4}{2025/09/24}{Moved the boxing of the contents in
% after \cs{mem@step@subcounter} that way a label can be placed inside
% contents (\#4).}
%    \begin{macrocode}
  \vbox\bgroup%
    \mem@step@subcounter%
    \setbox\@tempboxa \hbox{#4}%
    \@tempdima=\wd\@tempboxa
    \vbox\bgroup
    \ifcase\@tempcnta
      \@minipagefalse
    \or
      \vspace{\subfig@top}
    \or
      \ifdim \lastskip=\z@ \else
        \@tempskipb\subfig@top\@xaddvskip
      \fi
    \fi
    \if@contbotsub
      \box\@tempboxa\egroup
      \ifx \@empty#3\relax \else
        \vskip\subfloatcapskip
        \@memsubcaption{#1}{#2}{#3}%
      \fi
    \else
      \ifx \@empty#3\relax \else
        \@memsubcaption{#1}{#2}{#3}%
        \vskip\subfloatcapskip
        \vskip\subfloatcaptopadj
      \fi\egroup
      \box\@tempboxa
    \fi
    \vspace{\subfig@bottom}
  \egroup
\egroup}
  
%    \end{macrocode}
% \end{macro}
%
%
% The following series of macros, from \Lpack{subfigure}, control the 
% typesetting of the subcaptions.
%
% \begin{macro}{\@memsubfigcaptionlist}
% A copy of \cs{@subfigcaptionlist}.
%    \begin{macrocode}
\newcommand*{\@memsubfigcaptionlist}{}
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\memlistsubcaptions}
%   A copy of \cs{listsubcaptions}.
% ^^A note this is not mentioned in the manual
%    \begin{macrocode}
\newcommand*{\memlistsubcaptions}{%
  \@ifstar
    {\gdef\@memsubfigcaptionlist{}}%
    {\@memlistsubcaptions{\@captype}}}

%    \end{macrocode}
% \end{macro}
% 
%
% \begin{macro}{\@memlistsubcaptions}
%   A copy of \cs{@listsubcaptions}. Note that is is executed by
%   either \cs{end@float}, \cs{end@dblfloat} or \cs{@contcaption}.
%    \begin{macrocode}
\newcommand*{\@memlistsubcaptions}[1]{%
  \@ifundefined{@captype}{}{%
    \@ifundefined{ext@sub#1}{}{%
      \@for \@tempa:=\@memsubfigcaptionlist \do {%
        \ifx \@empty\@tempa\relax \else
          \addcontentsline{\@nameuse{ext@sub#1}}{sub#1}{\@tempa}%
        \fi}}}%
  \gdef\@memsubfigcaptionlist{}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@makesubfloatcaption}
%  This is a copy of \cs{@makesubfigurecaption}.
% \changes{v3.6k}{2011/07/21}{Added a \cs{unskip} to remove a space if
% the text is empty}
%    \begin{macrocode}
\newcommand{\@makesubfloatcaption}[2]{%
  \setbox\@tempboxa\hbox{%
    \@subcapsize
    {\@subcaplabelfont #1}{\@subcapfont\ignorespaces #2}\unskip}%
  \@tempdimb=-\subfloatcapmargin
  \multiply\@tempdimb\tw@
  \advance\@tempdimb\@tempdima
  \hb@xt@\@tempdima{%
    \hss
    \ifdim \wd\@tempboxa >\@tempdimb
      \memsubfig@caption{#1}{#2}%
    \else
      \if@shortsubcap
        \memsubfig@caption{#1}{#2}%
      \else
        \box\@tempboxa
      \fi
    \fi
    \hss}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\memsubfig@caption}
% This is a copy of \cs{subfig@caption}.
% \changes{v3.6k}{2011/07/21}{Added a \cs{unskip} to remove a space if
% the text is empty}
%    \begin{macrocode}
\newcommand{\memsubfig@caption}[2]{%
  \if@hangsubcap
    \sbox{\@tempboxa}{\@subcapsize\@subcaplabelfont #1}%
    \addtolength{\@tempdimb}{-\wd\@tempboxa}%
    \usebox{\@tempboxa}%
    \memsubfig@captionpar{\@tempdimb}{%
      {\@subcapfont\ignorespaces #2}\unskip}%
  \else
    \memsubfig@captionpar{\@tempdimb}{{\@subcaplabelfont #1}%
      {\@subcapfont\ignorespaces #2}\unskip}%
  \fi}

%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\memsubfig@captionpar}
% This replaces \cs{subfig@captionpar}.
%    \begin{macrocode}
\newcommand{\memsubfig@captionpar}[2]{%
  \parbox[t]{#1}{\@subcapsize\@contsubcstyle #2}}

%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\memsub@label}
% Basically we want a \cmd{\label} inside the caption to set
% \emph{two} labels with different values of
% \cmd{\@currentlabel}. First locally \cmd{\label} is set to
% \cmd{\mem@sublabel} defined as
% \changes{v3.8.4}{2025/09/22}{No longer needed due to reimplementation}
%    \begin{macrocode}
 % \newcommand{\memsub@label}{%
 %   \@ifnextchar (%
 %     {\sf@memsub@label}%
 %     {\sf@memsub@label(Sub\@captype\space
 %                      \@nameuse{p@sub\@captype}%
 %                      \@nameuse{thesub\@captype})}}
%    \end{macrocode}
% \end{macro}
%
% As of summer 2023 we are autoloading \Lpack{nameref}, thus the code
% for \cmd{\sf@@memsub@label} can be greatly reduced plus we can use
% the \cmd{\label} that has the \Lpack{nameref} extensions, then we
% don't have to look out for changes in say \Lpack{hyperref} etc.
% 
% \begin{macro}{\sf@memsub@label}
% \changes{v3.8}{2023/07/31}{Set \cs{@currentlabelname} directly
% instad of using \cs{mem@currentlabelname}}
% \changes{v3.8.4}{2025/09/22}{No longer needed due to reimplementation}
%    \begin{macrocode}
 % \def\sf@memsub@label(#1)#2{%
 %   \protected@edef\@currentlabelname{#1}%
 %   % if available we can also use %  \ExpandArgs{x}\mem@set@cln{#1}
 %   \sf@@memsub@label{#2}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sf@@memsub@label}
% \changes{v3.8}{2023/07/31}{reimplemented}
% This sets two labels, the user given one an one prefixed by
% \verb?sub@?. The difference between them is the value of
% \cmd{\@currentlabel}. For the latter we will aditionally locally
% disable showkeys.
%
% First we'd like to have a copy of the ``kernel'' \cmd{\label}
% command. Packages may have added stuff to make a copy at begin doc.
% \begin{macro}{\mem@kernel@label}
% \changes{v3.8.4}{2025/09/22}{No longer needed due to reimplementation}
%    \begin{macrocode}
 % \AtBeginDocument{
 %   \let\mem@kernel@label\label
 % }

%    \end{macrocode}
% Next we define the macro it self in terms of this
% \changes{v3.8.4}{2025/09/22}{No longer needed due to reimplementation}
%    \begin{macrocode}
 % \newcommand\sf@@memsub@label[1]{%
 %   \@bsphack%
 %   \mem@kernel@label{#1}% normal label
%    \end{macrocode}
%  Next locally redefine \cmd{\@currentlabel} so the next label only
%  gets the sub number. TODO: make the format
%  configurable. Additionally disable showkeys for this extra
%  label. This way we do not need a hook into the construction to
%  support \Lpack{showkeys} that just comes from the normal \cmd{\label}.
%    \begin{macrocode}
 %   \begingroup%
 %   % \ExpandArgs{x}\mem@set@cln{\@nameuse{@@thesub\@captype}}
 %   \protected@edef\@currentlabel{\@nameuse{@@thesub\@captype}}% sub@label
 %   \def\showkeyslabelformat##1{}% disable showkeys for this extra label
 %   \mem@kernel@label{sub@#1}% internally generated sub@label
 %   \endgroup%
 %   \@esphack%
 % }

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\subcaptionref}
% This is a copy of the \cs{subref} macro.
%    \begin{macrocode}
\DeclareRobustCommand{\subcaptionref}{%
  \@ifstar{\ssc@ref}{\sc@ref}}
%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\ssc@ref}
% \begin{macro}{\sc@ref}
% The implementation of the starred and unstarred forms of \cs{subcaptionref}.
%    \begin{macrocode}
\newcommand*{\ssc@ref}[1]{\ref{sub@#1}}
\newcommand*{\sc@ref}[1]{{\@subcaplabelfont\ref{sub@#1}}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% 
% \subsubsection{Side captions}
% \changes{v1.61803}{2008/01/30}{Added all the code for side captions 
%         (mempatch v4.1)}
%
% \begin{macro}{\m@mscap@capbox}
% \begin{macro}{\m@mscap@fbox}
% We need two save boxes, one to hold the caption and the other
% for the float material.
%    \begin{macrocode}
\newsavebox{\m@mscap@capbox}
\newsavebox{\m@mscap@fbox}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\sidecapsep}
% \begin{macro}{\sidecapwidth}
% \cs{sidecapsep} is the space between the text and the caption, which
% is set in a box \cs{sidecapwidth} wide. These are initialized to
% the \cs{marginpar...} values.
%    \begin{macrocode}
\newdimen\sidecapsep
  \sidecapsep=\marginparsep
\newdimen\sidecapwidth
  \sidecapwidth=\marginparwidth
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\setsidecaps}
% \cs{setsidecaps}\marg{sep}\marg{width} sets the \cs{sidecapsep} and
% \cs{sidecapwidth} (Ivars Finvers noted that the initial values don't change 
% if the \cs{marginpar...} values change, such as at \cs{checkandfixthelayout}).
% \changes{v1.61803}{2008/01/30}{Added \cs{setsidecaps} (mempatch v4.6)}
%    \begin{macrocode}
\newcommand*{\setsidecaps}[2]{%
  \setlength{\sidecapsep}{#1}\@memznegtest{\sidecapsep}%
  \setlength{\sidecapwidth}{#2}\@memznegtest{\sidecapwidth}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@m@tempdima}
% \begin{macro}{\m@mscapraise}
% Lengths for internal use. \cs{m@m@tempdima} is meant for general
% temporary use.
%    \begin{macrocode}
\newdimen\m@m@tempdima
\newdimen\m@mscapraise
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\sidecapraise}
% Length to make (small) adjustments to the position of the caption wrt the float.
%    \begin{macrocode}
\newdimen\sidecapraise
  \sidecapraise \z@

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\setsidecappos}
% \begin{macro}{\m@mscappos}
% \cs{setsidecappos}\marg{pos}, where \meta{pos} is one of \texttt{t},
% \texttt{c}, or \texttt{b}, sets the vertical position of the caption
% in relation to the float and the result is saved as \cs{m@mscappos}.
% The default is \texttt{c}.
%    \begin{macrocode}
\newcommand*{\setsidecappos}[1]{%
  \def\m@mscappos{#1}\def\@tempb{t}%
  \ifx\@tempb\m@mscappos
  \else
    \def\@tempb{b}%
    \ifx\@tempb\m@mscappos
    \else
      \def\@tempb{c}%
      \ifx\@tempb\m@mscappos
      \else
        \@memerror{Argument to \string\setsidecappos\space is not t or c or b.
                   \MessageBreak Set to c}{\@ehc}%
        \def\m@mscappos{c}%
      \fi
    \fi
  \fi}     
\setsidecappos{c}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\sidecapmargin}
% \begin{macro}{\m@mscapmarg}
% \cs{sidecapmargin}\marg{margin}, where \meta{marg} is one of
% \texttt{left}, \texttt{right}, \texttt{inner}, or \texttt{outer}, 
% controls the margin where the caption will be put. The result
% is saved as \cs{m@mscapmarg} as a number. The default
% is \texttt{left}.
%    \begin{macrocode}
\newcommand{\sidecapmargin}[1]{%
  \def\@tempa{#1}\def\@tempb{left}%
    \ifx\@tempb\@tempa
      \def\m@mscapmarg{0}%   left
    \else
      \def\@tempb{right}%
      \ifx\@tempb\@tempa
        \def\m@mscapmarg{1}%  right
      \else
        \def\@tempb{outer}%
        \ifx\@tempb\@tempa
          \def\m@mscapmarg{2}%  outer
        \else
          \def\@tempb{inner}%
          \ifx\@tempb\@tempa
            \def\m@mscapmarg{3}%  inner
          \else
            \@memerror{Unrecognized argument for \string\sidecapmargin}%
                      {\@ehc}%
            \def\m@mscapmarg{-1}% error
          \fi
        \fi
      \fi
    \fi}
\sidecapmargin{left}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\ifscapmargleft}
% \begin{macro}{\scapmarglefttrue}
% \begin{macro}{\scapmargleftfalse}
%  \cs{ifscapmargleft} is TRUE the caption should be in the left hand margin,
% otherwise in the right hand margin.
%    \begin{macrocode}
\newif\ifscapmargleft

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\sidecapfloatwidth}
% \begin{macro}{\m@mscapmainwidth}
% \cs{sidecapfloatwidth} is the width of the box holding the float. 
% Note that this is a macro,
% not a length, so must be changed using \cs{renewcommand*}.
% The default is \cs{linewidth}. Later, \cs{m@mscapmainwidth} will be set
% to the current length specification from \cs{sidecapfloatwidth}.
%    \begin{macrocode}
\def\sidecapfloatwidth{\linewidth}
\newdimen\m@mscapmainwidth

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\m@mscaplkern}
% \begin{macro}{\setm@mscaplkern}
% \cs{setm@mscaplkern} is a utility macro to calculate the kern 
% (\cs{m@mscaplkern}) required when the caption is in the left margin.
%    \begin{macrocode}
\newdimen\m@mscaplkern
\newcommand*{\setm@mscaplkern}{%
  \m@mscaplkern=\sidecapwidth
  \advance\m@mscaplkern \sidecapsep
  \advance\m@mscaplkern \m@mscapmainwidth}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\sidecapstyle}
% \cs{sidecapstyle} is called just before the caption is set. It can
% be redefined to set different caption style parameters. The default
% is raggedleft for left margin captions and raggedright for right
% margin captions.
%    \begin{macrocode}
\newcommand*{\sidecapstyle}{%
  \ifscapmargleft
    \captionstyle{\raggedleft}%
  \else
    \captionstyle{\raggedright}%
  \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sidecaption}
% The whole shebang is in the \texttt{sidecaption} environment but
% it is more convenient to specify this via macros rather than 
% directly as an environment.
%
% \cs{sidecaption}\oarg{fortoc}\marg{title}\oarg{label} is what it
% looks like to the user, but internally further macros handle
% all the arguments.
%    \begin{macrocode}
\newcommand*{\sidecaption}{%
  \@ifnextchar [{\@sidecaption}{\@sidecaption[]}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@sidecaption}
% \cs{@sidecaption}\oarg{fortoc}\marg{title} grabs the first
% two arguments.
%    \begin{macrocode}
\def\@sidecaption[#1]#2{%
  \@ifnextchar [{\@@sidecaption{#1}{#2}}{\@@sidecaption{#1}{#2}[]}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@mem@scap@beforehook}
% \begin{macro}{\@mem@scap@afterhook}
% Two hooks into the 'scap' internals. By default they do nothing, but
% can be used make say sidecaption align towards the spine in twosided
% documents. This is done by redefining \emph{before} to
% \verb+\checkoddpage\ifoddpage\else\raggedleft\fi+ and redefining
% \emph{after} to \verb+\par+. Note that since 'sidecontcaption',
% 'sidenamedlegend' and 'sidelegend' all share the same basic
% internals redefining the two hooks will affect those as well. The
% user might want to create their own special environment, say, like this:
% \begin{verbatim}
% \makeatletter
% \newenvironment{sidecaption*}{
%   \renewcommand\@mem@scap@beforehook{\checkoddpage\ifoddpage\else\raggedleft\fi}
%   \renewcommand\@mem@scap@afterhook{\par}
%   \begin{sidecaption}}
%   {\end{sidecaption}}
% \makeatother
% \end{verbatim}
% \changes{v1.6180339c}{2009/01/21}{Added 'before' and 'after' hooks
% to shared sidecaption internals}
%    \begin{macrocode}
\newcommand\@mem@scap@beforehook{}
\newcommand\@mem@scap@afterhook{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@@sidecaption}
% \cs{@@sidecaption}\marg{fortoc}\marg{title}\oarg{label} is the
% last macro in the chain and handles all three arguments.
% This does all the work for \verb?\begin{sidecaption}?
% \begin{macro}{\m@mscap@fortoc}
% \begin{macro}{\m@mscap@forcap}
% \begin{macro}{\m@mscaplabel}
% First, save all the arguments as macros.
%    \begin{macrocode}
\def\@@sidecaption#1#2[#3]{%
  \ifx\@empty#1\@empty
    \def\m@mscap@fortoc{#2}%
  \else
    \def\m@mscap@fortoc{#1}%
  \fi
  \def\m@mscap@forcap{#2}%
  \ifx\@empty#3\@empty
    \def\m@mscaplabel{}%
  \else
    \def\m@mscaplabel{\@bsphack\label{#3}\@esphack}%
  \fi
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% Set the float width, calculate the left margin kern, and start
% a \texttt{minipage} to hold the float, saving it in box
% \cs{m@mscap@fbox}.
%    \begin{macrocode}
  \m@mscapstart@fbox}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@mscapstart@fbox}
% \begin{macro}{\m@mscapend@fbox}
% \cs{m@mscapstart@fbox} is the macro that actually sets the float width, 
% calculates the left margin kern, and starts the float's \texttt{minipage}.
% The macro \cs{m@mscapend@fbox} ends the box.
%    \begin{macrocode}
\newcommand*{\m@mscapstart@fbox}{%
%    \end{macrocode}
% \changes{v1.6180339c}{2009/01/21}{Added \cs{@mem@scap@beforehook}}
%    \begin{macrocode}
  \@mem@scap@beforehook%
  \setlength{\m@mscapmainwidth}{\sidecapfloatwidth}%
  \setm@mscaplkern
  \begin{lrbox}{\m@mscap@fbox}%
    \begin{minipage}[c]{\m@mscapmainwidth}}
\newcommand*{\m@mscapend@fbox}{%
    \end{minipage}%
  \end{lrbox}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\endsidecaption}
% \begin{macro}{\endsidecaption@refstepcounter}
% \cs{endsidecaption} does the work for
% \verb?\end{sidecaption}?.

% First we define a helper macro that others can hook into. Here is
% the default definition. The two arguments are either two copies of
% \cs{@captype} or for the cont version, \cs{@captype} and
% \texttt{memhycontfloat}. Then this macro is redefined whenever
% \Lpack{hyperref} is loaded (via \Lpack{memhfixc}). The addition
% eliminates the need for a full macro redef in \Lpack{memhfixc}.
% \changes{v3.8.2}{2023/09/10}{Added macro at the suggestion of Axel Sommerfelt}
%    \begin{macrocode}
\newcommand*\sidecaption@refstepcounter[2]{\refstepcounter{#1}}
%    \end{macrocode}
%
% Finish the float minipage, then increment the caption counter and
% call \cs{label} via \cs{m@mscaplabel}.
%    \begin{macrocode}
\def\endsidecaption{%
  \m@mscapend@fbox
%    \end{macrocode}
% % \changes{v3.8.2}{2023/09/10}{Added macro call at the suggestion of Axel Sommerfelt}
%    \begin{macrocode}
  \sidecaption@refstepcounter\@captype\@captype
  \m@mscaplabel
%    \end{macrocode}
% \changes{v3.6k}{2012/08/19}{We need to move \cs{m@mscapcheckside}
% here or the \cs{sidecapstyle} inside the box, will never work correctly.}
%    \begin{macrocode}
  \m@mscapcheckside%
%    \end{macrocode}
% Set the caption inside a minipage, saving it in box \cs{m@mscap@capbox}.
%    \begin{macrocode}
  \begin{lrbox}{\m@mscap@capbox}%
    \begin{minipage}[c]{\sidecapwidth}%
      \sidecapstyle
      \@caption\@captype[\m@mscap@fortoc]{\m@mscap@forcap}
    \end{minipage}%
  \end{lrbox}%
%    \end{macrocode}
% Output the float and caption.
%    \begin{macrocode}
  \m@mscapopboxes}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\m@mscapopboxes}
% Having determined how high the caption box must be raised with
% respect to the float box, output the boxes. 
%    \begin{macrocode}
\newcommand*{\m@mscapopboxes}{%
  \m@mcalcscapraise
%    \end{macrocode}
% Set the float (from box \cs{m@mscap@fbox}) then the caption (from
% box \cs{m@mscap@capbox}) kerning it to the left or right as
% appropriate.
% \changes{v3.6k}{2012/08/19}{Moved \cs{m@mscapcheckside} into
% \cs{endsidecaption}, otherwise \cs{sidecapstyle} never see the side check}
%    \begin{macrocode}
  \usebox{\m@mscap@fbox}%\m@mscapcheckside
  \ifscapmargleft%
    \rlap{\kern-\m@mscaplkern
          \raisebox{\m@mscapraise}{\usebox{\m@mscap@capbox}}}%
  \else%
    \rlap{\kern\sidecapsep 
          \raisebox{\m@mscapraise}{\usebox{\m@mscap@capbox}}}%
  \fi
%    \end{macrocode}
% Finally, make \cs{m@mscapthisside} a no-op.
%    \begin{macrocode}
  \gdef\m@mscapthisside{}%
%    \end{macrocode}
% \changes{v1.6180339c}{2009/01/21}{Added \cs{@mem@scap@afterhook}}
%    \begin{macrocode}
  \@mem@scap@afterhook%
}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@mcalcscapraise}
% Calculate the amount the caption might have to be raised wrt the
% float. This depends on the position: \\
% \texttt{t:} raise by the difference in heights \\
% \texttt{c:} shouldn't have to do anything as the minipages are meant
%             to center aligned \\
% \texttt{b:} lower by the difference in depths \\
%
%    However, experiments showed that a little bit of tweaking might
% help. The final adjustment, \cs{sidecapraise} is controlled by
% the user.
%    \begin{macrocode}
\newcommand*{\m@mcalcscapraise}{%
  \def\@tempb{t}%
  \ifx\m@mscappos\@tempb
    \settoheight{\m@m@tempdima}{\strut\usebox{\m@mscap@capbox}}%
    \settoheight{\m@mscapraise}{\usebox{\m@mscap@fbox}}%
    \advance\m@mscapraise -\m@m@tempdima
    \advance\m@mscapraise  0.5ex
  \else
    \def\@tempb{b}%
    \ifx\m@mscappos\@tempb
      \settodepth{\m@m@tempdima}{\usebox{\m@mscap@fbox}}%
      \settodepth{\m@mscapraise}{\strut\usebox{\m@mscap@capbox}}%
      \advance\m@mscapraise -\m@m@tempdima
    \else
      \m@mscapraise=\z@
      \advance\m@mscapraise 0.25ex
    \fi
  \fi
  \advance\m@mscapraise  \sidecapraise}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@mscapcheckside}
% This macro determines whether the caption should be set in the
% left or right margin. In twocolumn documents the caption for a single
% column float is always set in the adjacent margin. Starred floats
% are treated as regular floats as in a onecolumn document.
%    \begin{macrocode}
\newcommand*{\m@mscapcheckside}{%
  \if@twocolumn
    \ifdim\hsize=\textwidth%  float*
      \m@mscapcheckregside
    \else
      \if@firstcolumn
        \scapmarglefttrue
      \else
        \scapmargleftfalse
      \fi
    \fi
  \else
    \m@mscapcheckregside
  \fi
%    \end{macrocode}
% Finally apply any user's override.
%    \begin{macrocode}
  \m@mscapthisside}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@mscapcheckregside}
% This performs the margin calculation for onecolumn documents.
%    \begin{macrocode}
\newcommand*{\m@mscapcheckregside}{%
    \if@twoside
      \checkoddpage
      \ifnum\m@mscapmarg<\@ne%      % left
        \scapmarglefttrue
      \else
        \ifnum\m@mscapmarg=\@ne%    % right
          \scapmargleftfalse
        \else  
          \ifnum\m@mscapmarg=\tw@%  % outer
            \scapmarglefttrue
            \ifoddpage
              \scapmargleftfalse
            \fi
          \else%                  % inner
            \scapmargleftfalse
            \ifoddpage
              \scapmarglefttrue
            \fi
          \fi
        \fi
      \fi
    \else%     oneside
%    \end{macrocode}
% In oneside documents, inner and outer is the same as left and right.
% \changes{v3.7f}{2015/08/10}{Side caption placement bugfix for
% onesided docs. Related to \protect\url{http://tex.stackexchange.com/q/259324/3929}.
% }
%    \begin{macrocode}
      % \scapmarglefttrue% 0 and 3
      % \ifnum\m@mscapmarg>\@ne
      %   \ifnum\m@mscapmarg<\thr@@
      %     \scapmargleftfalse
      %   \fi
      % \fi
      \ifcase\m@mscapmarg\relax% 0
        \scapmarglefttrue%
      \or% 1
        \scapmargleftfalse%
      \or% 2
        \scapmargleftfalse%
      \or% 3
        \scapmarglefttrue%
      \fi%
    \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\overridescapmargin}
% \begin{macro}{\m@mscapthisside}
% User macro to override the calculated caption margin. Call as either:\\
% \verb?\overridescapmargin{left}? or \verb?\overridescapmargin{right}?  \\
%    \begin{macrocode}
\newcommand*{\overridescapmargin}[1]{%
  \def\@tempb{#1}\def\@tempa{left}%
  \ifx\@tempa\@tempb
    \def\m@mscapthisside{\scapmarglefttrue}%
  \else
    \def\@tempa{right}%
    \ifx\@tempa\@tempb
      \def\m@mscapthisside{\scapmargleftfalse}%
    \else
      \@memerror{Argument to \string\overridescapmargin\space neither 
                 left nor right}{\@ehc}%
      \def\m@mscapthisside{}%
    \fi
  \fi}
\newcommand*{\m@mscapthisside}{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%    Now for the other kinds of captions.
%
% \begin{macro}{\sidecontcaption}
% \cs{sidecontcaption}\marg{title}\oarg{label} is for
% a continuation sidecaption.
%    \begin{macrocode}
\newcommand*{\sidecontcaption}{%
  \@sidecontcaption}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@sidecontcaption}
% \cs{@sidecontcaption}\marg{title} grabs the first
% argument.
%    \begin{macrocode}
\def\@sidecontcaption#1{%
  \@ifnextchar [{\@@sidecontcaption{#1}}{\@@sidecontcaption{#1}[]}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@@sidecontcaption}
% \cs{@@sidecontcaption}\marg{title}\oarg{label} is the
% last macro in the chain and handles all two arguments.
% This does all the work for \verb?\begin{sidecontcaption}?
%    \begin{macrocode}
\def\@@sidecontcaption#1[#2]{%
  \def\m@mscap@forcap{#1}%
  \ifx\@empty#2\@empty
    \def\m@mscaplabel{}%
  \else
    \def\m@mscaplabel{\@bsphack\label{#2}\@esphack}%
  \fi
  \m@mscapstart@fbox}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\endsidecontcaption}
% \cs{endsidecontcaption} does the work for \verb?\end{sidecontcaption}?.
%
%    \begin{macrocode}
\def\endsidecontcaption{%
  \m@mscapend@fbox
  \addtocounter{\@captype}{\m@ne}
%    \end{macrocode}
% \changes{3.8.2}{2023/09/10}{factor refstep counter as in \cs{endsidecaption}}
%    \begin{macrocode}
  \sidecaption@refstepcounter\@captype{memhycontfloat}
  %\refstepcounter\@captype
  \m@mscaplabel
%    \end{macrocode}
% \changes{v3.7b}{2013/05/30}{Forgot the side check}
%    \begin{macrocode}
  \m@mscapcheckside %<--- added 2013/05/30
  \begin{lrbox}{\m@mscap@capbox}%
    \begin{minipage}[c]{\sidecapwidth}%
      \sidecapstyle
      \@contcaption\@captype{\m@mscap@forcap}
    \end{minipage}%
  \end{lrbox}%
  \m@mscapopboxes}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\sidenamedlegend}
% \begin{macro}{\@sidenamedlegend}
% \cs{sidenamedlegend}\oarg{fortoc}\marg{title} is for
% a namedlegend sidecaption.
%    \begin{macrocode}
\newcommand*{\sidenamedlegend}{%
  \@ifnextchar [{\@sidenamedlegend}{\@sidenamedlegend[]}}
\def\@sidenamedlegend[#1]#2{%
  \@@sidenamedlegend{#1}{#2}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@@sidenamedlegend}
% \cs{@@sidenamedlegend}\marg{fortoc}\marg{title} is the
% last macro in the chain and handles all arguments.
% This does all the work for \verb?\begin{sidenamedlegend}?
%    \begin{macrocode}
\def\@@sidenamedlegend#1#2{%
  \ifx\@empty#1\@empty
    \def\m@mscap@fortoc{#2}%
  \else
    \def\m@mscap@fortoc{#1}%
  \fi
  \def\m@mscap@forcap{#2}%
  \def\m@mscaplabel{}%
  \m@mscapstart@fbox}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\endsidenamedlegend}
% \cs{endsidenamedlegend} does the work for \verb?\end{sidenamedlegend}?.
%    \begin{macrocode}
\def\endsidenamedlegend{%
  \m@mscapend@fbox
  \begin{lrbox}{\m@mscap@capbox}%
    \begin{minipage}[c]{\sidecapwidth}%
      \sidecapstyle
      \@legend\@captype[\m@mscap@fortoc]{\m@mscap@forcap}
    \end{minipage}%
  \end{lrbox}%
  \m@mscapopboxes}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\sidelegend}
% \cs{sidelegend}\marg{title} is for
% a legend sidecaption.
%    \begin{macrocode}
\newcommand*{\sidelegend}{%
  \@@sidelegend}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@@sidelegend}
% \cs{@@sidelegend}\marg{title} is the
% last macro in the chain and handles all arguments.
% This does all the work for \verb?\begin{sidelegend}?
%    \begin{macrocode}
\def\@@sidelegend#1{%
  \def\m@mscap@forcap{#1}%
  \m@mscapstart@fbox}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\endsidelegend}
% \cs{endsidelegend} does the work for \verb?\end{sidelegend}?.
%    \begin{macrocode}
\def\endsidelegend{%
  \m@mscapend@fbox
  \begin{lrbox}{\m@mscap@capbox}%
    \begin{minipage}[c]{\sidecapwidth}%
      \sidecapstyle
      \legend{\m@mscap@forcap}
    \end{minipage}%
  \end{lrbox}%
  \m@mscapopboxes}

%    \end{macrocode}
% \end{macro}
%
% \changes{v3.6k}{2013/015/13}{Added \Lpack{longtable} caption
% support}
% 
% \subsubsection{Handling \Lpack{longtable} captions}
% 
% In \Lpack{longtable} the caption ends up as a special row in the
% table. In order to use our caption formatting we need to redefine
% \cs{LT@makecaption} to use our formatting macro plus
% \cs{belowcaptionskip}. It needs to be
% done after \Lpack{longtable} is loaded, and \emph{not} if the
% \Lpack{ltcaption} package is loaded. The later is used by the
% \Lpack{caption} package to aid caption formatting i
% \Lpack{longtable}. Special thanks to Axel Sommerfelt.
% \begin{macro}{\LT@makecaption}
%    \begin{macrocode}
\AtBeginDocument{
  \@ifpackageloaded{longtable}{
    \@ifpackageloaded{ltcaption}{}{%
      \def\LT@makecaption#1#2#3{%
        \LT@mcol\LT@cols c{\hbox to\z@{\hss\parbox[t]\LTcapwidth{%
           \let\@memtempa\relax%   
           % starred form -> #1 = \@gobble
           \ifx#1\@gobble%
             \let\@contnfont\@empty%
             \let\@contdelim\@empty%
             \@@makecaption{}{#3}%
           \else%
             \@@makecaption{#2}{#3}%
           \fi%
           \endgraf\vskip\belowcaptionskip}%
         \hss}}}
    }
  }{}
}
%    \end{macrocode}
% At a later point, we will supplement with a \cs{legend} for
% \Lpack{longtable} as well.
% \end{macro}
%
% \section{Epigraphs}
%
% This code comes from the \Lpack{epigraph} package~\cite{EPIGRAPH}.
%
% \begin{macro}{\beforeepigraphskip}
% \begin{macro}{\afterepigraphskip}
% \begin{macro}{\epigraphwidth}
% \begin{macro}{\epigraphrule}
%    The several length commands, which can be changed by the user with
% \cs{setlength}.
%    \begin{macrocode}
\newlength{\beforeepigraphskip}
  \setlength{\beforeepigraphskip}{.5\baselineskip}
\newlength{\afterepigraphskip}
  \setlength{\afterepigraphskip}{.5\baselineskip}
\newlength{\epigraphwidth}
  \setlength{\epigraphwidth}{.4\textwidth}
\newlength{\epigraphrule}
  \setlength{\epigraphrule}{.4\p@}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\epigraphsize}
%    The size of the font to be used.
%    \begin{macrocode}
\newcommand{\epigraphsize}{\small}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\epigraphflush}
% \begin{macro}{\textflush}
% \begin{macro}{\sourceflush}
%  The three commands to position epigraphs in the textblock and to position
%  the components of the epigraph.
%    \begin{macrocode}
\newcommand{\epigraphflush}{flushright}
\newcommand{\textflush}{flushleft}
\newcommand{\sourceflush}{flushright}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\epigraphfontsize}
% \begin{macro}{\epigraphposition}
% \begin{macro}{\epigraphtextposition}
% \begin{macro}{\epigraphsourceposition}
% These are declarative forms of the above. It's a bit late now, but
% the previous macros should have been internal.
% \changes{v1.2}{2002/08/10}{Added some declarations for epigraphs.}
%    \begin{macrocode}
\newcommand{\epigraphfontsize}[1]{\def\epigraphsize{#1}}
\newcommand{\epigraphposition}[1]{\long\def\epigraphflush{#1}}
\newcommand{\epigraphtextposition}[1]{\def\textflush{#1}}
\newcommand{\epigraphsourceposition}[1]{\def\sourceflush{#1}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
%
%
% \begin{macro}{\@epirule}
%  The internal command to draw a rule between text and source.
%    \begin{macrocode}
\newcommand{\@epirule}{\rule[.5ex]{\epigraphwidth}{\epigraphrule}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@epitext}
% The internal command to typeset the \meta{text}. Put it into a minipage of the
% right size and typeset per \cs{textflush}.
% \changes{v1.61803}{2008/01/30}{Added \cs{par} to \cs{@epitext} and 
%         \cs{@episource} (mempatch v4.7)}
%    \begin{macrocode}
\newcommand{\@epitext}[1]{%
  \begin{minipage}{\epigraphwidth}\begin{\textflush} #1\par
%    \end{macrocode}
%  Draw a rule if it will be visible, otherwise add some extra vertical space.
%    \begin{macrocode}
    \ifdim\epigraphrule>\z@ \@epirule \else \vspace*{1ex} \fi
  \end{\textflush}\end{minipage}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@episource}
%    The internal command for typesetting the \meta{source}, which is put 
% into a minipage and typeset according to \cs{sourceflush}.
%    \begin{macrocode}
\newcommand{\@episource}[1]{%
  \begin{minipage}{\epigraphwidth}
    \begin{\sourceflush} #1\par
  \end{\sourceflush}\end{minipage}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\epigraph}
%    Having got the preliminaries out of the way, here's the user command
% for a single epigraph. This is set in a minipage to prevent breaking
% across a page. Position it according to \cs{epigraphflush}.
%    \begin{macrocode}
\newcommand{\epigraph}[2]{\vspace{\beforeepigraphskip}
  {\epigraphsize\begin{\epigraphflush}\begin{minipage}{\epigraphwidth}
    \@epitext{#1}\\ \@episource{#2}
    \end{minipage}\end{\epigraphflush}
    \vspace{\afterepigraphskip}}}
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\qitem}
% \begin{macro}{\qitemlabel}
%    \cs{qitem} is the epigraph list version of \cs{item}. 
% Set everything inside a minipage.
%    \begin{macrocode}
\newcommand{\qitem}[2]{{%
  \raggedright\item \begin{minipage}{\epigraphwidth}
    \@epitext{#1}\\ \@episource{#2}
  \end{minipage}}}
%    \end{macrocode}
%  \cs{qitemlabel} is needed for a list as well. It is not going to 
% typeset anything.
%    \begin{macrocode}
\newcommand{\qitemlabel}[1]{\hfill}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{environment}{epigraphs}
%  Now for the epigraph list. This is defined in terms of a \Lenv{list}
% environment. 
%    \begin{macrocode}
\newenvironment{epigraphs}{%
%    \end{macrocode}
% Do the vertical space, set the font size, position according to 
% \cs{epigraphflush}, and put everything into a minipage.
%    \begin{macrocode}
  \vspace{\beforeepigraphskip}\begin{\epigraphflush}
  \epigraphsize
  \begin{minipage}{\epigraphwidth}
   \list{}%
%    \end{macrocode}
%  Make the list just fit the minipage (i.e., no indents).
%    \begin{macrocode}
    {\itemindent\z@ \labelwidth\z@ \labelsep\z@
     \leftmargin\z@ \rightmargin\z@
     \let\makelabel\qitemlabel}}%
  {\endlist\end{minipage}\end{\epigraphflush}
   \vspace{\afterepigraphskip}}
%    \end{macrocode}
% \end{environment}
%
% \subsection{Epigraphs before a chapter title}
%
%
% \begin{macro}{\@epichapapp}
% \begin{macro}{\dropchapter}
% \begin{macro}{\undodrop}
%    Commands to drop and restore positions of chapter titles. Dropping is
% accomplished by inserting vertical space before the \cs{@chapapp} command.
%    \begin{macrocode}
\newcommand{\dropchapter}[1]{%
  \let\@epichapapp\@chapapp
  \renewcommand{\@chapapp}{\vspace*{#1}\@epichapapp}}
\newcommand{\undodrop}{\let\@chapapp\@epichapapp}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% Placing an epigraph before a chapter title uses the scheme outlined
% by Piet van Oostrum~\cite{FANCYHDR}. This is to put a zero sized
% picture into the page header. 
%
% \begin{macro}{\if@epirhs}
% \begin{macro}{\if@epicenter}
%  Two booleans for testing whether an epigraph is to be at the RH margin,
% centered, or at the LH margin. The default is RH margin.
%    \begin{macrocode}
\newif\if@epirhs     \@epirhstrue
\newif\if@epicenter  \@epicentertrue
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@epipos}
%    This routine sets the \cs{if@epi...} booleans according to the value of
% \cs{epigraphflush}. If \cs{epigraphflush} is neither \texttt{center} nor 
% \texttt{flushleft}
% then it defaults to \texttt{flushright}. We have to use this to be upward 
% compatible with \cs{epigraphflush} being set by the user with \cs{renewcommand}.
%    \begin{macrocode}
\newcommand{\@epipos}{
  \long\def\@ept{flushleft}
  \ifx\epigraphflush\@ept
    \@epirhsfalse \@epicenterfalse
  \else
    \long\def\@ept{center}
    \ifx\epigraphflush\@ept
      \@epirhsfalse \@epicentertrue
    \else
      \@epirhstrue  \@epicenterfalse
    \fi
  \fi}
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\epigraphhead}
% \cs{epigraphhead}\oarg{distance}\marg{text} puts \meta{text} at
% \meta{distance} (a number, not a length) below the header at the 
% page position specified by \cs{epigraphflush}.
%    \begin{macrocode}
\newcommand{\epigraphhead}[2][95]{%
%    \end{macrocode}
% We have to use \cs{def} instead of the normal \LaTeX{} definition commands
% as we will keep on
% (re)defining things. For reasons that are not fully clear to me \LaTeX{}
% doesn't seem to like me using a \cs{savebox} for storing the epigraph text,
% so I'll use a command instead.
%    \begin{macrocode}
  \def\@epitemp{\begin{minipage}{\epigraphwidth}#2\end{minipage}}
%    \end{macrocode}
% Define an \texttt{epigraph} page style.
%    \begin{macrocode}
  \def\ps@epigraph{\let\@mkboth\@gobbletwo
%    \end{macrocode}
% There are three possible definitions for \cs{@oddhead} depending on the
% value of \cs{epigraphflush}. We call \cs{@epipos} to decide which one to do.
%    \begin{macrocode}
    \@epipos
    \if@epirhs
      \def\@oddhead{\hfil\begin{picture}(0,0)
                         \put(0,-#1){\makebox(0,0)[r]{\@epitemp}}
                         \end{picture}}
    \else
      \if@epicenter
        \def\@oddhead{\hfil\begin{picture}(0,0)
                           \put(0,-#1){\makebox(0,0)[b]{\@epitemp}}
                           \end{picture}\hfil}
      \else
        \def\@oddhead{\begin{picture}(0,0)
                           \put(0,-#1){\makebox(0,0)[l]{\@epitemp}}
                           \end{picture}\hfil}
      \fi
    \fi
    \let\@evenhead\@oddhead
    \def\@oddfoot{\reset@font\hfil\thepage\hfil}
    \let\@evenfoot\@oddfoot}
%    \end{macrocode}
% Make \texttt{epigraph} be the page style for this page.
%    \begin{macrocode}
  \thispagestyle{epigraph}}

%    \end{macrocode}
% \end{macro}
%
%    The above produces a \texttt{plain} pagestyle with the epigraph. Life is
% more complex if someone wants a fancy style with the epigraph. They
% will have to do some work, though.
%
% \begin{macro}{\the@epigraph}
% \begin{macro}{\@epidrop}
% \begin{macro}{\epigraphforheader}
% \cs{the@pigraph} is a macro to store the contents of an epigraph, and \cs{@pidrop}
% stores the \meta{distance} number.
% \cs{epigraphforheader}\oarg{distance}\marg{text} defines the internal macros
% appropriately.
% \changes{v1.2}{2002/08/10}{Added \cs{the@epigraph}, \cs{@epidrop}}
% \changes{v1.2}{2002/08/10}{Added \cs{epigraphforheader}}
%    \begin{macrocode}
\newcommand{\the@epigraph}{}
\newcommand{\@epidrop}{95}
\newcommand{\epigraphforheader}[2][95]{%
  \def\@epidrop{#1}\long\def\the@epigraph{#2}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\epigraphpicture}
% \cs{epigraphpicture} puts \cs{the@epigraph} into a zero-sized picture at location
% \verb?(0,-\@epidrop)?. This can then be used as part of a fancy chapter header.
% The coding is similar to \cs{epigraphhead}.
% \changes{v1.2}{2002/08/10}{Added \cs{epigraphpicture}}
%    \begin{macrocode}
\newcommand{\epigraphpicture}{%
  \def\@epitemp{%
    \begin{minipage}{\epigraphwidth}\the@epigraph\end{minipage}}%
  \@epipos
  \if@epirhs
    \begin{picture}(0,0)%
      \put(0,-\@epidrop){\makebox(0,0)[r]{\@epitemp}}%
    \end{picture}%
  \else
    \if@epicenter
      \begin{picture}(0,0)%
        \put(0,-\@epidrop){\makebox(0,0)[b]{\@epitemp}}%
      \end{picture}%
    \else
      \begin{picture}(0,0)%
        \put(0,-\@epidrop){\makebox(0,0)[l]{\@epitemp}}%
      \end{picture}%
    \fi
  \fi}

%    \end{macrocode}
% \end{macro}
%
%
%
% \section{The deprecated font commands}
%
% The class does not support the old font changing commands unless the
% \Lopt{oldfontcommands} option is used.
%
% \begin{macro}{\@memoldfonterr}
% \begin{macro}{\@memoldfontwarn}
% Macros for old font class error and warning. E.g., \\
% \verb?\@memoldfonterr{\tt}{\ttfamily}{\texttt}?
% \changes{v1.4}{2003/02/27}{Added \cs{@memoldfonterr} and \cs{@memoldfontwarn}}
% \changes{v1.618}{2005/09/03}{Fiddled with the braces in \cs{@memoldfontwarn} (mempatch v3.0)}
%    \begin{macrocode}
\newcommand*{\@memoldfonterr}[3]{%
  \@memerror{Font command \protect#1\space is not supported}{%
    Use \protect#2, or \protect#3{...}, or the oldfontcommands option}}
\newcommand*{\@memoldfontwarn}[3]{%
  \@memwarn{The \protect#1\space font command is deprecated.
    \MessageBreak Use \protect#2{...} or {\protect#3... } instead}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%  Just give a single warning when an old font command is used following the
% \Lopt{oldfontcommands} option.
% \changes{v1.4}{2003/11/22}{Just issue a single warning for an old font
%                            (from patch v1.9)}
%
% \begin{macro}{\@mem@rmwarn}
% \begin{macro}{\rm}
% The old command for roman font.
% \changes{v1.0a}{2002/01/29}{Changed definition of \cs{rm}}
% \changes{v1.4}{2003/02/27}{More efficient coding of all the old font commands}
%    \begin{macrocode}
\if@memoldfont
  \def\@mem@rmwarn{\@memoldfontwarn{\rm}{\textrm}{\rmfamily}}
  \DeclareOldFontCommand{\rm}{\@mem@rmwarn\gdef\@mem@rmwarn{}%
    \normalfont\rmfamily}{\mathrm}
\else
  \def\rm{\@memoldfonterr{\rm}{\textrm}{\rmfamily}}
\fi

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@mem@sfwarn}
% \begin{macro}{\sf}
% The old sans font command.
% \changes{v1.0a}{2002/01/29}{Changed definition of \cs{sf}}
%    \begin{macrocode}
\if@memoldfont
  \def\@mem@sfwarn{\@memoldfontwarn{\sf}{\textsf}{\sffamily}}
  \DeclareOldFontCommand{\sf}{\@mem@sfwarn\gdef\@mem@sfwarn{}%
    \normalfont\sffamily}{\mathsf}
\else
  \def\sf{\@memoldfonterr{\sf}{\textsf}{\sffamily}}
\fi

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@mem@ttwarn}
% \begin{macro}{\tt}
% The old typewriter font command.
% \changes{v1.0a}{2002/01/29}{Changed definition of \cs{tt}}
%    \begin{macrocode}
\if@memoldfont
  \def\@mem@ttwarn{\@memoldfontwarn{\tt}{\texttt}{\ttfamily}}
  \DeclareOldFontCommand{\tt}{\@mem@ttwarn\gdef\@mem@ttwarn{}%
    \normalfont\ttfamily}{\mathtt}
\else
  \def\tt{\@memoldfonterr{\tt}{\texttt}{\ttfamily}}
\fi

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@mem@bfwarn}
% \begin{macro}{\bf}
% The old bold font command.
% \changes{v1.0a}{2002/01/29}{Changed definition of \cs{bf}}
%    \begin{macrocode}
\if@memoldfont
  \def\@mem@bfwarn{\@memoldfontwarn{\bf}{\textbf}{\bfseries}}
  \DeclareOldFontCommand{\bf}{\@mem@bfwarn\gdef\@mem@bfwarn{}%
    \normalfont\bfseries}{\mathbf}
\else
  \def\bf{\@memoldfonterr{\bf}{\textbf}{\bfseries}}
\fi

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@mem@itwarn}
% \begin{macro}{\it}
% The old italic font command.
% \changes{v1.0a}{2002/01/29}{Changed definition of \cs{it}}
%    \begin{macrocode}
\if@memoldfont
  \def\@mem@itwarn{\@memoldfontwarn{\it}{\textit}{\itshape}}
  \DeclareOldFontCommand{\it}{\@mem@itwarn\gdef\@mem@itwarn{}%
    \normalfont\itshape}{\mathit}
\else
  \def\it{\@memoldfonterr{\it}{\textit}{\itshape}}
\fi

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@mem@slwarn}
% \begin{macro}{\sl}
% The old slanted font command.
% \changes{v1.0a}{2002/01/29}{Changed definition of \cs{sl}}
%    \begin{macrocode}
\if@memoldfont
  \def\@mem@slwarn{\@memoldfontwarn{\sl}{\textsl}{\slshape}}
  \DeclareOldFontCommand{\sl}{\@mem@slwarn\gdef\@mem@slwarn{}%
    \normalfont\slshape}{\@nomath\sl}
\else
  \def\sl{\@memoldfonterr{\sl}{\textsl}{\slshape}}
\fi

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@mem@scwarn}
% \begin{macro}{\sc}
% The old small caps font command.
% \changes{v1.0a}{2002/01/29}{Changed definition of \cs{sc}}
%    \begin{macrocode}
\if@memoldfont
  \def\@mem@scwarn{\@memoldfontwarn{\sc}{\textsc}{\scshape}}
  \DeclareOldFontCommand{\sc}{\@mem@scwarn\gdef\@mem@scwarn{}%
    \normalfont\scshape}{\@nomath\sc}
\else
  \def\sc{\@memoldfonterr{\sc}{\textsc}{\scshape}}
\fi

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@mem@calwarn}
% \begin{macro}{\cal}
% The old calligraphic font command.
% \changes{v1.0a}{2002/01/29}{Added definition of \cs{cal}}
%    \begin{macrocode}
\if@memoldfont
  \def\@mem@calwarn{%
    \@memwarn{The \protect\cal\space font command is deprecated.
    \MessageBreak Try to use \protect\mathcal\space instead}}
  \DeclareRobustCommand*\cal{\@mem@calwarn\gdef\@mem@calwarn{}%
    \@fontswitch\relax\mathcal}
\else
  \def\cal{%
    \@memerror{Font command \protect\cal\space is not supported}{%
    Use \protect\mathcal, or the oldfontcommands option}}
\fi

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@mem@mitwarn}
% \begin{macro}{\mit}
% The old math italic font command.
% \changes{v1.0a}{2002/01/29}{Added definition of \cs{mit}}
%    \begin{macrocode}
\if@memoldfont
  \def\@mem@mitwarn{%
    \@memwarn{The \protect\mit\space font command is deprecated.
    \MessageBreak Try to use \protect\mathnormal\space instead}}
  \DeclareRobustCommand*\mit{\@mem@mitwarn\gdef\@mem@mitwarn{}%
    \@fontswitch\relax\mathnormal}
\else
  \def\mit{%
  \@memerror{Font command \protect\mit\space is not supported}{%
             Use \protect\mathnormal, or the oldfontcommands option}}
\fi

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \changes{v3.8.4}{2025/09/23}{Code about \cs{em} and
% \cs{eminnershape} removed as it is already in the kernel in a better
% version}
%
%
% \section{Cross Referencing} \label{sec:xref}
%
% \subsection{Label referencing}
%
% \begin{macro}{\fref}
% \begin{macro}{\tref}
% \begin{macro}{\pref}
% \begin{macro}{\Aref}
% \begin{macro}{\Bref}
% \begin{macro}{\Pref}
% \begin{macro}{\Cref}
% \begin{macro}{\Sref}
%   These are named references to labeled figures, tables and pages.
%   I find these useful to ensure consistency throughout the document
%   --- I don't have to remember whether it is `see Figure ...' or
%   `figure' or `Fig.' or \ldots.
%
%   These are named references to labeled Part, Chapter and Sectional
%   divisions.
%
%   In hindsight, it is not a good idea for a class to provide these
%   as user preferences differ. It is better for users to define
%   these. From July 2025 we defined them at document start if they
%   aren't already defined. They will give a warning with a suggestion
%   on how to define your own version
% \changes{v1.2}{2002/07/27}{Added \cs{Pref}, \cs{Cref} and \cs{Sref}}
% \changes{v1.61803}{2008/01/30}{Added \cs{Bref} (mempatch v4.9+)}
% \changes{v1.61803}{2008/05/17}{Added \cs{Aref}}
% \changes{v3.8.4}{2025/07/30}{Move tilde here instead as part of \cs{..refname}}
% \changes{v3.8.4}{2025/07/30}{Mark deprecated and delay definition}
% \changes{v3.8.4}{2025/08/04}{Fixed a few typos, inclusing \cs{pref} not using \cs{pageref}}
%    \begin{macrocode}
\ExplSyntaxOn
 % helper function
\cs_new_protected:Npn \memoir_make_deprecated_ref_cmds:nNNN #1#2#3#4#5
{% #1 = starred (adds nobreakspace if not); #2: macro name; #3: ref macro; #4: macro name recommended in comment; #5: macro name we actually use
  \cs_if_exist:NF #2
  {
    \newcommand#2[1]{%
      \MarkDeprecated{#2}{from~memoir~in~2026.\MessageBreak%
        Define~your~own~version~in~the~preamble.~E.g.~via\MessageBreak%
         \string\newcommand\string#2[1]{\string#4\c_tilde_str\string#3{\c_hash_str1}}%
         \MessageBreak}%
       \IfBooleanTF{#1}
       {#5\ref{##1}}
       {#5\nobreakspace\ref{##1}}
    }
  }
}
\NewDocumentCommand\memoir@setup@deprecated@macros{smmm}{
  \memoir_make_deprecated_ref_cmds:nNNN {#1}#2#3#4
}
\ExplSyntaxOff

\AtBeginDocument{
  \memoir@setup@deprecated@macros\fref\ref\figurename\figurerefname
  \memoir@setup@deprecated@macros\tref\ref\tablename\tablerefname
  \memoir@setup@deprecated@macros\pref\pageref\pagename\pagerefname
  \memoir@setup@deprecated@macros\Aref\ref\appendixname\appendixrefname
  \memoir@setup@deprecated@macros\Bref\ref\bookname\bookrefname
  \memoir@setup@deprecated@macros\Pref\ref\partname\partrefname
  \memoir@setup@deprecated@macros\Cref\ref\chaptername\chapterrefname
  \memoir@setup@deprecated@macros*\Sref\ref\sectionname\sectionrefname
}

 % \newcommand*{\fref}[1]{\figurerefname~\ref{#1}}
 % \newcommand*{\tref}[1]{\tablerefname~\ref{#1}}
 % \newcommand*{\pref}[1]{\pagerefname~\pageref{#1}}
 % \newcommand*{\Aref}[1]{\appendixrefname~\ref{#1}}
 % \newcommand*{\Bref}[1]{\bookrefname~\ref{#1}}
 % \newcommand*{\Pref}[1]{\partrefname~\ref{#1}}
 % \newcommand*{\Cref}[1]{\chapterrefname~\ref{#1}}
 % \newcommand*{\Sref}[1]{\sectionrefname\ref{#1}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \subsection{Title referencing}
%
% \changes{v3.8}{2023/07/25}{Entire section rewritten}
% As of Summer 2023 this has been redone by directly loading the
% \Lpack{nameref} package instead. It is loaded without changing the
% sectional macros, which are in turn updated to set
% \cs{@currentlabelname} for the new kernel label system to
% pickup. The new kernel label system also requires us not to modify
% \cs{label} so the switch was required.
%
% \begin{macro}{\titleref}
%   Instead of defining our own macro we now let \cs{titleref} be an
%   alias for \cs{nameref}. Do remember that it also have a starred
%   version.
%    \begin{macrocode}
% disable nameref sectional patches (the macro just needs to be defined)
\def\NR@nopatch@sectioning{set}
\def\NR@nopatch@caption{set}
\RequirePackage{nameref}
\newcommand\titleref{\nameref}

%    \end{macrocode}
% \end{macro}
% \begin{macro}{\mem@set@cln}
%  We'll need to set \cs{@currentlabelname} in various places. The
%  title may need to be cleaned. \Lpack{nameref} provides
%  \cs{NR@gettitle} and we just use our own name for it.
%    \begin{macrocode}
\def\mem@set@cln{\NR@gettitle}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\M@gettitle}
%   All the sectional macros in memoir has been using \cs{M@gettitle}
%   for years to access the title to use for \cs{titleref}. We simply
%   change its definition to use our simpler case. Do remember that if
%   the argument for \cs{M@gettitle} is a macro, it needs to be
%   expanded once.
%    \begin{macrocode}
\newcommand\M@gettitle[1]{\mem@set@cln{#1}}      
%    \end{macrocode}
% \end{macro}
%
% In the sectional macros the title we will be giving to
% \cs{@currentlabelname} will be the title for the toc or if requested
% (and avaiable) the title for the header. That is
% \begin{verbatim}
% \chapter{title}               % sends title to toc and header, so use title
% \chapter[toc]{title}          % sends toc to toc and header, so use toc
% \chapter[toc][header]{title}  % data depends on \headnameref and
%                               % \tocnameref (default)
% \end{verbatim}
% \changes{v1.4}{2003/11/16}{Added title referencing (from patch v1.4)}
%
% \begin{macro}{\ifheadnameref}
% \begin{macro}{\headnameref}
% \begin{macro}{\tocnameref}
% \cs{ifheadnameref}: FALSE use ToC entry, TRUE use header entry. Used
% inside the sectional macros that support two optional arguments.
% \changes{v1.61803}{2008/01/30}{Added \cs{headnameref} and \cs{tocnameref}}
%    \begin{macrocode}
\newif\ifheadnameref
\newcommand*{\headnameref}{\headnamereftrue}
\newcommand*{\tocnameref}{\headnamereffalse}
  \tocnameref
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% Following the 2023 reimplementation of \cmd{\titleref} the following
% public macros are no longer used and are redefined to either do
% nothing or give an error.
% \begin{macro}{\namerefon}
% \begin{macro}{\namerefoff}
% Was used to enable (default) or disable support for
% \cmd{\titleref}. Now does nothing.
%    \begin{macrocode}
\providecommand\namerefon{\@memwarn{\protect\namerefon\space no longer does anything}}     
\providecommand\namerefoff{\@memwarn{\protect\namerefoff\space no longer does anything}}     
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \begin{macro}{\currenttitle}
%   \cmd{\currenttitle} was advertised to give the most recent
%   sectional title. It is better to be more specific and use a label
%   and \cmd{\titleref}. Now defined to give an error.
%    \begin{macrocode}
\providecommand\currenttitle{%
  \@memerror{The \protect\currenttitle\space command is no longer\MessageBreak
    available}{%
    Place a label and use \protect\titleref{label} instead
  }
}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\theTitleReference}
%   Was used to define the output of \cmd{\titleref}. Now just gives a
%   warning.
%    \begin{macrocode}
\providecommand\theTitleReference[2]{%
  \@memwarn{\protect\theTitleReference\space is no longer available}
}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\M@TitleReference}
%   This was used in the old implementation as a part of the data inside
%   \verb|\newlabel| in the \verb|.aux|-files. Deleting it will cause
%   the first compilation after a memoir update to fail. We'll
%   just define it to gobble two args.
%    \begin{macrocode}
\let\M@TitleReference\@gobbletwo
%    \end{macrocode}
% \end{macro}
%
%
% \section{Table of Contents, etc.}
%
%     A \cs{section} command writes a
%     \verb?\contentsline{section}?\marg{title}\marg{page}\verb!{}! command
%     on the \file{.toc} file, where \meta{title} contains the
%     contents of the entry and \meta{page} is the page number. If
%     sections are being numbered, then \meta{title} will be of the
%     form \cs{numberline}\marg{num}\marg{heading} where
%     \meta{num} is the number produced by \cs{thesection}.  Other
%     sectioning commands work similarly.
%
%     A \cs{caption} command in a `figure' environment writes \\
% \verb?\contentsline{figure}{?\cs{numberline}\marg{num}\marg{caption}\verb?}?\marg{page}\verb!{}! \\
%     on the \file{.lof} file, where \meta{num} is the number produced
%     by \cs{thefigure} and \meta{caption} is the figure caption.  It
%     works similarly for a `table' environment.
%
%    The command \cs{contentsline}\marg{name} expands to
%    \cs{l@}\meta{name}.  So, to specify the table of contents, we must
%    define \cs{l@chapter}, \cs{l@section}, \cs{l@subsection}, \ldots ; to
%    specify the list of figures, we must define \cs{l@figure}; and so
%    on.  Most of these can be defined with the \cs{@dottedtocline}
%    command, which works as follows. \\
% \cs{@dottedtocline}\marg{level}\marg{indent}\marg{numwidth}\marg{title}\marg{page}
%
%    \begin{description}
%    \item[\meta{level}] An entry is produced only if\meta{level}
%        $<=$ value of the \Lcount{tocdepth} counter.  Note,
%        \cs{chapter} is level 0, \cs{section} is level 1, etc.
%    \item[\meta{indent}] The indentation from the outer left margin
%        of the start of the contents line.
%    \item[\meta{numwidth}] The width of a box in which the section
%        number is to go, if \meta{title} includes a \cs{numberline}
%        command.
%    \end{description}
%
% \begin{macro}{\@pnumwidth}
% \begin{macro}{\@tocrmarg}
% \begin{macro}{\@dotsep}
%    This command uses the following three parameters, which are set
%    with a \cs{newcommand} (so em's can be used to make them depend upon
%    the font).
%    \begin{description}
%    \item[\texttt{\bslash @pnumwidth}] The width of a box in which the
%        page number is put.
%    \item[\texttt{\bslash @tocrmarg}] The right margin for multiple
%        line entries.  One wants \cs{@tocrmarg} $\ge$ \cs{@pnumwidth}
%    \item[\texttt{\bslash @dotsep}] Separation between dots, in mu
%        units. Should be defined as a number like 2 or 1.7
%    \end{description}
%
%    \begin{macrocode}
\newcommand{\@pnumwidth}{1.55em}
\newcommand{\@tocrmarg} {2.55em}
\newcommand{\@dotsep}{4.5}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\tocentryskip}
% \begin{macro}{\tocbaseline}
% \begin{macro}{\tocskip}
%    We define two lengths and a utility command.
%    \begin{macrocode}
\newlength{\tocentryskip} \setlength{\tocentryskip}{1em}
\newlength{\tocbaseline}  \setlength{\tocbaseline}{20pt}
\newcommand{\tocskip}[1]{%
    \addtocontents{toc}{\protect\vspace{#1}}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \subsection{New List of \ldots}
%
% It is apparent that users want to do at least two things that are not
% readily provided by the standard classes: (a) change the appearance
% of the Table of Contents, etc., headings, and (b) create new List of\ldots.
% This class provides a means of creating new Lists whose headings are
% parameterized, thereby killing two birds with one stone.
%
% In the standard classes the tables of contents, figures etc. are always 
% set in single-column style. In this class you can choose one- or two-column
% ToCs, etc.
% The titles are added to the ToC, unless the starred versions of the 
% commands are used.
% \changes{v1.6180339f}{2009/03/16}{Enabled two-column ToC, etc}
%
% \begin{macro}{\ensureonecol}
% \begin{macro}{\restorefromonecol}
%  These two
% macros cooperate to switch from two-columns to one column, and back again.
% \changes{v1.0a}{2002/01/24}{Deleted \cs{ensuretwocol} and 
%   \cs{restorefromtwocol} as they were unused. BUT later reinstated them.}
% \begin{macro}{\onecoltocetc}
% \begin{macro}{\twocoltocetc}
% \begin{macro}{\doccoltocetc}
% These macros define \cs{ensureonecol} and \cs{restorefromonecol} such that
% \begin{itemize}
% \item \cs{onecoltocetc} ToCs, etc., will be set in one column (the default)
% \item \cs{twocoltocetc} ToCs, etc., will be set in two columns
% \item \cs{doccoltocetc} ToCs, etc., will be set in column(s) corresponding
%        to the document's (onecolumn/twocolumn) option.
% \end{itemize}
% \changes{v1.6180339f}{2009/03/16}{Added \cs{onecoltocetc}, \cs{twocoltocetc}
%                                   and \cs{doccoltocetc}}
%    \begin{macrocode}
\newcommand*{\onecoltocetc}{%
  \def\ensureonecol{%
    \if@twocolumn
      \@restonecoltrue\onecolumn
    \else
      \@restonecolfalse
    \fi}%
  \def\restorefromonecol{\if@restonecol\twocolumn\fi}}
\newcommand*{\twocoltocetc}{%
  \def\ensureonecol{%
    \if@twocolumn
      \@restonecoltrue
    \else
      \@restonecolfalse\twocolumn
    \fi}%
  \def\restorefromonecol{\if@restonecol\else\onecolumn\fi}}
\newcommand*{\doccoltocetc}{%
  \let\ensureonecol\relax
  \let\restorefromonecol\relax}
%    \end{macrocode}
% Set the default
%    \begin{macrocode}
\onecoltocetc

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% 
% \begin{macro}{\cftparskip}
% The \cs{parskip} local to the ToC, etc, is set to the length \cs{cftparskip}.
%    \begin{macrocode}
\newlength{\cftparskip}
\setlength{\cftparskip}{0pt}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\newlistof}
% \cs{newlistof}\marg{listofcmmd}\marg{ext}\marg{listofname}
% creates the command \cs{listofcmmd} to typeset a new List of, where the
% external file has the extension \file{.ext} and the heading title is
% \meta{listofname}. The code for this is a heavily modified part
% of the \Lpack{tocloft} package.
%
%    \begin{macrocode}
\newcommand{\newlistof}[3]{%
%    \end{macrocode}
%
% In the following, \texttt{X} stands for the value of \meta{listofcmmd} and
% \texttt{Z} stands for the value of \meta{ext}.
%
% \begin{macro}{\ext@Z}
% \begin{macro}{\Zdepth}
% The file extension and listing depth, which is set to level~1.
%    \begin{macrocode}
  \@namedef{ext@#2}{#2}
  \@ifundefined{c@#2depth}{\newcounter{#2depth}}{}
  \setcounter{#2depth}{1}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\Zmark}
% The heading marks for the listing.
% \changes{v1.1}{2002/03/10}{Changed \cs{@mkboth} to \cs{markboth} in \cs{Zmark}}
%    \begin{macrocode}
  \@namedef{#2mark}{\markboth{#3}{#3}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\X}
% Typeset the listing title and entries, 
% with both a normal and starred version.
% \changes{v1.61803398}{2009/08/08}{changed such that it only use one
% internal macro}
% \changes{v1.61803398}{2009/08/09}{chose a better name for the
% internal macro}
%    \begin{macrocode}
   \@namedef{#1}{\@ifstar{\@nameuse{mem@#1}{01}}{\@nameuse{mem@#1}{00}}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\mem@X}
% \begin{macro}{\cftZbeforelisthook}
% \begin{macro}{\cftZafterlisthook}
% \changes{v1.61803398}{2009/08/08}{introduced \cs{mem@X} to replace
% \cs{@starZ} and \cs{@plainZ}}
%   In earlier version of the class, we used two macros \cs{@starZ}
%   and \cs{@plainZ}, to reduce code we now only use one, the argument
%   of it takes care of differentiating between the stuff that are
%   different. Two hooks is added just before and after importing the
%   list file contents. Additionally we have added a hook before the
%   title is being executed, it comes after \cs{phantomsection} but
%   before any \cs{addcontentsline}
% \changes{v1.61803398d}{2010/02/14}{added the before and after hooks}
% \changes{v3.7i}{2019/10/25}{moved the @\#2maketitle until after the
% \cs{addcontentsline}, that way the hyperref anchor is above the
% title, not below it. }
% \changes{v3.8.4}{2025/09/16}{Replaced \cs{phantomsection} by \cs{MakeLinkTarget}}
%    \begin{macrocode}
  \@namedef{cft#2beforelisthook}{}%
  \@namedef{cft#2afterlisthook}{}%
  \@namedef{mem@#1}##1{%
    \ensureonecol
    \par
    \begingroup
      % \phantomsection
      \MakeLinkTarget[chapter]{}%
      \if##1
        \ifmem@em@starred@listof\else
          \addcontentsline{toc}{chapter}{#3}
        \fi
      \fi
      \@nameuse{@#2maketitle}
      \parskip\cftparskip
      \@nameuse{cft#2beforelisthook}%
      \@starttoc{#2}%
      \@nameuse{cft#2afterlisthook}%
    \endgroup
    \restorefromonecol}
%    \end{macrocode}
%   
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@Zmaketitle}
% This macro typesets the title.
% \changes{v1.3}{2002/10/10}{Added \cs{printZnonum} to \cs{@Zmaketitle}}
% \changes{v1.61803}{2008/01/30}{Slight changes to \cs{@Zmaketitle}
%         (mempatch v4.6)}
% \changes{v3.6j}{2011/03/01}{Made sure \cs{parskip} is zero in the
% title, otherwise a non-zero \cs{parskip} might cause it to be placed
% incorrectly}
%    \begin{macrocode}
  \@namedef{@#2maketitle}{%
    \@nameuse{#2headstart}
   {\parindent\z@ 
    \parskip\z@
%%%%  \parskip\cftparskip
    \interlinepenalty\@M
%    \end{macrocode}
% \changes{v1.3}{2002/11/14}{Added printZnonum to \cs{newlistof}}
%    \begin{macrocode}
    \@nameuse{print#2nonum}%
    \@nameuse{print#2title}{#3}%
    \@nameuse{#2mark}%
    \thispagestyle{chapter}%
    \@nameuse{after#2title}
   }
    \@afterheading}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\Zheadstart}
% \begin{macro}{\afterZtitle}
% The macros \cs{Zheadstart} and \cs{afterZtitle}
% control what goes before and after the title. They
% default to the corresponding macros for chapters.
%    \begin{macrocode}
  \@namedef{#2headstart}{\chapterheadstart}
  \@namedef{after#2title}{\afterchaptertitle}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\printZnonum}
% This typesets something before the title and defaults
% to \cs{printchapternonum}.
% \changes{v1.3}{2002/10/10}{Added \cs{printZnonum} macro}
%    \begin{macrocode}
  \@namedef{print#2nonum}{\printchapternonum}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\printZtitle}
% The title is typeset by the macro \cs{printZtitle}\marg{title}
% which defaults to \cs{printchaptertitle}.
%    \begin{macrocode}
  \@namedef{print#2title}##1{\printchaptertitle{##1}}
%    \end{macrocode}
% \end{macro}
%
% This is the end of the definition of \cs{newlistof}.
%    \begin{macrocode}
} % end \newlistof

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ifmem@em@starred@listof}
% \begin{macro}{\KeepFromToc}
%   The class handles the created `new lists' a little different than
%   other classes. We automatically add it to the main table of
%   contents. This us usually what one wants. If not, one can always
%   use the starred version. But in some cases other packages will use
%   \cs{tableofcontents} to typeset their own `list of\dots', in which
%   case it becomes a little hard to add a star. Therefore we add a
%   switch that can be used to emulate the starred list of. After the
%   macro \cs{KeepFromToc} the memoir created (non-starred) `list of'
%   will behave as their starred counterpart.
% \changes{v1.61803398}{2009/08/08}{LM: added \cs{KeepFromToc}}
%    \begin{macrocode}
\newif\ifmem@em@starred@listof
\newcommand\KeepFromToc{\mem@em@starred@listoftrue}
%    \end{macrocode}
% Tip: use \cs{KeepFromToc} as an environment, i.e.
% \begin{verbatim}
% \begin{KeepFromToc}
%  \listoffigures 
% \end{KeepFromToc}
% \end{verbatim}
% to locally remove a list from the TOC.
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\@starttoc}
% A list of macro calls \cs{@starttoc} to read the appropriate file. I have
% changed the kernel definition to allow a file to be read multiple times
% by delaying killing the file until the end of the document.
% \changes{v1.3}{2002/11/14}{Changed \cs{@starttoc}}
% \changes{v1.61803398d}{2009/11/23}{Removed infelicity in \cs{@starttoc}}
%    \begin{macrocode}
\renewcommand{\@starttoc}[1]{%
  \begingroup\makeatletter
    \@input{\jobname.#1}%
    \if@filesw
      \AtEndDocument{%
%    \end{macrocode}
% If a ToC, or other ListOf, is called more than once then we have to stop
% opening yet another, redundant, output file. The check against \cs{relax}
% seems to meet the requirement.
%    \begin{macrocode}
        \expandafter\ifx\csname tf@#1\endcsname\relax
          \expandafter\newwrite\csname tf@#1\endcsname
          \immediate\openout \csname tf@#1\endcsname \jobname.#1\relax
        \fi
      }%
    \fi
  \@nobreakfalse
  \endgroup}

%    \end{macrocode}
% \end{macro}
%
%
% \subsection{Table of Contents}
%
% \begin{macro}{\tableofcontents}
% \begin{macro}{\tableofcontents*}
%    These macros request that \LaTeX{} produces a table of
%    contents. The ToC heading is added to the ToC unless the starred
% version is used.
%
%    \begin{macrocode}
\newlistof{tableofcontents}{toc}{\contentsname}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%    The List of Figures and List of Tables are defined later.
%
%
%
% \subsection{List entries}
%
%    Each command in the body of the text that makes an entry in the ToC,
% or LoF or LoT needs an addtional macro to format the entry, as described
% above. Users often want to change the formatting of the entries but
% it is not immediately obvious how to do that.
%
%    I have borrowed and modified more of the code from the \Lpack{tocloft}
% package to enable easy creation and modification the formatting of the
% entries.
%
%
% \begin{macro}{\setpnumwidth}
% \begin{macro}{\setrmarg}
%  User commands for setting \cs{@pnumwidth} and \cs{@tocrmarg}.
%    \begin{macrocode}
\newcommand*{\setpnumwidth}[1]{\renewcommand{\@pnumwidth}{#1}}
\newcommand*{\setrmarg}[1]{\renewcommand{\@tocrmarg}{#1}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\cftdot}
% \begin{macro}{\cftdotfill}
% In the default ToC, a dotted line can be used to provide a leader between
% a title and the page number. The definition of this leader is buried
% in the \cs{@dottedtocline} command. The \cs{cftdotfill}\marg{sep}
% command provides a parameterised version of the leader code, where
% \meta{sep} is the separation between the dots in mu units.
% The symbol used for the `dots' in the leader is given by the value
% of \cs{cftdot}. 
%    \begin{macrocode}
\providecommand{\cftdot}{.}
\providecommand{\cftdotfill}[1]{%
  \leaders\hbox{$\m@th\mkern #1 mu\hbox{\cftdot}\mkern #1 mu$}\hfill}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\cftdotsep}
% \begin{macro}{\cftnodots}
% \cs{cftdotsep} holds the default dot separation. 
% If the kerns in \cs{cftdotfill} are large enough, then no dots will
% be printed. \cs{cftnodots} should be `large enough'.
% \changes{v1.2}{2002/07/07}{Changed \cs{cftnodots} from 10,000 to 2,000 for 
%                17pt option and pdflatex}
%    \begin{macrocode}
\providecommand{\cftdotsep}{4.5}
\newcommand{\cftnodots}{2000}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%     Now for the trickier bits regarding the typesetting of the ToC
% entries.
%
%     A \file{.toc} (also \file{.lof} and \file{.lot}) file consists
% of a list of \\
% \cs{contentsline}\marg{kind}\marg{title}\marg{page} \\
% commands, where \meta{kind} is the kind of heading (e.g., \texttt{part} or
% \texttt{section} or \texttt{figure}), \meta{title} is the title text 
% (including the number),
% and \meta{page} is the page number. The entries are inserted into the
% file by calling the \\
% \cs{addcontentsline}\marg{file}\marg{kind}\marg{title} \\
% command, where \meta{file} is the file extension (e.g., \texttt{toc}, \texttt{lot})
% and the other arguments are the same as for the \cs{contentsline}
% command. (Arbitrary stuff may also be put into the file via the
% \cs{addtocontents}\marg{file}\marg{text} command).
% The typesetting of the \cs{contentsline} entries is performed by 
% commands of the form \cs{l@kind}. The sectioning and captioning commands
% call \cs{addcontentsline} to insert their titles into the \file{.toc}
% etc., files.
%
%     For the purposes at hand it is generally impossible to treat 
% the typesetting
% of a title and its number separately, as both are bundled into the
% \meta{title} argument within \cs{contentsline}. They could be handled
% separately if the \cs{contentsline} command was suitably modified. If
% this was done, then the \cs{addtocontentsline} command would also need
% to be changed which would then require the sectioning and captioning
% commands to be modified as well. This is certainly possible, but would
% cause problems if any other package also modified the sectioning or
% captioning commands, and there are several packages which do this.
%
%  I provide modified versions of the \cs{l@kind} commands. 
% Essentially, my new definitions
% consist of inlined versions of the code for \cs{@dottedtocline}.
%
%
% \begin{macro}{\cftparfillskip}
% The \cs{l@kind} commands modify (locally) the value of \cs{parfillskip}.
% \cs{cftparfillskip} is a copy of the default \theTeXbook{}
% \cs{parfillskip} definition.
%    \begin{macrocode}
\newcommand*{\cftparfillskip}{\parfillskip=0pt plus1fil}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@cftn@me}
% Lars Madsen suggested that macros like \cs{cftfigurename} be added
% to entries in the LoF, and so on.
% \changes{v1.61803}{2008/01/30}{Added \cs{@cftn@me} (Lars Madsen mempatch v4.5)}
%    \begin{macrocode}
\newcommand*{\@cftn@me}{}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\mem@cft@hb@xt@}
% \begin{macro}{\numberlinebox}
% \begin{macro}{\partnumberlinebox}
% \begin{macro}{\chapternumberlinebox}
% \begin{macro}{\booknumberlinebox}
% \changes{v3.6k}{2012/07/22}{Added four \cs{Xnumberlinebox} macros}
% Each of the four \cs{Xnumberline} macros (part, chapter, book and
% regular) typeset their contents inside a box of a certain width. In
% order to make this a little more flexible we provide a default box
% macro. Note that the box left aligned by default. The default
% \cs{Xnumberlinebox} macros are then let equal to this default.
%    \begin{macrocode}
\newcommand\mem@cft@hb@xt@[2]{\hb@xt@#1{#2\hfil}}
\let\numberlinebox\mem@cft@hb@xt@
\let\partnumberlinebox\mem@cft@hb@xt@
\let\chapternumberlinebox\mem@cft@hb@xt@
\let\booknumberlinebox\mem@cft@hb@xt@

%    \end{macrocode}
% 
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\numberline}
% \begin{macro}{\numberlinehook}
% The purpose of the \cs{numberline}\marg{secnum} command is to typeset
% \meta{secnum} left justified in a box of width \cs{@tempdima}. I redefine
% it to add three additional parameters, namely \cs{@cftbsnum}, 
% \cs{@cftasnum} and \cs{@cftasnumb} 
% (see \file{ltsect.dtx} for the original
% definition). 
% \changes{v1.61803398d}{2010/02/13}{added \cs{numberlinehook}}
% We also add a hook, that initially does nothing, but
% might be redefined to record say withs of \meta{secnum}s. In order
% to tell the owner of the \cs{numberline}'s apart, check the value of
% \cs{cftwhatismyname}. 
% \changes{v3.6k}{2012/07/22}{Factored out the box part into a
% separate macro}
%    \begin{macrocode}
\newcommand*\numberlinehook[1]{}
\renewcommand*{\numberline}[1]{%
  \numberlinehook{#1}%
  %\hb@xt@\@tempdima{\@cftn@me\@cftbsnum #1\@cftasnum\hfil}\@cftasnumb}
  \numberlinebox\@tempdima{\@cftn@me\@cftbsnum #1\@cftasnum}\@cftasnumb}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@cftbsnum}
% \begin{macro}{\@cftasnum}
% \begin{macro}{\@cftasnumb}
%    \begin{macrocode}
\newcommand{\@cftbsnum}{}
\newcommand{\@cftasnum}{}
\newcommand{\@cftasnumb}{}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\setcftvspacecmd}
% \begin{macro}{\mem@cft@vspace@cmd}
%   The entries in the ToC adds \cs{cftbeforeXskip} above each
%   entry. Traditionally the class have always used \cs{vskip}
%   here,\footnote{We do not know why.} whereas the standard classes
%   used \cs{addvspace}. It has only been 20 years (2025) before a
%   user complained that fx the space above the first entry does not
%   disappear. Since changing the \cs{vskip} to \cs{addvspace} will
%   change thousands of documents, we instead make it configurable,
%   then the user can choose what suits them best.
% \changes{v3.8.3}{2025/03/03}{Added \cs{setcftvspacecmd}}
%    \begin{macrocode}
\newcommand\setcftvspacecmd[1]{\def\mem@cft@vspace@cmd{#1}}
\setcftvspacecmd{\vskip}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% 
%
% \begin{macro}{\newlistentry}
% \cs{newlistentry}\oarg{within}\marg{counter}\marg{ext}\marg{level-1}
% creates a set of commands for typesetting a new kind of entry in a List of.
% \meta{counter} is the name of the counter for the entry and must be 
% the same as the name
% of the entry (e.g., \texttt{subsection}). The optional \meta{within} is the
% name of a counter within which \texttt{counter} is defined. The file extension
% for the List of is \meta{ext} and \meta{level-1} is one less than the 
% level of the entry in the List of.
% \changes{v1.61803}{2008/01/30}{Added \cs{cftXname} to \cs{newlistentry}
%                (mempatch v4.5)}
% \changes{v1.61803398}{2009/07/17}{Added bidi support to \cs{newlistentry}}
%    \begin{macrocode}
\newcommand{\newlistentry}[4][\@empty]{%
%    \end{macrocode}
%
%    In the following, \texttt{X} is used as the value of \meta{counter} and
% \texttt{Z} as the value of \meta{ext}.
%
% \begin{macro}{\c@X}
% \begin{macro}{\theX}
% Check if \meta{within} and \meta{counter} have been defined. It is
% an error if \meta{within} has not been defined. \meta{counter}
% will be created if it has not been previously defined.
% Set the default counter values.
%    \begin{macrocode}
  \@ifundefined{c@#2}{%    check & set the counter
    \ifx \@empty#1\relax
      \newcounter{#2}
    \else
      \newcounter{#2}[#1]%
      \expandafter\edef\csname the#2\endcsname{%
  \expandafter\noexpand\csname the#1\endcsname.\noexpand\arabic{#2}}
    \fi}{}
  \setcounter{#2}{0}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% That finishes off the error checking. No matter what the result, the
% rest of the new commands are defined.
%
% \begin{macro}{\l@X}
% \cs{l@X}\marg{title}\marg{page} typesets the entry.
%    \begin{macrocode}
  \@namedef{l@#2}##1##2{%
%    \end{macrocode}
% Only typeset if the \cs{Zdepth} is greater than \meta{level-1}.
%    \begin{macrocode}
    \ifnum \@nameuse{c@#3depth} > #4\relax
%    \end{macrocode}
% Add some vertical space.
% \changes{v3.8.3}{2025/03/03}{factoring the vertical space cmd}
% \changes{v3.8.3b}{2025/03/10}{This contained a bug, better to not use \cs{@nameuse}}
%    \begin{macrocode}
      % \vskip \@nameuse{cftbefore#2skip}
      % \mem@cft@vspace@cmd \@nameuse{cftbefore#2skip}
      \ExpandArgs{c}\mem@cft@vspace@cmd{cftbefore#2skip}
%    \end{macrocode}
% Start a group to keep paragraphing changes local. Set the \cs{leftskip}
% to the entry's indentation.
% \begin{macro}{\cftwhatismyname}
% \changes{v1.61803398d}{2010/02/13}{added \cs{cftwhatismyname}}
% \cs{cftwhatismyname} locally stores the type of toc entry. Useful
% for hooks into general macros like \verb?\numberline?.
%    \begin{macrocode}
      {%\leftskip \@nameuse{cft#2indent}\relax
       \newcommand*\cftwhatismyname{#2}% 
       \memRTLleftskip \@nameuse{cft#2indent}\relax
%    \end{macrocode}
% \end{macro}
% Set the \cs{rightskip} to \cs{@tocrmarg} to leave room for the page number.
%    \begin{macrocode}
%%%       \rightskip \@tocrmarg
       \memRTLrightskip \@tocrmarg
%    \end{macrocode}
% Ensure that the last line of an entry will be filled. Setting \cs{parfillskip}
% to a negative value prevents `overfull box' messages.
%    \begin{macrocode}
%%%       \parfillskip -\rightskip
       \parfillskip -\memRTLrightskip
%    \end{macrocode}
% Set the paragraph's indentation to the entry's indentation.
%    \begin{macrocode}
       \parindent \@nameuse{cft#2indent}\relax\@afterindenttrue
%    \end{macrocode}
% Try and prevent breaks between lines in a multiline entry.
%    \begin{macrocode}
       \interlinepenalty\@M
%    \end{macrocode}
% Make sure we have left vertical mode.
%    \begin{macrocode}
       \leavevmode
%    \end{macrocode}
% Our version of \cs{numberline} expects that the width of the number box
% is in \cs{@tempdima}, and that the three macros \cs{@cftbsnum}, 
% \cs{@cftaqsnum}, and \cs{@cftasnumb} are defined. We set all these to 
% the values for this entry.
% \changes{v3.6k}{2012/07/30}{Added brace pair around 
% \cs{nameuse\{cft#2name\}}, then
% \cs{cftXfont} can end with say \cs{MakeUppercase}}
%    \begin{macrocode}
       \settowidth{\@tempdima}{\@nameuse{cft#2font}{\@nameuse{cft#2name}}}%
       \addtolength{\@tempdima}{\@nameuse{cft#2numwidth}}%
 \expandafter\let\expandafter\@cftbsnum\csname cft#2presnum\endcsname
 \expandafter\let\expandafter\@cftasnum\csname cft#2aftersnum\endcsname
 \expandafter\let\expandafter\@cftasnumb\csname cft#2aftersnumb\endcsname
 \expandafter\let\expandafter\@cftn@me\csname cft#2name\endcsname
%    \end{macrocode}
% Arrange that the (entry number and) first line of the title is set at
% the current indent, and that any subsequent lines will be further
% indented.
%    \begin{macrocode}
%%%       \advance\leftskip\@tempdima \null\nobreak\hskip -\leftskip
       \advance\memRTLleftskip\@tempdima \null\nobreak\hskip -\memRTLleftskip
%    \end{macrocode}
% Print the (number and) title, prohibiting any breaking.
% \changes{v3.6k}{2012/07/29}{Added brace pair around \#\#1, then
% \cs{cftXfont} can end with say \cs{MakeUppercase}}
%    \begin{macrocode}
       {\@nameuse{cft#2font}{##1}}\nobreak
%    \end{macrocode}
% Print the leader and the page number, and then close the group.
%    \begin{macrocode}
       \@nameuse{cft#2fillnum}{##2}}
    \fi
  }% end of \l@#2

%    \end{macrocode}
% \end{macro}
%
% Now define all the layout commands used by \cs{l@X}. The default
% values of these print the entry in a normal font with a dotted
% line between the title and the page number.
% \begin{macro}{\cftbeforeXskip}
% The skip before the title.
%    \begin{macrocode}
  \expandafter\newlength\csname cftbefore#2skip\endcsname
    \setlength{\@nameuse{cftbefore#2skip}}{\z@ \@plus .2\p@}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\cftXindent}
% \begin{macro}{\cftXnumwidth}
% The indent and width for the number.
%    \begin{macrocode}
  \expandafter\newlength\csname cft#2indent\endcsname
  \expandafter\newlength\csname cft#2numwidth\endcsname
%    \end{macrocode}
% Set the default values for the indent and numwidth depending on
% the entry's level. A level of 1 corresponds to a figure entry
% (no indent, and space for a number like N.N).
%    \begin{macrocode}
  \ifcase #4\relax  % 0   (level 1)
    \setlength{\@nameuse{cft#2indent}}{0em}
    \setlength{\@nameuse{cft#2numwidth}}{2.3em}
  \or               % 1   (level 2)
    \setlength{\@nameuse{cft#2indent}}{2.3em}
    \setlength{\@nameuse{cft#2numwidth}}{3.2em}
  \or               % 2   (level 3)
    \setlength{\@nameuse{cft#2indent}}{5.5em}
    \setlength{\@nameuse{cft#2numwidth}}{4.1em}
  \or               % 3   (level 4)
    \setlength{\@nameuse{cft#2indent}}{8.5em}
    \setlength{\@nameuse{cft#2numwidth}}{5.0em}
  \else             % anything else
    \setlength{\@nameuse{cft#2indent}}{10.5em}
    \setlength{\@nameuse{cft#2numwidth}}{6.0em}
  \fi
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \begin{macro}{\cftXfont}
% \begin{macro}{\cftXname}
% \begin{macro}{\cftXpresnum}
% \begin{macro}{\cftXaftersnum}
% \begin{macro}{\cftXaftersnumb}
% \begin{macro}{\cftXdotsep}
% \begin{macro}{\cftXleader}
% \begin{macro}{\cftXpagefont}
% \begin{macro}{\cftXafterpnum}
% And the remaining commands; the only ones that are not null are for the
% dotsep, the font and the leader
%    \begin{macrocode}
  \@namedef{cft#2font}{\normalfont}
  \@namedef{cft#2name}{}
  \@namedef{cft#2presnum}{}
  \@namedef{cft#2aftersnum}{}
  \@namedef{cft#2aftersnumb}{}
  \@namedef{cft#2dotsep}{\cftdotsep}
  \@namedef{cft#2leader}{\normalfont\cftdotfill{\@nameuse{cft#2dotsep}}}
  \@namedef{cft#2pagefont}{\normalfont}
  \@namedef{cft#2afterpnum}{}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\toclevel@X}
% The hyperref package needs a command \cs{toclevel@X}, holding
% the \meta{level-1} value.
%    \begin{macrocode}
  \@namedef{toclevel@#2}{#4}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\cftXformatpnum}
% \begin{macro}{\cftXformatpnumhook}
% \begin{macro}{\cftXfillnum}
% Typeset the leader and page number. We add a hook into the formating
% of the page number. This might later be used to record the widths of
% the numbers used. It will be given the page number as its
% argument. Does nothing by default.
% \changes{v1.61803}{2008/01/30}{Added \cs{cftXformatpnum} (Dan Leucking
%                   mempatch v4.9)}
% \changes{v1.61803398d}{2010/02/13}{added hook into page number formatter}
%    \begin{macrocode}
  \@namedef{cft#2formatpnumhook}##1{}
  \@namedef{cft#2formatpnum}##1{%
    \@nameuse{cft#2formatpnumhook}{##1}%
    \hb@xt@\@pnumwidth{\hfil\@nameuse{cft#2pagefont}##1}}
  \@namedef{cft#2fillnum}##1{%
    {\@nameuse{cft#2leader}}\nobreak
%%%    \hb@xt@\@pnumwidth{%
%%%      \hfil\@nameuse{cft#2pagefont}##1}
       \@nameuse{cft#2formatpnum}{##1}%
       \@nameuse{cft#2afterpnum}\par}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% This ends the definition of \cs{newlistentry}.
%    \begin{macrocode}
} % end \newlistentry

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\cftsetindents}
% \cs{cftsetindents}\marg{entry}\marg{indent}\marg{numwidth} sets
% the \textit{indent} and \textit{numwidth} for entry \meta{entry}. 
%    \begin{macrocode}
\newcommand*{\cftsetindents}[3]{%
  \setlength{\@nameuse{cft#1indent}}{#2}
  \setlength{\@nameuse{cft#1numwidth}}{#3}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\cftbookname}
% If you want a book entry in the ToC like: \\
% BOOK I Title ... \\
% then \verb?\renewcommand*{\cftbookname}{BOOK~}? \\
%    \begin{macrocode}
\newcommand*{\cftbookname}{}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\cftbookbreak}
% \begin{macro}{\l@book}
% \begin{macro}{\booknumberline}
% \begin{macro}{\booknumberlinehook}
% Now for the ToC entry.
% \changes{v1.61803}{2008/01/30}{Added \cs{l@book} and supports (mempatch v4.4)}
% \changes{v1.6180339}{2008/07/23}{Deleted \cs{space} from \cs{booknumberline}
%                      and \cs{partnumberline}
%                      (per Lars Henrik Gam Madsen mempatch v5.1)}
% \changes{v1.61803398}{2009/07/18}{Added bidi support to \cs{l@book}}
% \changes{v1.61803398d}{2010/02/13}{added hook into the book numberline}
% \changes{v3.6k}{2012/07/22}{Factored the general box out of \cs{booknumberline}}
% \changes{v3.8.3}{2025/03/06}{Factored out the penalty}
% \changes{v3.8.4}{2025/08/15}{Fixed typo, need \cs{cftbeforebookpenalty} not \cs{cftbeforepartpenalty}, even if they have the same value }
%    \begin{macrocode}
\newcommand*{\cftbookbreak}{%
  \addpenalty{\cftbeforebookpenalty}%
  \addvspace{\cftbeforebookskip}%
}
\newcommand*{\l@book}[2]{%
  \ifnum\c@tocdepth >-3\relax
    \cftbookbreak
    \begingroup
      {%\leftskip \cftbookindent\relax
       \memRTLleftskip \cftbookindent\relax
%%%       \rightskip \@tocrmarg
       \memRTLrightskip \@tocrmarg
%%%       \parfillskip -\rightskip
       \parfillskip -\memRTLrightskip
       \parindent \cftbookindent\relax\@afterindenttrue
       \interlinepenalty\@M
       \leavevmode
       \settowidth{\@tempdima}{\cftbookfont\cftbookname}%
       \addtolength{\@tempdima}{\cftbooknumwidth}%
       \let\@cftbsnum \cftbookpresnum
       \let\@cftasnum \cftbookaftersnum
       \let\@cftasnumb \cftbookaftersnumb
%%%       \advance\leftskip \@tempdima \null\nobreak\hskip -\leftskip
       \advance\memRTLleftskip \@tempdima \null\nobreak\hskip -\memRTLleftskip
%    \end{macrocode}
% \changes{v3.6k}{2012/07/29}{Added brace pair around \#1, then
% \cs{cftbookfont} can end with say \cs{MakeUppercase}}
%    \begin{macrocode}
       {\cftbookfont {#1}}%
       \cftbookfillnum{#2}}
      \nobreak
      \global\@nobreaktrue
      \everypar{\global\@nobreakfalse\everypar{}}%
    \endgroup
  \fi}
\newcommand*\booknumberlinehook[1]{}
\newcommand{\booknumberline}[1]{%
  \booknumberlinehook{#1}%
  % \hb@xt@\@tempdima{%
  %   \cftbookname\@cftbsnum #1\@cftasnum\hfil}\@cftasnumb}%%\space}
  \booknumberlinebox\@tempdima{%
    \cftbookname\@cftbsnum #1\@cftasnum}\@cftasnumb}%%\space}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \newpage
%
% \begin{macro}{\cftbeforebookskip}
% \begin{macro}{\cftbeforebookpenalty}
% \begin{macro}{\cftbookindent}
% \begin{macro}{\cftbooknumwidth}
% \begin{macro}{\cftbookfont}
% \begin{macro}{\cftbookpresnum}
% \begin{macro}{\cftbookaftersnum}
% \begin{macro}{\cftbookaftersnumb}
% \begin{macro}{\cftbookleader}
% \begin{macro}{\cftbookdotsep}
% \begin{macro}{\cftbookpagefont}
% \begin{macro}{\cftbookafterpnum}
% \begin{macro}{\cftbookfillnum}
% \begin{macro}{\cftbookformatpnum}
% \begin{macro}{\cftbookformatpnumhook}
% \changes{v1.61803398d}{2010/02/13}{added hook into \cs{cftbookformatpnum}}
% \changes{v3.8.3}{2025/03/06}{added \cs{cftbeforebookpenalty}}
%    \begin{macrocode}
\newlength{\cftbeforebookskip}
  \setlength{\cftbeforebookskip}{2.25em \@plus\p@}
\newcommand\cftbeforebookpenalty{-\@highpenalty}
\newdimen\cftbookindent
  \setlength{\cftbookindent}{0em}
\newdimen\cftbooknumwidth
  \setlength{\cftbooknumwidth}{1.5em}
\newcommand*{\cftbookfont}{\large\bfseries}
\newcommand*{\cftbookpresnum}{}
\newcommand*{\cftbookaftersnum}{}
\newcommand*{\cftbookaftersnumb}{}
\newcommand*{\cftbookleader}{%
  \large\bfseries\cftdotfill{\cftbookdotsep}}
\newcommand*{\cftbookdotsep}{\cftnodots}
\newcommand*{\cftbookpagefont}{\large\bfseries}
\newcommand{\cftbookafterpnum}{}
\newcommand{\cftbookfillnum}[1]{%
  {\cftbookleader}%
%%%%  {\hb@xt@\@pnumwidth{\hss {\cftbookpagefont #1}}}%
  \cftbookformatpnum{#1}%
  \cftbookafterpnum\par}
\newcommand{\cftbookformatpnumhook}[1]{}
\newcommand{\cftbookformatpnum}[1]{%
  \cftbookformatpnumhook{#1}%
  \hb@xt@\@pnumwidth{\hss {\cftbookpagefont #1}}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
%
% \begin{macro}{\cftpartname}
% If you want a part entry in the ToC like: \\
% PART I Title ... \\
% then \verb?\renewcommand*{\cftpartname}{PART~}? \\
% \changes{v1.618}{2005/09/03}{Added \cs{cftpartname}, courtesy Danie Els (mempatch v3.12)}
%    \begin{macrocode}
\newcommand*{\cftpartname}{}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\cftpartbreak}
% \begin{macro}{\l@part}
% Can't use \cs{newlistentry} for \cs{l@part} because of the initial penalty
% and the final \cs{nobreak} code.
% \changes{v1.61803}{2008/01/30}{Added \cs{cftpartbreak}}
% \changes{v1.61803398}{2009/07/18}{Added bidi support to \cs{l@part}}
% \changes{v3.8.3}{2025/03/06}{Factored out the penalty part}
%    \begin{macrocode}
\newcommand*{\cftpartbreak}{%
  \addpenalty{\cftbeforepartpenalty}%
  \addvspace{\cftbeforepartskip}%
}
\newcommand*{\l@part}[2]{%
  \ifnum \c@tocdepth >-2\relax
    \cftpartbreak
    \begingroup
      {%\leftskip \cftpartindent\relax
       \memRTLleftskip \cftpartindent\relax
%%%       \rightskip \@tocrmarg
       \memRTLrightskip \@tocrmarg
%%%       \parfillskip -\rightskip
       \parfillskip -\memRTLrightskip
       \parindent \cftpartindent\relax\@afterindenttrue
       \interlinepenalty\@M
       \leavevmode    
       \settowidth{\@tempdima}{\cftpartfont\cftpartname}%
       \addtolength{\@tempdima}{\cftpartnumwidth}%
       \let\@cftbsnum \cftpartpresnum
       \let\@cftasnum \cftpartaftersnum
       \let\@cftasnumb \cftpartaftersnumb
%%%       \advance\leftskip \@tempdima \null\nobreak\hskip -\leftskip
       \advance\memRTLleftskip \@tempdima \null\nobreak\hskip -\memRTLleftskip
%    \end{macrocode}
% \changes{v3.6k}{2012/07/29}{Added brace pair around \#1, then
% \cs{cftpartkfont} can end with say \cs{MakeUppercase}}
%    \begin{macrocode}
       {\cftpartfont {#1}}%
       \cftpartfillnum{#2}}
      \nobreak
        \global\@nobreaktrue
        \everypar{\global\@nobreakfalse\everypar{}}%
    \endgroup
  \fi}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\toclevel@part}
% Needed if the \Lpack{hyperref} package is used.
% \changes{v1.61803}{2008/01/30}{Added \cs{toclevel@part} (mempatch v4.9)}
% \changes{v3.7.19}{2022/10/25}{Changing \cs{toclevel@part} definition to
% \cs{def} for better compability with future hyperref}
%    \begin{macrocode}
\def\toclevel@part{-1}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\partnumberline}
% \begin{macro}{\partnumberlinehook}
% \cs{partnumberline} is a special version of \cs{numberline} output by \cs{part}.
% Its default definition is identical to \cs{numberline}.
% \changes{v1.3}{2002/11/14}{Added \cs{partnumberline}}
% \changes{v1.61803}{2008/01/30}{Added a space after the number in 
%         \cs{partnumberline} (mempatch v4.4)}
% \changes{v1.61803398d}{2010/02/13}{added hook into part numberline}
% \changes{v3.6k}{2012/07/22}{Factored out the box command}
%    \begin{macrocode}
\newcommand*\partnumberlinehook[1]{}
\newcommand{\partnumberline}[1]{%
  \partnumberlinehook{#1}%
  % \hb@xt@\@tempdima{%
  %   \cftpartname\@cftbsnum #1\@cftasnum\hfil}\@cftasnumb}%%\space}
  \partnumberlinebox\@tempdima{%
    \cftpartname\@cftbsnum #1\@cftasnum}\@cftasnumb}%%\space}


%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\cftbeforepartskip}
% \begin{macro}{\cftbeforepartpenalty}
% \begin{macro}{\cftpartnumwidth}
% \begin{macro}{\cftpartfont}
% \begin{macro}{\cftpartpresnum}
% \begin{macro}{\cftpartaftersnum}
% \begin{macro}{\cftpartaftersnumb}
% \begin{macro}{\cftpartleader}
% \begin{macro}{\cftpartdotsep}
% \begin{macro}{\cftpartpagefont}
% \begin{macro}{\cftpartafterpnum}
% \begin{macro}{\cftpartindent}
% \begin{macro}{\cftpartformatpnum}
% \begin{macro}{\cftpartformatpnumhook}
% \begin{macro}{\cftpartfillnum}
%  These are the user commands to control the typesetting of Part entries.
%  They are initialised to give the standard appearance.
% \changes{v1.3}{2002/10/10}{Changed \cs{cftpartnumwidth} to cater for
%                            use of \cs{numberline} in the ToC}
% \changes{v1.61803}{2008/01/30}{Added \cs{cftpartformatpnum} (mempatch v4.9)}
% \changes{v1.61803398d}{2010/02/13}{added hook into \cs{cftpartformatpnum}}
% \changes{v3.8.3}{2025/03/06}{Added \cs{cftbeforepartpenalty}}
%    \begin{macrocode}
  \newlength{\cftbeforepartskip}
    \setlength{\cftbeforepartskip}{2.25em \@plus\p@}
  \newcommand\cftbeforepartpenalty{-\@highpenalty}
  \newlength{\cftpartindent}
    \setlength{\cftpartindent}{0em}
  \newlength{\cftpartnumwidth}
    \setlength{\cftpartnumwidth}{1.5em}
  \newcommand{\cftpartfont}{\large\bfseries}
  \newcommand{\cftpartpresnum}{}
  \newcommand{\cftpartaftersnum}{}
  \newcommand{\cftpartaftersnumb}{}
  \newcommand{\cftpartleader}{%
              \large\bfseries\cftdotfill{\cftpartdotsep}}
  \newcommand{\cftpartdotsep}{\cftnodots}
  \newcommand{\cftpartpagefont}{\large\bfseries}
  \newcommand{\cftpartafterpnum}{}
  \newcommand{\cftpartformatpnumhook}[1]{}
  \newcommand*{\cftpartformatpnum}[1]{%
    \cftpartformatpnumhook{#1}%
    \hb@xt@\@pnumwidth{\hss {\cftpartpagefont #1}}}
  \newcommand{\cftpartfillnum}[1]{%
    {\cftpartleader}%
    {\cftpartformatpnum{#1}}%
     \cftpartafterpnum\par}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\cftchaptername}
% If you want a chapter entry in the ToC like: \\
% Chapter 1. A title ... \\
% then \verb?\renewcommand*{\cftchaptername}{\chaptername~}? \\
% \verb?\renewcommand*{\cftchapteraftersnum}{.}? \\
% 
% \changes{v1.618}{2005/09/03}{Added \cs{cftchaptername}, courtesy Danie Els (mempatch v3.12)}
%    \begin{macrocode}
\newcommand*{\cftchaptername}{}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\l@chapapp}
% Generic chapter/appendix ToC entry typesetting.
% \changes{v1.3}{2002/11/14}{Added \cs{cftchapterbreak} to
% \cs{l@chapter} (Peter probably meant \cs{l@chapapp} here, and thus
% the remark was moved here, /dlf 2025/03/03)}
% \changes{v1.618}{2005/09/03}{Added \cs{l@chapapp}, courtesy Danie Els (mempatch v3.12)}
% \changes{v1.61803398}{2009/07/18}{Added bidi support to \cs{l@chapapp}}
%     \begin{macrocode}
\newcommand*{\l@chapapp}[3]{%
  \ifnum \c@tocdepth >\m@ne
%    \end{macrocode}
% 2025/03/03: Factored the vertical skip part into \cs{cftchapterbreak} to mimic \cs{part} and \cs{book}
%    \begin{macrocode}
    \cftchapterbreak
    % \vskip \cftbeforechapterskip
    {%\leftskip \cftchapterindent\relax
     \memRTLleftskip \cftchapterindent\relax
%%%     \rightskip \@tocrmarg
     \memRTLrightskip \@tocrmarg
%%%     \parfillskip -\rightskip
     \parfillskip -\memRTLrightskip
     \parindent \cftchapterindent\relax
     \@afterindenttrue
     \interlinepenalty\@M
     \leavevmode
     \let\@cftbsnum \cftchapterpresnum
     \let\@cftasnum \cftchapteraftersnum
     \let\@cftasnumb \cftchapteraftersnumb
     \def\@chapapp@head{#3}%
     \settowidth{\@tempdima}{\cftchapterfont\@chapapp@head}%
     \addtolength{\@tempdima}{\cftchapternumwidth}%
%%%     \advance\leftskip \@tempdima \null\nobreak\hskip -\leftskip
     \advance\memRTLleftskip \@tempdima \null\nobreak\hskip -\memRTLleftskip
%    \end{macrocode}
% \changes{v3.6k}{2012/07/29}{Added brace pair around \#1, then
% \cs{cftchapterfont} can end with say \cs{MakeUppercase}}
%    \begin{macrocode}
     {\cftchapterfont {#1}}\nobreak
     \cftchapterfillnum{#2}}
  \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\l@chapter}
%  \cs{l@chapter}\marg{title}\marg{page} typesets the ToC entry for
% a \texttt{chapter} heading. It is a parameterised copy of the default 
% \cs{l@chapter}
% (see \file{classes.dtx} for the original definition). Can't use
% \cs{newlistentry} for this because of the intial penalty.
% \changes{v1.618}{2005/09/03}{Defined \cs{l@chapter} in terms of \cs{l@chapapp} (mempatch v3.12)}
%    \begin{macrocode}
\newcommand*{\l@chapter}[2]{%
  \l@chapapp{#1}{#2}{\cftchaptername}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\toclevel@chapter}
% Needed if the \Lpack{hyperref} package is used.
% \changes{v1.61803}{2008/01/30}{Added \cs{toclevel@chapter} (mempatch v4.9)}
% \changes{v3.7.19}{2022/10/25}{Changing \cs{toclevel@chapter} definitions to
% \cs{def} for better compability with future hyperref}
%    \begin{macrocode}
\def\toclevel@chapter{0}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\cftappendixname}
% If you want a appendixed chapter entry in the ToC like: \\
% Appendix A A title ... \\
% then \verb?\renewcommand*{\cftappendixname}{\appendixname~}? \\
% 
% \changes{v1.618}{2005/09/03}{Added \cs{cftappendixname}, courtesy Danie Els (mempatch v3.12)}
%    \begin{macrocode}
\newcommand*{\cftappendixname}{}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\l@appendix}
% \begin{macro}{\toclevel@appendix}
% Similar to \cs{l@chapter} but for an appendix.
% \changes{v1.618}{2005/09/03}{Added \cs{l@apendix} (mempatch v3.12)}
% \changes{v3.7.19}{2022/10/25}{Changing \cs{toclevel@appendix} definitions to
% \cs{def} for better compability with future hyperref}
%    \begin{macrocode}
\newcommand*{\l@appendix}[2]{%
  \l@chapapp{#1}{#2}{\cftappendixname}}
\def\toclevel@appendix{0}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\chapternumberline}
% \begin{macro}{\chapternumberlinehook}
% \cs{chapternumberline} is a special version of \cs{numberline} output by 
% \cs{chapter}.
% It's default definition is identical to \cs{numberline}.
% \changes{v1.3}{2002/11/14}{Added \cs{chapternumberline}}
% \changes{v1.618}{2005/09/03}{Added \cs{@chapapp@head} to \cs{chapternumberline} (mempatch v3.12)}
% \changes{v1.61803398d}{2010/02/13}{added hook into chapter numberline}
% \changes{v3.6k}{2012/07/22}{Factored out the box command}
%    \begin{macrocode}
\newcommand*\chapternumberlinehook[1]{}
\newcommand{\chapternumberline}[1]{%
  \chapternumberlinehook{#1}%
  % \hb@xt@\@tempdima{\@chapapp@head\@cftbsnum #1\@cftasnum\hfil}%
  % \@cftasnumb}
  \chapternumberlinebox\@tempdima{\@chapapp@head\@cftbsnum #1\@cftasnum}%
  \@cftasnumb}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\cftbeforechapterskip}
% \begin{macro}{\cftbeforechapterpenalty}
% \begin{macro}{\cftchapterindent}
% \begin{macro}{\cftchapternumwidth}
% \begin{macro}{\cftchapterfont}
% \begin{macro}{\cftchapterpresnum}
% \begin{macro}{\cftchapteraftersnum}
% \begin{macro}{\cftchapteraftersnumb}
% \begin{macro}{\cftchapterleader}
% \begin{macro}{\cftchapterdotsep}
% \begin{macro}{\cftchapterpagefont}
% \begin{macro}{\cftchapterafterpnum}
% \begin{macro}{\cftchapterformatpnum}
% \begin{macro}{\cftchapterformatpnumhook}
% \begin{macro}{\cftchapterfillnum}
%  These are the user commands to control the typesetting of Chapter entries.
%  They are initialised to give the standard appearance.
% \changes{v1.61803}{2008/01/30}{Added \cs{cftchapterformatpnum} (mempatch v4.9)}
% \changes{v1.61803398d}{2010/02/13}{added hook into \cs{cftchapterformatpnum}}
% \changes{v3.8.3}{2025/03/06}{Added \cs{cftbeforechapterpenalty}}
%    \begin{macrocode}
  \newlength{\cftbeforechapterskip}
    \setlength{\cftbeforechapterskip}{1.0em \@plus\p@}
  \newcommand\cftbeforechapterpenalty{-\@highpenalty}
  \newlength{\cftchapterindent}
    \setlength{\cftchapterindent}{0em}
  \newlength{\cftchapternumwidth}
    \setlength{\cftchapternumwidth}{1.5em}
  \newcommand{\cftchapterfont}{\bfseries}
  \newcommand{\cftchapterpresnum}{}
  \newcommand{\cftchapteraftersnum}{}
  \newcommand{\cftchapteraftersnumb}{}
  \newcommand{\cftchapterleader}{%
              \bfseries\cftdotfill{\cftchapterdotsep}}
  \newcommand{\cftchapterdotsep}{\cftnodots}
  \newcommand{\cftchapterpagefont}{\bfseries}
  \newcommand{\cftchapterafterpnum}{}
  \newcommand{\cftchapterformatpnumhook}[1]{}
  \newcommand*{\cftchapterformatpnum}[1]{%
    \cftchapterformatpnumhook{#1}%
    \hb@xt@\@pnumwidth{\hfil\cftchapterpagefont #1}}
  \newcommand*{\cftchapterfillnum}[1]{%
    {\cftchapterleader}\nobreak
    \cftchapterformatpnum{#1}%
    \cftchapterafterpnum\par}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\cftchapterbreak}
% Another parameter for \cs{l@chapter}.
% \changes{v1.3}{2002/11/14}{Added \cs{cftchapterbreak}}
% \changes{v3.8.3}{2025/03/03}{Moved the vertical skip part into \cs{cftchapterbreak}}
% \changes{v3.8.3}{2025/03/06}{Factored the penalty into its own macro}
%    \begin{macrocode}
\newcommand{\cftchapterbreak}{%
  \addpenalty{\cftbeforechapterpenalty}%
  \mem@cft@vspace@cmd \cftbeforechapterskip%
}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\l@section}
% \begin{macro}{\l@subsection}
% \begin{macro}{\l@subsubsection}
% \begin{macro}{\l@paragraph}
% \begin{macro}{\l@subparagraph}
%  \cs{l@section}\marg{title}\marg{page} typesets the ToC entry for
% a \cs{section} heading. Similarly \cs{l@subsection} and \cs{l@subsubsection}
% for \cs{subsection} and \cs{subsubsection} entries, and so on.
% \changes{v1.4}{2003/11/22}{Used \cs{newlistentry} for pararaph and 
%                             subparagraph (from patch v1.7)}
% \changes{v1.618}{2005/09/02}{Corrected (sub)paragraph ToC indents (mempatch v2.3)}
%    \begin{macrocode}
\newlistentry[chapter]{section}{toc}{0}
  \cftsetindents{section}{1.5em}{2.3em}
\newlistentry[section]{subsection}{toc}{1}
  \cftsetindents{subsection}{3.8em}{3.2em}
\newlistentry[subsection]{subsubsection}{toc}{2}
  \cftsetindents{subsubsection}{7.0em}{4.1em}
\newlistentry[subsubsection]{paragraph}{toc}{3}
  \cftsetindents{paragraph}{10.0em}{5.0em}
\newlistentry[paragraph]{subparagraph}{toc}{4}
  \cftsetindents{subparagraph}{12.0em}{6.0em}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%   The typesetting for Figures and Tables is defined later.
%
%
%
% \subsection{Support for the \Lpack{subfigure} package}
%
%  The code for supporting the \Lpack{subfigure} package is, in all 
% essentials, the same as that for the figure and table captions; only the
% names are changed. However, the code need only be executed if the
% \Lpack{subfigure} package is actually loaded. 
%
% \begin{macro}{\@cftl@subfigtab}
%    This command redefines the \cs{l@subfigure} and \cs{l@subtable} commands. 
% \changes{v1.61803}{2008/01/30}{Made \cs{@cftl@subfigtab} a no-op (mempatch v4.6)}
%    \begin{macrocode}
\newcommand*{\@cftl@subfigtab}{
%    \end{macrocode}
% \begin{macro}{\l@subfigure}
% \begin{macro}{\l@subtable}
%  \cs{l@subfigure}\marg{title}\marg{page} typesets the LoF entry for
% a subfigure caption heading, and \cs{l@subtable} does the same for subtables.
%    \begin{macrocode}
\newlistentry[figure]{subfigure}{lof}{1}
  \cftsetindents{subfigure}{2.3em}{2.5em}
\newlistentry[table]{subtable}{lot}{1}
  \cftsetindents{subtable}{2.3em}{2.5em}}
\renewcommand*{\@cftl@subfigtab}{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
%    Call the \Lpack{subfigure} package setup code only if the 
% \Lopt{subfigure} package has been used.
%    \begin{macrocode}
\AtBeginDocument{\@ifpackageloaded{subfigure}{\@cftl@subfigtab}{}}

%    \end{macrocode}
%
%
% \subsection{Switching page numbering}
%
%    It can, at times, be useful to be able to have ToC entries that have
% no printed page numbers.
%
% \begin{macro}{\cftpagenumbersoff}
% The user level command for switching off page numbers is 
% \cs{cftpagenumbersoff}\marg{entry} where \meta{entry} is the 
% name of the entry. 
% The macro redefines the \cs{cftXfillnum} command so that there is no leader
% and the page number is ignored.
%    \begin{macrocode}
\DeclareRobustCommand{\cftpagenumbersoff}[1]{%
  \@namedef{cft#1fillnum}##1{%
    \cftparfillskip\@nameuse{cft#1afterpnum}\par}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\cftpagenumberson}
% \cs{cftpagenumberson}\marg{entry} is the user level command for 
% reversing the corresponding \cs{cftpagenumbersoff}.
% The macro defines the \cs{cftXfillnum} command to correspond to 
% the default definition.
% \changes{v1.61803}{2008/01/30}{Modified \cs{cftpagenumberson} to use \cs{cftXformatpnum} 
%                   (mempatch v4.9)}
%    \begin{macrocode}
\DeclareRobustCommand{\cftpagenumberson}[1]{%
  \@namedef{cft#1fillnum}##1{%
    \@nameuse{cft#1leader}\nobreak
    \@nameuse{cft#1formatpnum}{##1}%
    \@nameuse{cft#1afterpnum}\par}}

%    \end{macrocode}
% \end{macro}
%
%
% \subsection{Chapter precis}
%
% \begin{macro}{\chapterprecis}
% The command \cs{chapterprecis}\marg{text} typesets
% \meta{text} at the point where it is called, and also adds \meta{text}
% to the \file{.toc} file. It is expects to be called immediately after
% a \cs{chapter} command.
%    \begin{macrocode}
\newcommand{\chapterprecis}[1]{%
  \chapterprecishere{#1}
  \chapterprecistoc{#1}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chapterprecishere}
% \cs{chapterprecishere}\marg{text} typesets \meta{text}. It expects
% to be called immediately after a \cs{chapter} command. 
% \changes{v1.3}{2002/11/14}{Parameterised \cs{chapterprecishere}}
%    \begin{macrocode}
\newcommand{\chapterprecishere}[1]{%
  \prechapterprecis #1\postchapterprecis}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\prechapterprecis}
% \begin{macro}{\prechapterprecisshift}
% \begin{macro}{\precisfont}
% \begin{macro}{\postchapterprecis}
% The \cs{pre...} and \cs{post...} macros put code before and after 
% \cs{chapterprecishere} text. By
% default \cs{prechapterprecis} adds some (negative) space (defined by
% \cs{prechapterprecisshift} whose value depends on whether or not the
% \Lopt{article} option is used, as discovered by Lars Madsen) and starts a
% quote environment using the \cs{precisfont}. \cs{postchapterprecis} ends
% the quote environment.
% \changes{v1.3}{2002/11/14}{Added \cs{prechapterprecis} and 
%                            \cs{postchapterprecis}}
% \changes{v1.61803}{2008/01/30}{Added \cs{prechapterprecisshift} and
%          \cs{precisfont} (mempatch v4.9)}
%    \begin{macrocode}
\newdimen\prechapterprecisshift
\ifartopt
  \prechapterprecisshift=0pt
\else
  \prechapterprecisshift=-2\baselineskip
\fi
\newcommand*{\precisfont}{\normalfont\itshape}
\newcommand{\prechapterprecis}{%
  \vspace*{\prechapterprecisshift}%
  \begin{quote}\precisfont}
%    \end{macrocode}
% \changes{v3.6k}{2013/04/24}{We are missing the after heading
% stuff. Otherwise text will indent after \cs{chapterprecis}}
%    \begin{macrocode}
\newcommand*{\postchapterprecis}{%
  \end{quote}%
  \par\m@mindentafterchapter%
  \@afterheading}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\precistocfont}
% Font for typesetting chapter precis in the ToC.
% \changes{v1.3}{2002/11/14}{Added \cs{precistocfont}}
%    \begin{macrocode}
\newcommand{\precistocfont}{\normalfont\itshape}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\precistocformat}
% Macro for adding extra formatting to the precis toc text, formatting
% that has nothiing to do with font. The default is \cs{noindent}.
% \changes{v3.6d}{2010/06/09}{Added \cs{precistocformat}}
%    \begin{macrocode}
\newcommand{\precistocformat}{\noindent}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chapterprecistoc}
% \begin{macro}{\precistoctext}
% \cs{chapterprecistoc}\marg{text} effectively adds \meta{text} to 
% the \file{.toc}
% file. The \meta{text} will be typeset within the same margins as the
% the title text of a \cs{chapter} heading, using the \cs{precistocfont} font.
% \changes{v1.3}{2002/11/14}{Added \cs{precistoctext}}
% \changes{v1.61803398}{2009/07/18}{Added bidi support to \cs{precistoctext}}
%    \begin{macrocode}
\newcommand{\chapterprecistoc}[1]{%
  \addtocontents{toc}{\precistoctext{#1}}}
\DeclareRobustCommand{\precistoctext}[1]{%
%    \end{macrocode}
% Start a group to localize changes to the paragraphing. Set the 
% left margin to the chapter indent plus the chapter number width.
% \changes{v1.6180339c}{2009/01/20}{Added a \cs{nopagebreak}, though
% this only disencourage a page break}
%    \begin{macrocode}
  {%\nopagebreak\leftskip \cftchapterindent\relax
   \nopagebreak\memRTLleftskip \cftchapterindent\relax
%%%   \advance\leftskip \cftchapternumwidth\relax
   \advance\memRTLleftskip \cftchapternumwidth\relax
%    \end{macrocode}
% Set the right hand margin to \cs{@tocrmarg}.
%    \begin{macrocode}
%%%   \rightskip \@tocrmarg\relax
   \memRTLrightskip \@tocrmarg\relax
%    \end{macrocode}
% Typeset \meta{text} using an italic font, then ensure that the paragraph
% is finished (to use the local skips). Finally close the group and we 
% are done.
% \changes{v3.6d}{2010/06/09}{Added \cs{precistocformat}}
%    \begin{macrocode}
   \precistocformat\precistocfont #1\par}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \subsection{Adding things to the ToC}
%
% \begin{macro}{\cftlocalchange}
% \cs{cftmakelocalchange}\marg{file}\marg{pnumwidth}\marg{tocrmarg}
% makes an entry into \meta{file} to change the \cs{@pnumwidth} and
% the \cs{@tocrmarg} values.
%    \begin{macrocode}
\newcommand{\cftlocalchange}[3]{%
  \addtocontents{#1}{\protect\setpnumwidth{#2} \protect\setrmarg{#3}}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\cftaddtitleline}
% \cs{cftaddtitleline}\marg{file}\marg{kind}\marg{title}\marg{page}
% adds a \cs{contentsline} entry to \meta{file} with the given information.
% \changes{v3.8.4}{2025/09/18}{Missing a \texttt{\{\}}}
%    \begin{macrocode}
\newcommand{\cftaddtitleline}[4]{%
  \addtocontents{#1}{\protect\contentsline{#2}{#3}{#4}{}}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\cftaddnumtitleline}
% \cs{cftaddnumtitleline}\marg{file}\marg{kind}\marg{num}\marg{title}\marg{page}
% adds a \cs{contentsline} entry to \meta{file} with the given information.
% \changes{v3.8.4}{2025/09/18}{Missing a \texttt{\{\}}}
%    \begin{macrocode}
\newcommand{\cftaddnumtitleline}[5]{%
  \addtocontents{#1}%
    {\protect\contentsline{#2}{\protect\numberline{#3}%
                              {\protect\ignorespaces #4}}{#5}{}}}
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\cftinsertcode}
% \begin{macro}{\cftinserthook}
% \begin{macro}{\cftinsert}
%  This is a generalisation of a suggestion by Lars Madsen (private email,
% 2007/12/14).
%
% \cs{cftinsertcode}\marg{id}\marg{code} creates a hook to be executed in 
% a `List of'. Since we use \cs{@nameuse} it does not matter if the hook 
% does not exist
%
% \cs{cftinserthook}\marg{list}\marg{id} inserts the hook \meta{id} into the 
% \meta{list} `List of' file (in the form of \cs{cftinsert}\marg{id}).
%
% Use like this:
% \begin{verbatim}
% \cftinsertcode{A}{%
%    \renewcommand*{\cftchapterfont}{\normalfont\scshape}
%    ...
%    }
% \cftinsertcode{F}{...}
% \cftinsertcode{G}{...}
%    ...
% \frontmatter
% \tableofcontents
% \cftinserthook{lof}{G}
% \listoffigures
% \chapter{...}
% ...
% \mainmatter
% \cftinserthook{lof}{F}
% \cftinserthook{toc}{A}
% \chapter{...}
% ...
% \end{verbatim}
%
% \changes{v1.61803}{2008/01/30}{Added \cs{cftinsert} and friends (mempatch v4.9)}
% \changes{v3.8.3}{2024/02/14}{Better implementation for \cs{cftinserthook}}
%    \begin{macrocode}
\newcommand*{\cftinsert}[1]{\@nameuse{cftinsert#1}}
\newcommand{\cftinsertcode}[2]{\@namedef{cftinsert#1}{#2}}
\NewDocumentCommand\cftinserthook{smm}{
  \IfBooleanTF{#1}{
    \ifdim\pagetotal>\z@
      \addtocontents{#2}{\protect\cftinsert\protect{#3\protect}}
      \clearpage
    \else
      \immediateaddtocontents{#2}{\noexpand\cftinsert{#3}}
    \fi 
  }{%
    \addtocontents{#2}{\protect\cftinsert\protect{#3\protect}}%
  }%
}



%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \paragraph{Caveat:} In certain cases an immediate verson of
% \cs{cftinserthook} might be needed due to race conditions. We might
% add such a version at some point.
% 
% 
% \subsection{ToC and divisional numbering}
%
%  Commands are provided, based on the \Lpack{tocvsec2} package, for changing
% the section numbering level and the ToC entry level.
%
% \begin{macro}{\@setclcnt}
% Helper macro to set a sectioning-related counter. Use as
% \cs{@setclcnt}\marg{sec}\marg{counter} to set \Lcount{counter}
% to the level of \meta{sec}.
% \changes{v1.61803}{2008/01/30}{Added book to \cs{@setclcnt} and friends
%                   (mempatch v4.4)}
% \changes{v1.61803398}{2009/07/29}{PW: Replaced \cs{if@tempswa} with 
%   \cs{@setclcntok} in \cs{@setclcnt} to avoid bad clashes with other uses}
% \changes{v3.8.3}{2024/02/13}{Reimplemented using expl3}
%    \begin{macrocode}
\ExplSyntaxOn
\newcommand*{\@setclcnt}[2]{%
  \str_case_e:nnF{#1}{
    {none}{          \setcounter{#2}{-10}}
    {book}{          \setcounter{#2}{-2} }
    {part}{          \setcounter{#2}{-1} }
    {chapter}{       \setcounter{#2}{0}  }
    {section}{       \setcounter{#2}{1}  }
    {subsection}{    \setcounter{#2}{2}  }
    {subsubsection}{ \setcounter{#2}{3}  }
    {paragraph}{     \setcounter{#2}{4}  }
    {subparagraph}{  \setcounter{#2}{5}  }
    {all}{           \setcounter{#2}{50} }
  }{
     \@memerror{%
       Unknown~document~division~name~(#1)
     }{%
      I'll~ignore~it.~
      Type~<return>~and~I'll~continue.\MessageBreak
      If~you~haven't~mistyped~the~name~then~ use~
      \protect\setcounter~instead.}%
  }
}
\ExplSyntaxOff
 % \newcommand*{\@setclcnt}[2]{%
 %   \def\@setclcntok{0}% = false
 %   \nametest{#1}{none}%
 %   \ifsamename
 %     \setcounter{#2}{-10}%
 %     \def\@setclcntok{1}% = true
 %   \fi
 %   \nametest{#1}{book}%
 %   \ifsamename
 %     \setcounter{#2}{-2}%
 %     \def\@setclcntok{1}%
 %   \fi
 %   \nametest{#1}{part}%
 %   \ifsamename
 %     \setcounter{#2}{-1}%
 %     \def\@setclcntok{1}%
 %   \fi
 %   \nametest{#1}{chapter}%
 %   \ifsamename
 %     \setcounter{#2}{0}%
 %     \def\@setclcntok{1}%
 %   \fi
 %   \nametest{#1}{section}%
 %   \ifsamename
 %     \setcounter{#2}{1}%
 %     \def\@setclcntok{1}%
 %   \fi
 %   \nametest{#1}{subsection}%
 %   \ifsamename
 %     \setcounter{#2}{2}%
 %     \def\@setclcntok{1}%
 %   \fi
 %   \nametest{#1}{subsubsection}%
 %   \ifsamename
 %     \setcounter{#2}{3}%
 %     \def\@setclcntok{1}%
 %   \fi
 %   \nametest{#1}{paragraph}%
 %   \ifsamename
 %     \setcounter{#2}{4}%
 %     \def\@setclcntok{1}%
 %   \fi
 %   \nametest{#1}{subparagraph}%
 %   \ifsamename
 %     \setcounter{#2}{5}%
 %     \def\@setclcntok{1}%
 %   \fi
 %   \nametest{#1}{all}%
 %   \ifsamename
 %     \setcounter{#2}{50}%
 %     \def\@setclcntok{1}%
 %   \fi
 % %%  \if@tempswa\else
 %     \ifnum \@setclcntok = 0\relax
 %     \@memerror{%
 %       Unknown document division name (#1)
 %     }{%
 %      I'll ignore it.
 %      Type \space <return> and I'll continue.\MessageBreak
 %      If you haven't mistyped the name then use
 %      \protect\setcounter\space instead.}%
 %   \fi}
 % 
%    \end{macrocode}
% \end{macro}
%
% 
% \begin{macro}{\settocdepth@}
%   \cs{settocdepth@}\marg{macro}\marg{sec}\\
%   This is a utility macro to fuel \cs{settocdepth}, and a
%   variant. Instead of a \cs{nametest} stack it is implemented using
%   the expl3 \verb|\str_case_e:nnTF| function. Here \meta{macro} is
%   the macro to use to write to the toc file.
% \changes{v3.8.3}{2024/02/13}{Added simpler implementation}
%    \begin{macrocode}
 \ExplSyntaxOn
\newcommand*{\settocdepth@}[2]{%
  \str_case_e:nnTF{#2}{
    {none}{          #1{toc}{\changetocdepth{-10}}}
    {book}{          #1{toc}{\changetocdepth{-2}} }
    {part}{          #1{toc}{\changetocdepth{-1}} }
    {chapter}{       #1{toc}{\changetocdepth{0}}  }
    {section}{       #1{toc}{\changetocdepth{1}}  }
    {subsection}{    #1{toc}{\changetocdepth{2}}  }
    {subsubsection}{ #1{toc}{\changetocdepth{3}}  }
    {paragraph}{     #1{toc}{\changetocdepth{4}}  }
    {subparagraph}{  #1{toc}{\changetocdepth{5}}  }
    {all}{           #1{toc}{\changetocdepth{50}} }
  }{
    \@ifundefined{toclevel@#2}{%
      \@memwarn{Unknown~toclevel~for~#2}%
    }{%
      \setcounter{tocdepth}{\@nameuse{toclevel@#2}}%
    }
  }{
    \@memerror{%
      Unknown~document~division~name~(#2)
    }{%
     I'll~ignore~ it.~
     Type~<return>~and~I'll~continue.}%
  }
}
\ExplSyntaxOff
%    \end{macrocode}
% \begin{macro}{\settocdepth}
% \begin{macro}{\immediatesettocdepth}
% \cs{settocdepth}\marg{sec} is the user command for setting 
% \Lcount{tocdepth} in the \file{.toc} file to the value corresponding to
% \meta{sec}. Also added an immediate version, which is rather dangerous,
% so not mentioned in the manual for now.
% \changes{v1.3}{2002/11/14}{Changed \cs{settocdepth} to use \cs{changetocdepth}}
% \changes{v1.61803}{2008/01/30}{Added book to ToC depth setting (mempatch v4.4)}.
% \changes{v1.61803398}{2009/07/29}{PW: Replaced \cs{if@tempswa} with 
%   \cs{@chtocdok} in \cs{settocdepth} to avoid bad clashes with other uses}
% \changes{v3.8.3}{2024/02/13}{Reimplemented using simpler code}
%    \begin{macrocode}
% \newcommand*{\settocdepth}[1]{\settocdepth@{\addtocontents}{#1}}
% \newcommand*{\immediatesettocdepth}[1]{\settocdepth@{\immediateaddtocontents}{#1}}
\NewDocumentCommand\settocdepth{sm}{%
  \IfBooleanTF{#1}{%
    \ifdim\pagetotal>\z@%
      \settocdepth@{\addtocontents}{#2}%
      \clearpage%
    \else%
      \settocdepth@{\immediateaddtocontents}{#2}%
    \fi%
  }{%
    \settocdepth@{\addtocontents}{#2}%
  }%
}




 %   \def\@chtodok{0}%   false
 %   \nametest{#1}{none}%
 %   \ifsamename
 %     \addtocontents{toc}{\changetocdepth{-10}}%
 %     \def\@chtodok{1}%   true
 %   \fi
 %   \nametest{#1}{book}%
 %   \ifsamename
 %     \addtocontents{toc}{\changetocdepth{-2}}%
 %     \def\@chtodok{1}%
 %   \fi
 %   \nametest{#1}{part}%
 %   \ifsamename
 %     \addtocontents{toc}{\changetocdepth{-1}}%
 %     \def\@chtocdok{1}%
 %   \fi
 %   \nametest{#1}{chapter}%
 %   \ifsamename
 %     \addtocontents{toc}{\changetocdepth{0}}%
 %     \def\@chtocdok{1}%
 %   \fi
 %   \nametest{#1}{section}%
 %   \ifsamename
 %     \addtocontents{toc}{\changetocdepth{1}}%
 %     \def\@chtocdok{1}%
 %   \fi
 %   \nametest{#1}{subsection}%
 %   \ifsamename
 %     \addtocontents{toc}{\changetocdepth{2}}%
 %     \def\@chtocdok{1}%
 %   \fi
 %   \nametest{#1}{subsubsection}%
 %   \ifsamename
 %     \addtocontents{toc}{\changetocdepth{3}}%
 %     \def\@chtocdok{1}%
 %   \fi
 %   \nametest{#1}{paragraph}%
 %   \ifsamename
 %     \addtocontents{toc}{\changetocdepth{4}}%
 %     \def\@chtocdok{1}%
 %   \fi
 %   \nametest{#1}{subparagraph}%
 %   \ifsamename
 %     \addtocontents{toc}{\changetocdepth{5}}%
 %     \def\@chtocdok{1}%
 %   \fi
 %   \nametest{#1}{all}%
 %   \ifsamename
 %     \addtocontents{toc}{\changetocdepth{50}}%
 %     \def\@chtocdok{1}%
 %   \fi
 %   \ifnum\@chtocdok=1\relax
 %     \@ifundefined{toclevel@#1}{%
 %       \@memwarn{Unknown toclevel for #1}%
 %     }{%
 %       \setcounter{tocdepth}{\@nameuse{toclevel@#1}}%
 %     }
 %   \else
 %     \@memerror{%
 %       Unknown document division name (#1)
 %     }{%
 %      I'll ignore it.
 %      Type \space <return> and I'll continue.}%
 %   \fi}
 
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\toclevel@none}
% \begin{macro}{\toclevel@all}
% Couple of extras for hypperef to cater for \texttt{all} and \texttt{none}
% as `division levels'.
% \changes{v1.61803}{2008/01/30}{Added \cs{toclevel@none} and \cs{toclevel@all}
%         (mempatch v4.4)}
% \changes{v3.7.19}{2022/10/25}{Changing \cs{toclevel@...} definitions to
% \cs{def} for better compability with future hyperref}
%    \begin{macrocode}
\def\toclevel@none{-10}
\def\toclevel@all{50}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\changetocdepth}
% Changes the \texttt{tocdepth} counter. Make it robust as it will be written
% to the *.toc file.
% \changes{v1.3}{2002/11/14}{Added \cs{changetocdepth}}
%    \begin{macrocode}
\DeclareRobustCommand{\changetocdepth}[1]{\setcounter{tocdepth}{#1}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\maxtocdepth}
% \cs{maxtocdepth}\marg{sec} can be used to initialise \Lcount{tocdepth}
% to the value corresponding to \meta{sec}. This can only be used
% between the end of the preamble and the \cs{tableofcontents} command.
%    \begin{macrocode}
\newcommand{\maxtocdepth}[1]{%
  \@setclcnt{#1}{tocdepth}}
%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\maxsecnumdepth}
% \cs{maxsecnumdepth}\marg{sec} can be used to initialise 
% \Lcount{secnumdepth}
% to the value corresponding to \meta{sec}.
% \changes{v1.1}{2002/03/10}{Added maxsecnumdepth counter and modified \cs{maxsecnumdepth}}
%    \begin{macrocode}
\newcounter{maxsecnumdepth}
\newcommand{\maxsecnumdepth}[1]{%
  \@setclcnt{#1}{secnumdepth}\@setclcnt{#1}{maxsecnumdepth}}

%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\setsecnumdepth}
% \cs{setsecnumdepth}\marg{sec} is the user command for setting
% \Lcount{secnumdepth} to the value for \meta{sec}. In the preamble it sets
% both the \Lcount{secnumdepth} and \Lcount{maxsecnumdepth} to \meta{sec}
% while in the body it only sets \Lcount{secnumdepth}.
% \changes{v1.61803}{2008/01/30}{Extended \cs{setsecnumdepth} to make it more
%           intuitive (mempatch v4.9)}
%    \begin{macrocode}
\newcommand{\setsecnumdepth}[1]{%
  \ifx\@nodocument\relax%      after the preamble
    \@setclcnt{#1}{secnumdepth}%
  \else
    \@setclcnt{#1}{secnumdepth}%
    \@setclcnt{#1}{maxsecnumdepth}%
  \fi}
\setsecnumdepth{section}

%    \end{macrocode}
% \end{macro}
% 
% 
%
%
% \section{Bibliography}
%
%
% \begin{macro}{\bibindent}
% The \Lopt{open} bibliography uses an indentation of \cs{bibindent}.
%    \begin{macrocode}
\newdimen\bibindent
  \setlength\bibindent{1.5em}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\bibitemsep}
% The vertical separation between items in the bibliography list.
% \changes{v1.4}{2003/11/22}{Added \cs{bibitemsep} (from patch v1.7)}
%    \begin{macrocode}
\newlength{\bibitemsep}
  \setlength{\bibitemsep}{\itemsep}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\biblistextra}
% A hook into the \texttt{bibitemlist}.
% \changes{v1.4}{2003/11/22}{Added \cs{biblistextra} (from patch v1.7)}
%    \begin{macrocode}
\newcommand{\biblistextra}{\itemsep=\bibitemsep}

%    \end{macrocode}
% \end{macro}
%
% \begin{environment}{bibitemlist}
%  The \texttt{thebibliography} environment starts a new document division. 
% Internally it tweaks some typesetting aspects; principally it
% uses \cs{sloppy} because good linebreaking is hard in a bibliography,
% and \verb?\sfcode`\.=1000\relax? causes a full stop not to produce an
% end-of-sentence space. The implementation of the environment is
% based on the generic \texttt{list} environment, and uses the \cs{c@enumiv}
% count for the labels. The following code is extracted from the
% \Lpack{book} class, plus some additions.
% \changes{v1.4}{2003/11/22}{Added \cs{biblistextra} to bibitemlist (from patch v1.7)}
%    \begin{macrocode}
\newenvironment{bibitemlist}[1]{%
  \typeout{bibitemlist}
  \list{\@biblabel{\@arabic\c@enumiv}}%
       {\settowidth\labelwidth{\@biblabel{#1}}%
        \leftmargin\labelwidth
        \advance\leftmargin\labelsep
        \@openbib@code
        \usecounter{enumiv}%
        \let\p@enumiv\@empty
        \renewcommand\theenumiv{\@arabic\c@enumiv}%
        \biblistextra}%
  \sloppy
  \clubpenalty4000
  \@clubpenalty \clubpenalty
  \widowpenalty4000%
  \sfcode`\.\@m}%
  {\def\@noitemerr
    {\@latex@warning{Empty `thebibliography' environment}}%
    \endlist}

%    \end{macrocode}
% \end{environment}
%
% \begin{macro}{\newblock}
% The default is for \cs{newblock} to provide a small space.
%    \begin{macrocode}
\newcommand{\newblock}{\hskip .11em\@plus.33em\@minus.07em}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@openbib@code}
% This a an empty hook. It will be modified if the \Lopt{openbib}
% option is used.
%    \begin{macrocode}
\let\@openbib@code\@empty
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\setbiblabel}
% \begin{macro}{\@biblabel}
% This is the user command for setting the label for a \cs{bibitem}. 
% The following sets the default definition.
%    \begin{macrocode}
\newcommand*{\setbiblabel}[1]{%
  \renewcommand*{\@biblabel}[1]{#1}}
\setbiblabel{[#1]\hfill}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@memb@bchap}
% \begin{macro}{\@memb@bsec}
%  In a \ctt{} thread \textit{memoir, natbib, and chapterbib} in January 2003
% there was a discussion on how to get all three to work together.
% Donald Arseneau suggested that \cs{bibsection} be used as a `standard'
% way of controlling the sectioning command of a bibliography. Here is
% an implementation of that idea.
%
% \cs{@memb@bchap} is a copy of memoir's original code for the start
% of the \texttt{thebibliography} environment which used a \cs{chapter*}
% title. \cs{@memb@bsec} is the much simpler version for a \cs{section} title.
% \changes{v1.4}{2003/02/27}{Added support code for implementing \cs{bibsection}
%                            (patch 1.3)}
% \changes{v3.7g}{2018/02/28}{Removeded \cs{phantomsection} before
% \cs{addcontentsline} as it is no longer needed, and causes the
% hyperlink target to the bibligraphy to be below the title, reported
% via \texttt{https://tex.stackexchange.com/a/396303/3929}}
%    \begin{macrocode}
\newcommand{\@memb@bchap}{%
  \chapter*{\bibname}%
  \bibmark
  \ifnobibintoc\else
    % \phantomsection
    \addcontentsline{toc}{chapter}{\bibname}%
  \fi
  \prebibhook}
\newcommand{\@memb@bsec}{\section{\bibname}\prebibhook}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\bibsection}
% Normally treat the bibliography heading as a chapter.
% \changes{v1.4}{2003/02/27}{Added \cs{bibsection} to replace memoir's
%                            original code for the bibliography (patch 1.3)}
%    \begin{macrocode}
\newcommand{\bibsection}{\@memb@bchap}

%    \end{macrocode}
% \end{macro}
% 
% \begin{environment}{thebibliography}
% The definition of the \texttt{thebibliography} environment in this class is not
% quite the same as in the standard classes!
%
% \changes{v0.2}{2001/06/03}{Deleted starred version of thebibliography}
% \changes{v1.4}{2003/02/27}{Replaced initial code in the bibliography
%                            environment by \cs{bibsection} (patch 1.3)}
%    \begin{macrocode}
\newenvironment{thebibliography}[1]{%
  \bibsection
  \begin{bibitemlist}{#1}}{\end{bibitemlist}\postbibhook}
%    \end{macrocode}
% \end{environment}
%
% \begin{macro}{\ifnobibintoc}
% \begin{macro}{\bibintoc}
% \begin{macro}{\nobibintoc}
% Flag to control whether or not to add the bibliography title to the ToC,
% and declarations to set the flag.
% Default is to put the title into the ToC.
% \changes{v0.2}{2001/06/03}{Added \cs{ifnobibintoc}, etc.}
%    \begin{macrocode}
\newif\ifnobibintoc
\newcommand*{\bibintoc}{\nobibintocfalse}
\newcommand*{\nobibintoc}{\nobibintoctrue}
\bibintoc

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\prebibhook}
% \begin{macro}{\postbibhook}
% These two macros are called just before starting the bib items and just
% after finishing them. By default they do nothing but can be changed
% by the user to give, say, some introductory information.
%    \begin{macrocode}
\newcommand{\prebibhook}{}
\newcommand{\postbibhook}{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\@cite}
% The output of the \cs{cite} command is produced by this macro. The default
% is used. The \Lpack{cite} package is a good way of changing this.
%    \begin{macrocode}
% \renewcommand*{\@cite}[1]{[#1]}
%    \end{macrocode}
% \end{macro}
%
% \subsection{Use with the \Lpack{natbib} and \Lpack{chapterbib} packages}
%
% The \Lpack{natbib} package~\cite{NATBIB} uses its own definition for
% the \texttt{thebibliography} environment, which knows nothing about adding
% the Bibliography to the ToC. The following makes appropriate changes
% to \Lpack{natbib} code to support the class.
%
% The \Lpack{chapterbib} package by Donald Arseneau also may make changes
% to the \texttt{thebibliography} environment --- perhaps memoir's version
% or natbib's version.
%
%    As packages get loaded after classes, I have to try and patch any
% non-memoir modifications at begin document time. 
% The fixes have to be firstly for \Lpack{natbib}
% and only after those can \Lpack{chapterbib} be considered.
%
% \changes{v1.1}{2002/03/10}{Added internal support for the natbib package}
% \changes{v1.4}{2003/02/27}{Changed code supporting natbib (patch 1.3)}
% \changes{v1.4}{2003/02/27}{Added code supporting chapterbib (patch 1.3)}
% \begin{macro}{\bibsection}
% \begin{macro}{\endthebibliography}
% Natbib provides \cs{bibsection} for titling the bibliography. I also have
% to extend the end of the \texttt{thebibliography} environment to cater for
% \cs{postbibhook}.
%    \begin{macrocode}
\AtBeginDocument{%
  \@ifpackageloaded{natbib}{% natbib is loaded
%    \end{macrocode}
% As \Lpack{natbib} is used, change \cs{endthebibliography} to the class
% definition.
%    \begin{macrocode}
    \addtodef{\endthebibliography}{}{\vskip-\lastskip\postbibhook}
    \@ifpackagewith{natbib}{sectionbib}{% with sectionbib option
%    \end{macrocode}
% \Lpack{natbib}'s \Lopt{sectionbib} option is used,
%    \begin{macrocode}
      \renewcommand{\bibsection}{\@memb@bsec}}%
%    \end{macrocode}
% The \Lopt{sectionbib} option is not used, so we have a chapter title.
%    \begin{macrocode}
      {\renewcommand{\bibsection}{\@memb@bchap}}}%
%    \end{macrocode}
% Finished with any \Lpack{natbib} related changes.
%    \begin{macrocode}
  {}
%    \end{macrocode}
%
% Now deal with \Lpack{chapterbib} if necessary.
%    \begin{macrocode}
  \@ifpackagewith{chapterbib}{sectionbib}{%
%    \end{macrocode}
% \Lpack{chapterbib} is used with its \Lopt{sectionbib} option. This is the
% only case to worry about. Kill \Lpack{chapterbib}'s \cs{sectionbib} macro
% which it calls at begin document to do its patch, then make sure
% the class definition is used.
%    \begin{macrocode}
    \renewcommand{\sectionbib}[2]{}
    \renewcommand{\bibsection}{\@memb@bsec}}{}
%    \end{macrocode}
% And we've finished with this bunch of \cs{AtBeginDocument} code.
%    \begin{macrocode}
}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
%
%  \section{The index}
%
% I allow for a single column index as well as the default double column.
%
% \begin{macro}{\ifonecolindex}
% TRUE for a one column index.
% \changes{v1.3}{2002/10/10}{Added one column index}
%    \begin{macrocode}
\newif\ifonecolindex
  \onecolindexfalse

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\onecolindex}
% \begin{macro}{\twocolindex}
% \changes{v1.61803}{2008/01/30}{Added \cs{onecolindex} and \cs{twocolindex}}
%    \begin{macrocode}
\newcommand*{\onecolindex}{\onecolindextrue}
\newcommand*{\twocolindex}{\onecolindexfalse}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{environment}{theindex}
%    The environment \texttt{theindex} can be used for indices. It makes an
%    index with two columns, with each entry a separate paragraph. At
%    the user level the commands \cs{item}, \cs{subitem} and \cs{subsubitem}
%    are used to produce index entries of various levels. When a new
%    letter of the alphabet is encountered an amount of \cs{indexspace}
%    white space can be added.
%
%
% \changes{v0.2}{2001/06/03}{Deleted starred version of theindex}
% \changes{v0.2}{2001/06/03}{Changed Index pagestyle to chapter}
% \changes{v1.618}{2005/09/03}{Make \cs{indexcolsep} work, courtesy of hazydirk (mempatch v3.11)}
% \changes{v1.61803}{2008/01/30}{Added \cs{clearforchapter} to theindex
%         environment (Erik Quaeghebeur, mempatch v4.4)}
% \changes{v1.61803}{2008/01/30}{Added an indextitlepagestyle (Lars Madsen
%                    mempatch v4.6)}
% \changes{v3.8.4}{2025/09/16}{Replaced \cs{phantomsection} by \cs{MakeLinkTarget} and moved it}
%    \begin{macrocode}
\newenvironment{theindex}{%
  \clearforchapter
  \if@twocolumn
    \@restonecolfalse
  \else
    \@restonecoltrue
  \fi
  \ifonecolindex
    \onecolumn
    \chapter*{\indexname}
    \preindexhook
  \else
    \setlength{\columnseprule}{\indexrule}%
    \setlength{\columnsep}{\indexcolsep}%
    \MakeLinkTarget[chapter]{}% <-- new 2025
    \twocolumn[%
    \@makeschapterhead{\indexname}
    \preindexhook]%
  \fi
  \indexmark
  \ifnoindexintoc\else
    %\phantomsection
    \addcontentsline{toc}{chapter}{\indexname}%
  \fi
  \thispagestyle{indextitlepagestyle}\parindent\z@
  \parskip\z@ \@plus .3\p@\relax
  \let\item\@idxitem}%
  {\if@restonecol\onecolumn\else\twocolumn\fi}

%    \end{macrocode}
% \end{environment}
%
% \begin{macro}{\ps@indextitlepagestyle}
%    \begin{macrocode}
\aliaspagestyle{indextitlepagestyle}{chapter}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ifnoindexintoc}
% \begin{macro}{\indexintoc}
% \begin{macro}{\noindexintoc}
% Flag to control whether or not to add the index title to the ToC,
% and declarations to set the flag.
% Default is to put the title into the ToC.
% \changes{v0.2}{2001/06/03}{Added \cs{ifnoindexintoc}, etc.}
%    \begin{macrocode}
\newif\ifnoindexintoc
\newcommand*{\indexintoc}{\noindexintocfalse}
\newcommand*{\noindexintoc}{\noindexintoctrue}
\indexintoc

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\indexcolsep}
% \begin{macro}{\indexrule}
% These two lengths control the column separation and the thickness
% of the inter-column rule.
% \changes{v0.2}{2001/06/03}{Added \cs{indexcolsep} and \cs{indexrule}}
%    \begin{macrocode}
\newlength{\indexcolsep} \setlength{\indexcolsep}{35pt}
\newlength{\indexrule}   \setlength{\indexrule}{0pt}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\preindexhook}
% A macro that is called between the index heading and the start of the
% two columns. The user can modify it to add something.
%    \begin{macrocode}
\newcommand{\preindexhook}{}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\l@index}
%   Format the index entry in the table of contents.
%    \begin{macrocode}
\newcommand{\l@index}{\@dottedtocline{1}{0em}{0pt}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@idxitem}
% \begin{macro}{\subitem}
% \begin{macro}{\subsubitem}
%    Thsee macros are used to format the entries in the index. 
%    \begin{macrocode}
\newcommand{\@idxitem}  {\par\hangindent 40\p@}
\newcommand{\subitem}   {\par\hangindent 40\p@ \hspace*{20\p@}}
\newcommand{\subsubitem}{\par\hangindent 40\p@ \hspace*{30\p@}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\indexspace}
%    The amount of white space that is inserted between `letter
%    blocks' in the index.
%    \begin{macrocode}
\newcommand{\indexspace}{\par \vskip 10\p@ \@plus5\p@ \@minus3\p@\relax}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\makeindex}
% \begin{macro}{\index}
% \begin{macro}{\specialindex}
% \begin{macro}{\makememindexhook}
% This is a modified version of the kernel \cs{makeindex} to allow for
% multiple indexes. It also defines \cs{index} (which is a modified version
% of the standard \cs{index}) and \cs{specialindex}.
%
% \cs{makememindexhook} is a null op but can be redefined to add extra code
% into \cs{makeindex}. For example, to incorporate \Lpack{ledmac}'s
% \cs{edindex} into the scheme:
% \begin{verbatim}
% \renewcommand*{\makememindexhook}{%
%    \def\edindex{\@bsphack%
%      \@ifnextchar [{\l@d@index}{\l@d@index[\jobname]}}}
% \end{verbatim}
% \changes{v1.3}{2002/11/14}{Indexing macros completely redone and extended}
% \changes{v1.61}{2004/03/12}{Added the \cs{makememindexhook} to \cs{makeindex}}
% \changes{v1.618}{2005/09/02}{Modified \cs{makeindex} for \cs{nofiles}}
%    \begin{macrocode}
\newcommand*{\makememindexhook}{}
%    \end{macrocode}
%    \begin{macrocode}
\providecommand*{\makeindex}{}
\renewcommand*{\makeindex}[1][\jobname]{%
  \if@filesw
    \def\index{\@bsphack%
      \@ifnextchar [{\@index}{\@index[\jobname]}}
    \def\specialindex{\@bsphack\@spindex}%
    \makememindexhook
    \expandafter\newwrite\csname #1@idxfile\endcsname
    \expandafter\immediate\openout \csname #1@idxfile\endcsname #1.idx\relax
    \typeout{Writing index file #1.idx }%
  \fi}

%    \end{macrocode}
% Initially define, but emasculate, \cs{index} and \cs{specialindex} which are
% defined properly by the user calling \cs{makeindex}.
%    \begin{macrocode}
\renewcommand{\index}[2][\jobname]{\@bsphack\@esphack}
\newcommand{\specialindex}[3]{\@bsphack\@esphack}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\printindex}
% The command to read an \file{ind} file.
%    \begin{macrocode}
\newcommand{\printindex}[1][\jobname]{\@input@{#1.ind}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ifreportnoidxfile}
% \begin{macro}{\reportnoidxfile}
% \begin{macro}{\ignorenoidxfile}
% \begin{macro}{\ifshowindexmark}
% \begin{macro}{\showindexmarks}
% \begin{macro}{\hideindexmarks}
% Two booleans to control reporting on unknown \file{idx} files and
% displaying indexed items in the margin.
%    \begin{macrocode}
\newif\ifreportnoidxfile
\newcommand*{\reportnoidxfile}{\reportnoidxfiletrue}
\newcommand*{\ignorenoidxfile}{\reportnoidxfilefalse}
  \ignorenoidxfile
\newif\ifshowindexmark
\newcommand*{\showindexmarks}{\showindexmarktrue}
\newcommand*{\hideindexmarks}{\showindexmarkfalse}
  \hideindexmarks

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@index}
% \verb?\@index[file]? is first stage of \cs{index}, handling the \file{idx} file.
%    \begin{macrocode}
\def\@index[#1]{%
  \@ifundefined{#1@idxfile}%
  {\ifreportnoidxfile
     \@memwarn{Undefined index file #1}%
    \fi
    \begingroup
    \@sanitize
    \@nowrindex}%
  {\def\@idxfile{#1}%
   \begingroup
   \@sanitize
   \@wrindexm@m}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@nowrindex}
% Called when there is no \file{idx} file to throw away the indexed item.
%    \begin{macrocode}
\newcommand{\@nowrindex}[1]{%
  \ifshowindexmark\@showidx{#1}\fi\endgroup\@esphack}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@wrindexm@m}
% \begin{macro}{\@@wrindexhyp}
% The next stage in index processing is \verb?\@wrindexm@m{item}?, 
% which writes the \file{idx} file name
% and indexed item to the \file{aux} file. The \cs{@@wrindexhyp} macro
% provides hyperlinks in case the \Lpack{hyperref} package is used.
%    \begin{macrocode}
\newcommand{\@wrindexm@m}[1]{\@@wrindexhyp#1||\\}
\def\@@wrindexhyp#1|#2|#3\\{%
  \ifshowindexmark\@showidx{#1}\fi
  \ifx\\#2\\%
    \protected@write\@auxout{}%
      {\string\@@wrindexm@m{\@idxfile}{#1|hyperpage}{\thepage}}%
  \else
    \def\Hy@temp@A{#2}%
    \ifx\Hy@temp@A\HyInd@ParenLeft
      \protected@write\@auxout{}%
        {\string\@@wrindexm@m{\@idxfile}{#1|#2hyperpage}{\thepage}}%
    \else
%    \end{macrocode}
% Add a corresponding test on \verb+|)+ to add \verb|hyperpage|. This
% is needed by the \verb|xindy| indexing programme. The standard
% \verb|makeindex| programme does not seem to mind.
% \changes{v3.7g}{2018/04/04}{Added test for \texttt{|)} and adding
% \texttt{hyperpage} accordingly.}
%    \begin{macrocode}
      \ifx\Hy@temp@A\HyInd@ParenRight
        \protected@write\@auxout{}%
          {\string\@@wrindexm@m{\@idxfile}{#1|#2hyperpage}{\thepage}}%
      \else
        \protected@write\@auxout{}%
          {\string\@@wrindexm@m{\@idxfile}{#1|#2}{\thepage}}%
      \fi        
    \fi
  \fi
  \endgroup
  \@esphack}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\hyperpage}
% \begin{macro}{\hyperlink}
% These are defined in the \Lpack{hyperref} package but we need them.
% Other hyperstuff is only used if the package itself is used.
%    \begin{macrocode}
\newcommand{\hyperpage}[1]{#1}
\newcommand{\hyperlink}[2]{#2}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@@wrindexm@m}
% The macro \verb?\@@wrindexm@m{file}{item}{page}? has been written into
% the \file{aux} file. It is normally defined so that it calls
% \verb?\@@@wrindexm@m{item}{page}? to finally write to the \file{idx} file.
%    \begin{macrocode}
\newcommand{\@@wrindexm@m}[1]{\begingroup
  \def\@idxfile{\@nameuse{#1@idxfile}}
  \@sanitize
  \@@@wrindexm@m}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@@@wrindexm@m}
% \cs{@@@wrindexm@m}\marg{item}\marg{page} writes the \cs{indexentry} to 
% the \file{idx} file. This file is read both at the beginning and end of 
% a document so \cs{@@@wrindexm@m} must be disabled for one of these reads
% otherwise the index entries will be doubled up. Initially I disabled it
% after the first read. It eventually dawned on me that this meant two
% LaTeX runs to update the \file{idx}. Enabling it for the second read
% means that the \file{idx} file is updated at the end of each run.
% \changes{v1.618}{2005/09/02}{Made \cs{@@@wrindexm@m} obey \cs{nofiles}}
% \changes{v1.618}{2005/09/25}{\cs{@@@wrindexm@m} now reads the aux
%                  file at the end of the document}
% \changes{v3.7i}{2019/11/15}{Changed the writing to protected}
%    \begin{macrocode}
\newcommand{\@@@wrindexm@m}[2]{\endgroup}
\AtBeginDocument{%
  \def\@@@wrindexm@m#1#2{%
    \if@filesw
      %\immediate\write \@idxfile{\string\indexentry{#1}{#2}}%
      \immediate@protected@write\@idxfile{}{\string\indexentry{#1}{#2}}%
    \fi
    \endgroup}%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@spindex}
% Now do similar things for \cs{specialindex}.
%    \begin{macrocode}
\newcommand{\@spindex}[2]{%
  \@ifundefined{#1@idxfile}%
  {\ifreportnoidxfile
     \@memwarn{Undefined index file #1}%
    \fi
    \begingroup
    \@sanitize
    \@nowrindex}%
  {\def\@idxfile{#1}%
   \def\@sptheidx{#2}%
   \begingroup
   \@sanitize
   \@wrspindex}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@wrspindex}
% \begin{macro}{\@@wrspindexhyp}
%    \begin{macrocode}
\newcommand{\@wrspindex}[1]{\@@wrspindexhyp#1||\\}
\def\@@wrspindexhyp#1|#2|#3\\{%
  \ifshowindexmark\@showidx{#1}\fi
  \ifx\\#2\\%
    \protected@write\@auxout{}%
      {\string\@@wrindexm@m{\@idxfile}%
        {#1|hyperspindexpage(\thepage)}%
      {\@nameuse{the\@sptheidx}}}%
  \else
    \def\Hy@temp@A{#2}%
    \ifx\Hy@temp@A\HyInd@ParenLeft
      \protected@write\@auxout{}%
        {\string\@@wrindexm@m{\@idxfile}%
         {#1|#2hyperspindexpage(\thepage)}%
         {\@nameuse{the\@sptheidx}}}%
    \else
      \protected@write\@auxout{}%
        {\string\@@wrindexm@m{\@idxfile}{#1|#2}%
        {\@nameuse{the\@sptheidx}}}%
    \fi
  \fi
  \endgroup
  \@esphack}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\hyperspindexpage}
%    \begin{macrocode}
\def\hyperspindexpage(#1)#2{\hyperlink{page.#1}{#2}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ifmemhyperindex}
% \begin{macro}{\memhyperindextrue}
% \begin{macro}{\memhyperindexfalse}
% Flag to turn off \cs{hyperindexfalse} hyperrefing the index (apparently
% \Lpack{xindy} can't cope with this. Email from Frederic Connes, 2005/07/13:
% \begin{verbatim}
%  ...You use |hyperspindex(\thepage) which xindy doesn't 
% recognise as a valid markup-locref. And I don't know how 
% to add it because xindy only accepts one argument in 
% markup-locref (if the number is not a page number, it will 
% still point to a page with that number) so replacing it 
% with |hyperpage won't work. ...
% \end{verbatim}
% 
%
% The default is \cs{memhyperindextrue}. Setting \cs{memhyperindexfalse}
% prohibits a hyper index --- setting whatever option in \Lpack{hyperref}
% to disable hyper indexing will (probably) not work as far as \Lpack{xindy}
% is concerned.
% \changes{v1.618}{2005/09/04}{Added \cs{ifmemhyperindex}}
%    \begin{macrocode}
\newif\ifmemhyperindex
  \memhyperindextrue

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\ifm@mxindy}
% \begin{macro}{\m@mxindytrue}
% \begin{macro}{\m@mxindyfalse}
% \begin{macro}{\xindyindex}
% \begin{macro}{\@@wrspindexhyp}
%   Use \cs{xindyindex} when you are going to use the xindy program
%   rather than makeindex. hyperrefed entries won't work with xindy.
%   The code was supplied by Frederic Connes in an email to me on
%   2006/01/08.
% \changes{v1.61803}{2008/01/30}{Added \cs{xindyindex} (Frederic Connes
%                  mempatch v4.4)}
%    \begin{macrocode}
\newif\ifm@mxindy
\m@mxindyfalse
\newcommand*{\xindyindex}{\m@mxindytrue}
\def\@@wrspindexhyp#1|#2|#3\\{%
  \ifshowindexmark\@showidx{#1}\fi
  \ifx\\#2\\%
    \protected@write\@auxout{}%
      {\string\@@wrindexm@m{\@idxfile}%
        \ifm@mxindy{#1}\else{#1|hyperspindexpage(\thepage)}\fi
      {\@nameuse{the\@sptheidx}}}%
  \else
    \def\Hy@temp@A{#2}%
    \ifx\Hy@temp@A\HyInd@ParenLeft
      \protected@write\@auxout{}%
        {\string\@@wrindexm@m{\@idxfile}%
         \ifm@mxindy{#1|#2}\else{#1|#2hyperspindexpage(\thepage)}\fi
      {\@nameuse{the\@sptheidx}}}%
    \else
      \protected@write\@auxout{}%
        {\string\@@wrindexm@m{\@idxfile}{#1|#2}%
      {\@nameuse{the\@sptheidx}}}%
    \fi
  \fi
  \endgroup
  \@esphack}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
%
% \begin{macro}{\@@wrindexhyp}
% \begin{macro}{\@@wrspindexhyp}
% If the \Lpack{hyperref} package is not being used, or \cs{ifmemhyperindex}
% is false, there is no need
% to clutter up the index files. 
% \changes{v1.61}{2004/03/28}{Declutter index files if hyperref is not used}
% \changes{v1.618}{2005/09/02}{Fixed spaces in non-hyperref index files (mempatch v2.3).
% Reported by Michael W. Daniels.}
%    \begin{macrocode}
\AtBeginDocument{%
  \@ifpackageloaded{hyperref}{}{\memhyperindexfalse}%
%    \end{macrocode}
% If the \Lpack{hyperref} package is not being used, or a hyperindex
% is not required, simplify!
%    \begin{macrocode}
  \ifmemhyperindex\else
    \def\@@wrindexhyp#1||\\{%
      \ifshowindexmark\@showidx{#1}\fi
      \protected@write\@auxout{}%
        {\string\@@wrindexm@m{\@idxfile}{#1}{\thepage}}%
      \endgroup
      \@esphack}%
    \def\@@wrspindexhyp#1||\\{%
      \ifshowindexmark\@showidx{#1}\fi
      \protected@write\@auxout{}%
        {\string\@@wrindexm@m{\@idxfile}{#1}{\@nameuse{the\@sptheidx}}}%
      \endgroup
      \@esphack}%
  \fi
}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\see}
% \begin{macro}{\seename}
% \begin{macro}{\seealso}
% \begin{macro}{\alsoname}
% These definitions are taken from the \Lpack{makeidx} package.
%    \begin{macrocode}
\newcommand*{\see}[2]{\emph{\seename} #1}
\newcommand*{\seename}{see}
\newcommand*{\seealso}[2]{\emph{\alsoname} #1}
\newcommand*{\alsoname}{see also}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\citeindexfile}
% For the \Lpack{natbib} package, and possibly other packages that do 
% some special indexing.
%    \begin{macrocode}
\newcommand{\citeindexfile}{\jobname}
\AtBeginDocument{\@ifpackageloaded{natbib}{%
  \def\NAT@index{\index[\citeindexfile]{\NAT@idxtxt}}}{}}

%    \end{macrocode}
% \end{macro}
%
% The next part of the code is essentially the \Lpack{showidx} package.
% I tried putting index entries into marginpars but too many on a page
% led to the `too many floats' problem.
%
% \begin{macro}{\indexmarkstyle}
% \begin{macro}{\@indexbox}
%    \begin{macrocode}
\newtoks\indexmarkstyle
  \indexmarkstyle{\normalfont\footnotesize\ttfamily}
\newinsert\@indexbox
  \dimen\@indexbox\maxdimen

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%    \begin{macrocode}
\begingroup
  \catcode`\@\active
  \expandafter\gdef\csname\string @sanitizeat\endcsname
  {\def @{\char`\@}}
\endgroup

%    \end{macrocode}
%
% \begin{macro}{\@showidx}
%    \begin{macrocode}
\newcommand{\@showidx}[1]{%
  \insert\@indexbox{%
    \@sanitizeat
    \the\indexmarkstyle
    \hsize\marginparwidth
    \hangindent\marginparsep \parindent\z@
    \everypar{}\let\par\@@par \parfillskip\@flushglue
    \lineskip\normallineskip
    \baselineskip .8\normalbaselineskip\sloppy
    \raggedright \leavevmode
    \vrule \@height .7\normalbaselineskip \@width \z@\relax
      #1\relax
    \vrule \@height \z@ \@depth .3\normalbaselineskip \@width \z@\relax
  }%
  \ifhmode\penalty\@M \hskip\z@skip\fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@leftidx}
% \begin{macro}{\@rightidx}
%    \begin{macrocode}
\newcommand{\@leftidx}{\hskip-\marginparsep \hskip-\marginparwidth}
\newcommand{\@rightidx}{\hskip\columnwidth \hskip\marginparsep}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@mkidx}
%    \begin{macrocode}
\newcommand{\@mkidx}{\vbox to \z@{%
  \rlap{%
    \if@twocolumn
      \if@firstcolumn \@leftidx \else \@rightidx \fi
    \else
      \if@twoside
        \ifodd\c@page \@rightidx \else \@leftidx \fi
      \else
        \@rightidx
      \fi
    \fi
    \box\@indexbox
  }%
  \vss}}

%    \end{macrocode}
% \end{macro}
%
% \section{Page bottom}
%
% \begin{macro}{\raggedbottom}
% \begin{macro}{\flushbottom}
% \begin{macro}{\@texttop}
% \begin{macro}{\mem@flshbot}
% These kernel macros need changing because of the new \cs{@indexbox} 
% marginal insert.
% \changes{v3.7d}{2015/04/21}{It makes more sense to explicitly call
% \cs{flushbottom} than just let \cs{@texttop}. We also add a switch
% macro to see if \cs{flushbottom} is active. \cs{raggedbottom} and
% \cs{sloppybottom} sets the switch to false}
% \changes{v3.8}{2023/08/08}{The kernel defined these as robust, we'd
% better too}
%    \begin{macrocode}
\DeclareRobustCommand{\raggedbottom}{%
  \def\mem@flshbot{01}%
  \def\@textbottom{\vskip\z@ plus.0001fil}%
  \let\@texttop\@mkidx}
\DeclareRobustCommand{\flushbottom}{%
  \def\mem@flshbot{00}%
  \let\@textbottom\relax
  \let\@texttop\@mkidx}
\let\@texttop\@mkidx
\flushbottom

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \subsection{Widows and sloppybottom}
%
%    There was a discussion \textit{widow handling?} on CTT in 
% May 2006. Ivowel wrote
% \begin{quote}
% in experimenting with raggedbottom, widowpenalty, and clubpenalty,
% I think that I have not found a solution that strikes me as 
% particularly desirable. I think what I would really like is that
% widows (i.e., left-over single lines that begin on the following
% page) are resolved not by pushing one extra line from the same
% paragraph also onto the next page, but by stretching the
% \cs{textheight} to allow this one extra at the bottom of the
% same page.
% \end{quote}
% Donald Arseneau, as he so often does, came up with a solution he
% termed \cs{sloppybottom}. Here is a generalised version.
%
% \begin{macro}{\sloppybottom}
% \cs{sloppybottom} allows an extra line on a page to save a widow.
% You must increase the \cs{topskip} (by 60 percent is reasonable) and this
% will push the text lower on the page. Run \cs{checkandfixthelayout}
% after the change. For example:
% \begin{verbatim}
% \setlength{\topskip}{1.6\topskip}
% \checkandfixthelayout
% \sloppybottom
% ...
% \end{verbatim}
% \changes{v1.61803}{2008/01/30}{Added \cs{sloppybottom} (mempatch v4.6)}
% \changes{v3.7d}{2015/04/21}{Added flush bottom switch}
%    \begin{macrocode}
\newcommand*{\sloppybottom}{%
  \def\mem@flshbot{01}%
  \def\@textbottom{\vskip \z@ \@plus.0001fil \@minus .95\topskip}%
  \topskip=1\topskip \@plus 0.625\topskip \@minus .95\topskip
  \def\@texttop{\vskip \z@ \@plus -0.625\topskip \@minus -0.95\topskip}}

%    \end{macrocode}
% \end{macro}
%
%
%
%
% \section{Glossaries}
%
% Standard LaTeX provides little and insufficient support for
% glossaries, just a \cs{makeglossary} and \cs{glossary} commands.
% This class does somewhat better. The code follows along the lines
% of that for indexes.
% \changes{v1.618}{2005/09/25}{Added glossary code}
%
%
% \begin{macro}{\ifonecolglossary}
% \begin{macro}{\onecolglossarytrue}
% \begin{macro}{\onecolglossaryfalse}
% TRUE for a one column glossary, otherwise its two column.
%    \begin{macrocode}
\newif\ifonecolglossary
  \onecolglossarytrue
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\onecolglossary}
% \begin{macro}{\twocolglossary}
% \changes{v1.61803}{2008/01/30}{Added \cs{onecolglossary} and \cs{twocolglossary}}
%    \begin{macrocode}
\newcommand*{\onecolglossary}{\onecolglossarytrue}
\newcommand*{\twocolglossary}{\onecolglossaryfalse}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{environment}{theglossary}
% The environment \texttt{theglossary} is used for glossaries.
% It makes a glossary with one or two columns, headed by a chapter-like
% title.
% \changes{v3.8.4}{2025/09/16}{Replaced \cs{phantomsection} with \cs{MakeLinkTarget} and moved it}
%    \begin{macrocode}
\newenvironment{theglossary}{%
  \if@twocolumn
    \@restonecolfalse
  \else
    \@restonecoltrue
  \fi
  \ifonecolglossary
    \onecolumn
    \chapter*{\glossaryname}
    \preglossaryhook
  \else
    \setlength{\columnseprule}{\glossaryrule}
    \setlength{\columnsep}{\glossarycolsep}
    \MakeLinkTarget[chapter]{}%
    \twocolumn[%
    \@makeschapterhead{\glossaryname}
    \preglossaryhook
    ]%
  \fi
  \glossarymark
  \ifnoglossaryintoc\else
    %\phantomsection
    \addcontentsline{toc}{chapter}{\glossaryname}
  \fi
  \thispagestyle{chapter}\parindent\z@
  \parskip\z@ \@plus .3\p@\relax
  \begintheglossaryhook}%
  {\atendtheglossaryhook\if@restonecol\onecolumn\else\twocolumn\fi}

%    \end{macrocode}
% \end{environment}
%
% \begin{macro}{\begintheglossaryhook}
% \begin{macro}{\atendtheglossaryhook}
% Two vacuous macros called as the last thing by \verb?\begin{theglossary}?
% and the first thing by \verb?\end{theglossary}? These could be used,
% for example, to insert another kind of environment.
%    \begin{macrocode}
\newcommand*{\begintheglossaryhook}{}
\newcommand*{\atendtheglossaryhook}{}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\preglossaryhook}
% A vacuous macro called after the title is set and before the listing
% starts. The user can modify it to, for example, add some explanatory
% text.
%    \begin{macrocode}
\newcommand*{\preglossaryhook}{}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ifnoglossaryintoc}
% \begin{macro}{\glossaryintoc}
% \begin{macro}{\noglossaryintoc}
% Flag and declarations to control whether or not the glossary
% title is added to the ToC. Default is to put the title
% in the ToC.
%    \begin{macrocode}
\newif\ifnoglossaryintoc
\newcommand*{\glossaryintoc}{\noglossaryintocfalse}
\newcommand*{\noglossaryintoc}{\noglossaryintoctrue}
  \glossaryintoc

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\glossarycolsep}
% \begin{macro}{\glossaryrule}
% When the glossary is two column these lengths control the
% column separation and the width of a rule between the columns.
%    \begin{macrocode}
\newdimen\glossarycolsep \glossarycolsep=35\p@
\newdimen\glossaryrule \glossaryrule=0\p@
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\glossaryspace}
% Vertical space between `letter blocks' in the glossary.
% Note that this is a macro, not a length.
%    \begin{macrocode}
\newcommand*{\glossaryspace}{%
    \par \vskip 1.0\onelineskip \@plus 5\p@ \@minus3\p@\relax}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\makeglossary}
% The preamble command to set up a glossary. Output is to the
% \file{\#1.glo} file. We need the \cs{providecommand} in case \cs{nofiles}
% has been called before the class. \cs{makeglossary} sets up several 
% file-specific macros.
%    \begin{macrocode}
\providecommand*{\makeglossary}{}
\renewcommand*{\makeglossary}[1][\jobname]{%
  \makememglossaryhook
  \@namedef{memglsact#1}{@}%           actual
  \@namedef{memglsnx#1}{}%             no ref
  \@namedef{memglsn#1}{\thepage}%      num  by page
  \@namedef{memglsnf#1}{|memjustarg}%  no special number format | emacs
  \if@filesw \expandafter\newwrite\csname #1memglofile\endcsname
    \expandafter\immediate\openout \csname #1memglofile\endcsname #1.glo\relax
    \typeout{Writing glossary file #1.glo }%
  \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\makememglossaryhook}
% A vacuous macro called at the start of the \cs{makeglossary} code.
% It is redefinable to do something useful.
%    \begin{macrocode}
\newcommand*{\makememglossaryhook}{}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\glossary}
% The user command for a raw glossary item. The full calling
% sequence looks like: \\
% \cs{glossary}\oarg{file}\parg{key}\marg{term}\marg{desc} \\
% but most is accomplished by lower level macros. It calls
% \cs{@glossary} to handle the first optional argument.
%    \begin{macrocode}
  \def\glossary{\@bsphack%
    \@ifnextchar [{\@glossary}{\@glossary[\jobname]}}%
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@glossary}
% \cs{@glossary}\oarg{file} handles the first of the \cs{glossary} optional
% arguments, even though the calling sequence looks like: \\
% \cs{@glossary}\oarg{file}\parg{key}\marg{term}\marg{desc}. \\
% It calls \cs{@@glossary} to handle the second optional argument
% and the rest.
%    \begin{macrocode}
\def\@glossary[#1]{%
  \@ifnextchar ({\@@glossary[#1]}{\@@glossary[#1]()}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@@glossary}
% The base macro for \cs{glossary}. Its real calling sequence is: \\
% \cs{@@glossary}\oarg{file}\parg{key}\marg{term}\marg{desc}. \\
% Provided the glossary output file has been set up it calls
% \cs{@wrglom@m} to write the data, otherwise it throws away its
% arguments.
%    \begin{macrocode}
\def\@@glossary[#1](#2)#3#4{%
  \@ifundefined{#1memglofile}{%
    \begingroup
    \@sanitize
    \endgroup
    \@esphack%
   }{%
    \def\memglofile{#1}%
    \begingroup
    \@sanitize
%    \end{macrocode}
% Use the correct key, \meta{key} if given, otherwise \meta{term}.
%    \begin{macrocode}
    \ifx\@empty#2\@empty
      \@wrglom@m{#3}{#3}{#4}%
    \else
      \@wrglom@m{#2}{#3}{#4}%
    \fi}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@wrglom@m}
% \cs{@wrglom@m}\marg{key}\marg{term}\marg{desc} writes its three arguments,
% plus the \meta{ref} and the \meta{num} to the \file{aux} file as the
% arguments to the \cs{@@wrglom@m} macro.
%    \begin{macrocode}
\newcommand{\@wrglom@m}[3]{%
  \protected@write\@auxout{}%
    {\string\@@wrglom@m{\memglofile}{#1}{#2}{#3}{\@nameuse{memglsnx\memglofile}}{\@nameuse{memglsn\memglofile}}}%
  \endgroup
  \@esphack}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@@wrglom@m}
% The calling sequence looks like: \\
% \cs{@@wrglom@m}\marg{file}\marg{key}\marg{term}\marg{desc}\marg{ref}\marg{num} \\
% but is actually really only \\
% \cs{@@wrglom@m}\marg{file} \\
% It saves the output file identifier in \cs{memglofile} and 
% \meta{file} as \cs{m@mgf}, then calls \cs{memwritetoglo}
% to handle the remaining `arguments'.
%    \begin{macrocode}
\newcommand{\@@wrglom@m}[1]{\begingroup
  \def\memglofile{\@nameuse{#1memglofile}}%
  \def\m@mgf{#1}%
  \@sanitize
  \memwritetoglo}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\memwritetoglo}
% \begin{macro}{\@ctualm@mwritetoglo}
% \cs{memwritetoglo}\marg{key}\marg{name}\marg{desc}\marg{ref}\marg{num}
% will, at an appropriate time write the raw glossary data to the
% appropriate \file{glo} file.
%
%    The \file{aux} file is read twice, once as one of the initial
% actions at the start of the \texttt{document} environment, and again
% at the end of the \texttt{document} environment. The raw glossary
% data must only be written once from the \file{aux} to the \file{glo} file.
% Initially \cs{memwritetoglo} is defined to do nothing, then, after the
% \file{aux} file has been read at the beginning is redefined to do
% its writing. 
%
% The Makeindex program expects its input to be like: \\
% \verb?\glosaryentry{key@data}{num}?
% Very cunningly the raw data is fed to the \file{glo}
% file looking like: \\
% \verb?\glossaryentry{key@{\memgloterm{term} \memglodesc{desc} \memgloref{ref}}{num}? \\
% which as far as Makeindex is concerned is simply: \\
% \verb?\glosaryentry{key@{data}}{num}? \\
% (note where all the braces are).
%
% 
% \changes{v3.7k}{2020/02/24}{Rewritten to use
% \cs{immediate@protected@write} instead, otherwise UTF8 may get
% written as latin1}
%    \begin{macrocode}
\newcommand{\memwritetoglo}[5]{\endgroup}
\newcommand{\@ctualm@mwritetoglo}[5]{%
  %\immediate\write \memglofile%
  \immediate@protected@write\memglofile{}%
        {\string\glossaryentry{#1\@nameuse{memglsact\m@mgf}
        {\string\memgloterm{#2}}{\string\memglodesc{#3}}
        {\string\memgloref{#4}}\@nameuse{memglsnf\m@mgf}}{#5}}%
  \endgroup}
\AtBeginDocument{%
  \let\memwritetoglo\@ctualm@mwritetoglo}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\changeglossactual}
% \begin{macro}{\changeglossref}
% \begin{macro}{\changeglossnum}
% \begin{macro}{\changeglossnumformat}
% There are internal macros that are file-dependant, their names
% being constructed from the file name plus a fixed name. The
% \cs{makeglossary} command initializes these but the user may well need
% to change them. In the macros below, \texttt{...actual} refers to the
% actual character in a Makeindex configuration file (default \texttt{@}),
% \texttt{...ref} to the \meta{ref} glossary argument, \texttt{...num}
% to the meta{num} argument (default \cs{thepage}) and \texttt{...numformat}
% to the Makeindex encapsulating command. Example uses are:
% \begin{verbatim}
% \changeglossactual[file]{?}
% \changeglossref[file]{\thepage}
% \changeglossnum[file]{\thesection}
% \changeglossnumref[file]{|textbf}
% \end{verbatim}
%    \begin{macrocode}
\newcommand*{\changeglossactual}[2][\jobname]{%
  \@namedef{memglsact#1}{#2}}
\newcommand*{\changeglossref}[2][\jobname]{%
  \@namedef{memglsnx#1}{#2}}
\newcommand*{\changeglossnum}[2][\jobname]{%
  \@namedef{memglsn#1}{#2}}
\newcommand*{\changeglossnumformat}[2][\jobname]{%
  \@namedef{memglsnf#1}{#2}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\glossitem}
% The final sorted glossary data is in the form: \\
% \cs{glossitem}\marg{term}\marg{desc}\marg{ref}\marg{num} \\
% The definition here does little.
%    \begin{macrocode}
\newcommand{\glossitem}[4]{#1 #2 #3 #4\par}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\memgloterm}
% \begin{macro}{\memglodesc}
% \begin{macro}{\memgloref}
% \begin{macro}{\memglonum}
% These are wrappers round the \meta{term}, \meta{desc}, \meta{ref} and
% \meta{num} elements in the final data. They are vacuous to start with.
%    \begin{macrocode}
\newcommand*{\memgloterm}[1]{#1}
\newcommand*{\memglodesc}[1]{#1}
\newcommand*{\memgloref}[1]{#1}
\newcommand*{\memglonum}[1]{#1}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\printglossary}
% \cs{printglossary}\oarg{file} inputs the glossary \file{gst} file.
%    \begin{macrocode}
\newcommand*{\printglossary}[1][\jobname]{\@input@{#1.gls}}

%    \end{macrocode}
% \end{macro}
%
%
%
%      
% \section{Notes/Marginalia}
%
%
% \subsection{A simple interface for specifying locations}
%
% \changes{v1.61803398d}{2010/01/25}{added}
%
% The \Lpack{memoir} class as of December 2009 supports \cs{marginpar},
% \cs{sidepar}, and \cs{sidebar} for placing information in a margin.
% The means of specifying in which margin the information should be put
% is different for each of these. Here a consistent location interface 
% is provided for all marginalia.
%
%
% \begin{macro}{\m@msetm@argin}
% \begin{macro}{\m@mm@argin}
% A workhorse macro for setting a margin placement code. The argument
% may be one of: left, right, outer, or inner, with \cs{m@mm@argin} defined
% as the corresponding codes of 0, 1, 2, or 3. An unkown argument is coded
% as a negative number.
%    \begin{macrocode}
\newcommand*{\m@msetm@argin}[1]{%
  \def\@tempa{#1}\def\@tempb{left}%
  \ifx\@tempa\@tempb
    \def\m@mm@argin{0}%
  \else
    \def\@tempb{right}%
    \ifx\@tempa\@tempb
      \def\m@mm@argin{1}%
    \else
      \def\@tempb{outer}%
      \ifx\@tempa\@tempb
        \def\m@mm@argin{2}%
      \else
        \def\@tempb{inner}%
        \ifx\@tempa\@tempb
          \def\m@mm@argin{3}%
        \else
          \def\m@mm@argin{-1}%
        \fi
      \fi
    \fi
  \fi}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\ifmemtortm}
% \begin{macro}{\memtortmtrue}
% \begin{macro}{\memtortmfalse}
% A flag set TRUE if the marginalia is to be moved to the right of the text
% and FALSE if it is to be moved to the left of the text. 
%    \begin{macrocode}
% MEM-TO-RighT-Margin
\newif\ifmemtortm
  \memtortmtrue
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\m@mwhich@margin}
% \cs{m@mwhich@margin}\marg{code} sets \cs{ifmemtortm} TRUE or FALSE depending
% on the value of \meta{code} (0 to 3), and other factors.
% \begin{description}
% \item[Two column document] If the first column, to the left, otherwise
%                            to the right, irrespective the document being
%                            one- or two-side.
% \item[One sided document] If code = 0 (left), to the left, otherwise 
%  (code = 1 (right), 2 (outer), 3 (inner)) to the right.
% \item[Two sided document] depends on whether a recto or verso page:
%    \begin{description}
%    \item[Recto (odd) page] right if code = 1 (right) or 2 (outer), otherwise
%                            left.
%    \item[Verso (even) page] left if code = 0 (left) or 2 (outer), otherwise
%                             right.
%    \end{description}
% \end{description}
%
% 
%    \begin{macrocode}
\newcommand*{\m@mwhich@margin}[1]{%
  \memtortmtrue
  \if@twocolumn
    \if@firstcolumn% left
      \memtortmfalse
    \else%           right
      \memtortmtrue
    \fi
  \else
    \if@twoside
      \checkoddpage
      \ifcase #1\relax% 0 left
        \memtortmfalse
      \or%                   1 right
        \memtortmtrue
      \or%                   2 outer
        \ifoddpage
          \memtortmtrue
        \else
          \memtortmfalse
        \fi
      \or%                 3 inner
        \ifoddpage
          \memtortmfalse
        \else
          \memtortmtrue
        \fi
      \fi% end ifcase
    \else%           oneside
      \ifnum #1=\z@% 0   left, all else right       
        \memtortmfalse
      \else
        \memtortmtrue
      \fi
    \fi% end if@twoside
  \fi}

%    \end{macrocode}
% \end{macro}
%
%
%    
% \subsection{Marginpars}
%
% A \cs{marginpar} is a kind of floating object --- you can't control
% exactly where it will go. There is one problem with the kernel
% definition of \cs{marginpar} in that sometimes a \cs{marginpar} may
% end up on the wrong side of the page. The following is an attempt
% to fix that using the odd/even page check provided as part of
% the class.
% 
% \begin{macro}{\@addmarginpar}
% The part of the code for \cs{marginpar} that deals with deciding which
% side of the page it should be printed on is \cs{@addmarginpar}, buried
% away in the kernel's \texttt{output} routine. A couple of minor changes are made
% to the kernel code. The first is at the beginning where I have added
% the \cs{checkoddpage} page checking code.
% \changes{v1.618033988d}{2010/02/26}{fixed twoside -> left marrgin
% bug, reported by Frank Wikstr\"om, on private email}
% In the new margin placement syntax, there is a new syntax: always
% left, in twoside mode. This cannot be implemented using the normal
% marginpar placement controls, so we have to add our own.
%    \begin{macrocode}
\def\@addmarginpar{%
    \checkoddpage
%    \end{macrocode}
% Continue with the kernel code. The twocolumn stuff in the new syntax
% scheme is the same as in the kernel.
%    \begin{macrocode}
    \@next\@marbox\@currlist{\@cons\@freelist\@marbox
    \@cons\@freelist\@currbox}\@latexbug\@tempcnta\@ne
    \if@twocolumn
        \if@firstcolumn \@tempcnta\m@ne \fi
    \else
%    \end{macrocode}
% \changes{v1.618033988d}{2010/02/26}{added as a part of the above
% mentioned fix}
% Here we add the new stuff. We make use of the fact that we have
% hidden all the page checking in \verb?\m@mwhich@margin?, and we only
% fire it of if we know \verb?\marginparmargin? have been used (via
% \verb?\ifm@msetmp?). 
%    \begin{macrocode}
      \ifm@msetmp%
        % \@tempcnta > 0 => right side of page
        % \@tempcnta < 0 => left side of page
        \m@mwhich@margin{\m@mmpar@margin}% set left or right margin
        \ifmemtortm%
          \@tempcnta\@ne\relax%
         \else% 
          \@tempcnta\m@ne\relax%
        \fi%
      \else%
        \if@mparswitch
%    \end{macrocode}
% The next line, reading \\
% \verb?\ifodd\c@page \else\@tempcnta\m@ne \fi? \\
% is where the odd/even page checking is done in the kernel code. I
% replace it with my code, and then continue with the kernel.
%    \begin{macrocode}
          \ifoddpage \else \@tempcnta\m@ne \fi%
        \fi%
        \if@reversemargin \@tempcnta -\@tempcnta \fi%
      \fi%
    \fi%
    \ifnum\@tempcnta <\z@  \global\setbox\@marbox\box\@currbox \fi
    \@tempdima\@mparbottom
    \advance\@tempdima -\@pageht
    \advance\@tempdima\ht\@marbox
    \ifdim\@tempdima >\z@
%    \end{macrocode}
% The next line in the kernel reads: \\
% \verb?\@latex@warning@no@line {Marginpar on page \thepage\space moved}? \\
% I have changed the warning message to give the user an indication
% of the severity of the move. Then follow the kernel on to the end.
%    \begin{macrocode}
      \@latex@warning@no@line {Marginpar on page 
                               \thepage\space moved by \the\@tempdima}%
    \else
      \@tempdima\z@
    \fi
    \global\@mparbottom\@pageht
    \global\advance\@mparbottom\@tempdima
    \global\advance\@mparbottom\dp\@marbox
    \global\advance\@mparbottom\marginparpush
    \advance\@tempdima -\ht\@marbox
    \global\setbox \@marbox
                   \vbox {\vskip \@tempdima
                          \box \@marbox}%
    \global \ht\@marbox \z@
    \global \dp\@marbox \z@
    \kern -\@pagedp
    \nointerlineskip
    \hb@xt@\columnwidth
      {\ifnum \@tempcnta >\z@
          \hskip\columnwidth \hskip\marginparsep
       \else
          \hskip -\marginparsep \hskip -\marginparwidth
       \fi
       \box\@marbox \hss}%
    \nointerlineskip
    \hbox{\vrule \@height\z@ \@width\z@ \@depth\@pagedp}%
}

%    \end{macrocode}
% \end{macro}
%
% \subsubsection{Marginpar -- margin interface}
%
% The `standard' method of specifying the desired margin for a \cs{marginpar}
% consists of the two macros \cs{normalmarginpar} and \cs{reversemarginpar}, 
% whose effects depend on whether the document is one- or two-sided, whether
% the page is recto or verso, and if it is set in one- or two-columns.
%
% \begin{macro}{\ifm@msetmp}
% \begin{macro}{m@msetmptrue}
% \begin{macro}{m@msetmpfalse}
% TRUE if the macro \cs{marginparmargin} has been called.
%    \begin{macrocode}
\newif\ifm@msetmp
  \m@msetmpfalse
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\marginparmargin}
% \begin{macro}{\m@mmpar@margin}
% The user command for specifying the desired margin for \cs{marginpar}s.
% The code is stored as \cs{m@mmpar@margin}, and \cs{setmpbools} is called to
% convert to the regular \cs{marginpar} booleans.
%    \begin{macrocode}
\newcommand*{\marginparmargin}[1]{%
  \m@msetmptrue
  \m@msetm@argin{#1}%
  \ifnum\m@mm@argin<\z@
    \@memwarn{Bad \string\marginparmargin\space argument `#1'\MessageBreak
              set to `outer'}%
    \gdef\m@mmpar@margin{2}%   set as outer
  \else
    \global\let\m@mmpar@margin\m@mm@argin
  \fi
  \setmpbools}

%    \end{macrocode}
% \changes{v3.6k}{2013/05/14}{Added default \cs{m@mmpar@margin}}
%    \begin{macrocode}
\if@twocolumn\else
  \if@twoside
    \def\m@mmpar@margin{2}
  \else
    \def\m@mmpar@margin{1}
  \fi
\fi

%    \end{macrocode}
% 
%
% \end{macro}
% \end{macro}
%
% \begin{macro}{\setmpbools}
% Given \cs{m@mmpar@margin}, \cs{setmpbools} sets the corresponding 
% \cs{marginpar} location booleans.
%    \begin{macrocode}
\newcommand*{\setmpbools}{%
  \if@twoside
    \@mparswitchtrue
  \else
    \@mparswitchfalse
  \fi
  \ifcase\m@mmpar@margin\relax% 0 left
    \@reversemargintrue%  \sideparswitchfalse \reversesidepartrue
  \or%                    1 right
    \@reversemarginfalse% \sideparswitchfalse \reversesideparfalse
  \or%                    2 outer
    \@reversemarginfalse% \sideparswitchtrue \reversesideparfalse
  \or%                    3 inner
    \@reversemargintrue% \sideparswitchtrue \reversesidepartrue
  \fi}

%    \end{macrocode}
% \end{macro}
%
%    \begin{macrocode}
\newcommand*{\m@msetmpcodes}{%
  \if@mparswitch%  2 sided
    \if@reversemargin% inner
      \def\m@mmpar@margin{3}%
    \else% outer
      \def\m@mmpar@margin{2}%
    \fi
  \else% 1 sided
    \if@reversemargin% left
      \def\m@mmpar@margin{0}%
    \else% right
      \def\m@mmpar@margin{1}%
    \fi
  \fi}

%    \end{macrocode}
%
% \subsection{A fixed marginpar}
%
%
% Introduce a non-floating marginpar.
% \changes{v1.4}{2003/11/22}{Added \cs{sidepar} and supports for a fixed 
%                            marginpar (from patch v1.8)}
%
% \begin{macro}{\parnopar}
% From \theTeXbook{} Exercise 14.15. It creates an `invisible' end/start paragraph,
% and may be used for getting \TeX{} to try a pagebreak.
% 
% Roman Eisle (email 2008/09/05) found a problem with the original
% definition as its effects continued on: \\
% \verb?\newcommand{\parnopar}{\parfillskip=0pt\par\parskip=0pt\noindent}? \\
% and he supplied the fix used below.
%
% \changes{v1.6180339c}{2008/12/24}{Changed \cs{parnopar} to limit its effect
% to a single instance}
% \changes{v3.6e}{2010/08/17}{made \cs{parnopar} sit inside a group}
%    \begin{macrocode}
\newcommand*{\parnopar}{{\parfillskip=0pt\par\parskip=0pt\noindent}} 

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\ifreversesidepar}
% \begin{macro}{\ifsideparswitch}
% \changes{v1.61803398d}{2010/01/25}{Added footnote explaining the default}
% Analogues of \cs{marginpar} controls.\footnote{Note that for some
% now forgotten reason the default placement of the \cs{sidepar} is
% reversed in comparison to say \cs{marginpar}. As not to change
% existing documents, we have left the default like this.}
%    \begin{macrocode}
\newif\ifreversesidepar
%  \reversesideparfalse
  \reversesidepartrue
\newif\ifsideparswitch
  \sideparswitchfalse
\if@twoside \sideparswitchtrue \fi

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \changes{v1.61803398d}{2010/01/25}{Added}
% \begin{macro}{\ifm@msetsp}
% \begin{macro}{\m@msetsptrue}
% \begin{macro}{\m@msetspfalse}
%    \begin{macrocode}
%% true if \sideparmargin used
\newif\ifm@msetsp
  \m@msetspfalse
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \changes{v1.61803398d}{2010/01/25}{Added}
% \begin{macro}{\sideparmargin}
% \begin{macro}{\m@mspar@margin}
% User command for specifing the margin for \cs{sidepar}s.
% The numeric code is stored in \cs{m@mspar@margin}.
%    \begin{macrocode}
\newcommand*{\sideparmargin}[1]{%
  \m@msetsptrue
  \m@msetm@argin{#1}%
  \ifnum\m@mm@argin<\z@
    \@memwarn{Bad \string\sideparmargin\space argument `#1'\MessageBreak
              set to `outer'}%
    \gdef\m@mspar@margin{2}%   set as outer
  \else
    \global\let\m@mspar@margin\m@mm@argin
  \fi}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \changes{v1.61803398d}{2010/01/25}{Added}
% \begin{macro}{\m@msidepar@left}
% \begin{macro}{\m@msidepar@right}
% Move a \cs{sidepar} into the left/right margin.
%    \begin{macrocode}
\newcommand*{\m@msidepar@left}{%
  \@tempdimc\marginparwidth
  \advance\@tempdimc\marginparsep
  \kern-\@tempdimc}
\newcommand*{\m@msidepar@right}{%
  \@tempdimc\columnwidth
  \advance\@tempdimc\marginparsep
  \kern\@tempdimc}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \changes{v1.61803398d}{2010/01/25}{Added}
% \begin{macro}{\setspbools}
% Given the \cs{m@mspar@margin} code, calculates the corresponding
% \cs{sidepar} location booleans.
%    \begin{macrocode}
\newcommand*{\setspbools}{%
    \ifcase\m@mspar@margin\relax% 0 left
      \sideparswitchfalse \reversesidepartrue
    \or%                    1 right
      \sideparswitchfalse \reversesideparfalse
    \or%                    2 outer
      \sideparswitchtrue \reversesideparfalse
    \or%                    3 inner
      \sideparswitchtrue \reversesidepartrue
    \fi}

%    \end{macrocode}
% \end{macro}
% \changes{v1.61803398d}{2010/01/25}{Added}
% \begin{macro}{\setspcode}
% Given the \cs{sidepar} location booleans, sets up the corresponding
% \cs{m@mspar@margin} numeric codes.
%    \begin{macrocode}
\newcommand*{\setspcode}{%
  \ifsideparswitch
    \ifreversesidepar
      \def\m@mspar@margin{3}% inner
    \else
      \def\m@mspar@margin{2}% outer
    \fi
  \else
    \ifreversesidepar
      \def\m@mspar@margin{0}% left
    \else
      \def\m@mspar@margin{1}% right
    \fi
  \fi}

%    \end{macrocode}
% \end{macro}
% \changes{v1.61803398d}{2010/01/25}{Added}
% \begin{macro}{\sideparfont}
% \begin{macro}{\sideparform}
% The font to be used for \cs{sidepar}s and the alignment for it.
% \changes{v1.61803398d}{2010/02/04}{Changed default font}
% \changes{v1.61803398d}{2010/02/05}{added \cs{sideparform}} 
% The \cs{sideparform} holds code that will set the text flush against
% the edge of the text.\footnote{One might consider redefining this
% using the \cs{RaggedRight} and \cs{RaggedLeft} macros from the
% ragged2e package.}
%    \begin{macrocode}
\newcommand*{\sideparfont}{\normalfont\normalsize}
\newcommand*{\sideparform}{\ifmemtortm\raggedright\else\raggedleft\fi}
%    \end{macrocode}
% \end{macro}
% \end{macro}

%
% \begin{macro}{\sidepar}
% \begin{macro}{\@sidepar}
% \begin{macro}{\sideparvshift}
% \cs{sidepar}\oarg{left}\marg{right} (per \cs{marginpar}).
% Sidepars had a nasty habit of moving up or down depending on whether 
% characters in the sidepar and the main text line have ascenders and/or 
% descenders. The length \cs{sideparvshift} was provided to
% enable adjustments. This is Dan Luecking's modified version of my
% original code  
% (CTT \textit{Re: sidepars drift up a point}, 2006/04/11) which does a much
% better job,
% and the default for \cs{sideparvshift} is now 0pt.
% \changes{v1.61803}{2008/01/30}{Fixed \cs{sidepars} from moving up and down
%     (mempatch v4.5)}
% \changes{v1.61803}{2008/01/30}{Normalised font in \cs{@sidepar} 
%          (mempatch v4.9)}
% \changes{v1.61803398d}{2010/01/25}{\cs{@sidepar} changed to fit the
% interface just added}
% \changes{v1.61803398d}{2010/02/05}{added \cs{sideparform}}
% \changes{v3.6h}{2010/10/29}{The inserted text should have the same
% baseline stretch as the rest of the page notes.}
%    \begin{macrocode}
\newcommand{\sidepar}{\@dblarg{\@sidepar}}
\long\def\@sidepar[#1]#2{\leavevmode\@bsphack\strut\vadjust{%
  \checkoddpage
  \ifm@msetsp% \sideparmargin used
%%%%    \setspbools
  \else% \sideparmargin not used, set the \m@mspar@margin code
    \setspcode
  \fi
  \rlap{\kern-\parindent
    \m@mwhich@margin{\m@mspar@margin}% set left or right margin
    \ifmemtortm
      \m@msidepar@right
    \else
      \m@msidepar@left
    \fi
  \setbox0=\vtop to 0pt{%
    \begin{minipage}[t]{\marginparwidth}%
      \def\baselinestretch{\m@m@footnote@spacing}%
      \sideparform\sideparfont%
      \ifmemtortm #2\else #1\fi
    \end{minipage}%
    \vss}%
  \vtop to 0pt{\kern\sideparvshift% default should be 0pt
    \kern-\dp\strutbox
    \kern-\ht0
    \box0 \vss}}}%
  \@esphack}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% Vertical shift for sidepar to align with text line
%    \begin{macrocode}
\newlength{\sideparvshift}
\setlength{\sideparvshift}{0pt}
%%%%  \setlength{\sideparvshift}{-2.08ex}% seems to work for all font sizes

%    \end{macrocode}
% \end{macro}
%
%
% \subsection{Sidebars}
%
% \changes{v1.1}{2002/03/19}{Added experimental code for sidebars}
%
% On 2002/10/22 Donald Arseneau posted the following code to \ctt{} for adding
% sidebars to plain TeX.
% \begin{verbatim}
% \newinsert\sideins
% \skip\sideins=0pt
% \count\sideins=0
% \dimen\sideins=2in
% 
% \def\sidebarvsep{25pt}
% \def\sidebarhsep{15pt}
% 
% \let\mainpagecontents\pagecontents
% 
% \def\sidecontents{%
%   \ifvoid\sideins\else
%       {\advance\hsize\sidebarhsep
%        \moveright\hsize \vtop to0pt{%
%        \vskip-\sidebarvsep \vskip\topskip % offset by difference
%        \unvbox\sideins \vss}%
%     }\fi}
% \def\pagecontents{\sidecontents\mainpagecontents}
% \long\def\sidebar#1{
%   \insert\sideins{%
%     \splittopskip\sidebarvsep\relax
%     \hsize 1.5in \rightskip=0pt plus 20pt \it
%     \noindent \vbox to \sidebarvsep{}\ignorespaces #1%
%     \ifhmode \unskip\strut\fi \par
%    }%
% }
% 
% \end{verbatim}
%
% The following started off (2002/03/19) as my attempt to rewrite the above 
% into a form suitable for LaTeX, and this class in particular.
%
% Donald Arseneau came up with some improvements to my sidebar code. 
% The impetus
% for this came from a CTT thread, \textit{whitespace after my command}, 
% 2006/11/30 and earlier. In email to me on 2006/11/30 he said:
% \begin{quotation}
%    For \Lpack{memoir} \cs{sidebar}, it seems the rules are expanding
% to fill the space for the sidebar, so here is my suggested change
% to \cs{sidecontents}.
%
%    It occurs to me that a separate \cs{sidetsep} (or \cs{sidetopsep})
% would be more valuable than having an explicit 1\cs{onelineskip}.
%
%   I grouped common code into two macros, and altered \cs{sidebarform} too.
% \end{quotation}
%
% Since then we have been going back and forth, with the result that
% practically all the complex code is Donald's.
% \changes{v1.61803}{2008/01/30}{Major rewrite of \cs{sidebar} code
%                 (mempatch v4.6 and v4.9)}
%
%
% \begin{macro}{\sideins}
% Create a new insert called \cs{sideins}, which also creates a corresponding
% skip, count, dimen, and box. \\
% \verb?\skip\sideins? is the extra vertical space to allow on the page for 
% the insert, \\
% \verb?\count\sideins? is the magnification factor for page breaking, \\
% \verb?\dimen\sideins? is the maximum insertion size (height) per page, \\
% and the inserted material will be in \verb?\box\sideins? when a page is output.
%    \begin{macrocode}
\newinsert\sideins
  \skip\sideins=0pt
  \count\sideins=0

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sidebartopsep}
% Separation at the top of a sidebar.
%    \begin{macrocode}
\newlength{\sidebartopsep}
  \setlength{\sidebartopsep}{0pt}
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\setsidebarheight}
% The macro \cs{setsidebarheight}\marg{length} sets the total
% height of sidebars on a page to \meta{length}.
% This is an interface for controlling \verb?\dimen\sideins? properly,
% taking account of \cs{topskip} and the sidebar font size (and therefore
% should be invoked \emph{after} declaring \cs{sidebarfont}).
%
%    Note that \cs{sidebartopsep} is \emph{not} included as part of the
% allocated height.
%    \begin{macrocode}
\newcommand{\setsidebarheight}[1]{%
  \setlength{\dimen\sideins}{#1}%
  \advance\dimen\sideins-\topskip
  \advance\dimen\sideins\ht\strutbox}

%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\sidebarhsep}
% \begin{macro}{\sidebarvsep}
% \begin{macro}{\sidebarwidth}
% The length \cs{sidebarhsep} is the gap between the typeblock and the sidebar.
% \cs{sidebarvsep} is the vertical gap between sidebars on a page.
% The maximum number of sidebar lines on a page is 
% \verb?1 + (\dimen\sideins - \sidebarvsep)?, assuming \verb?\dimen\sideins?
% is defined in terms of \cs{onelineskip}.
% The width of the sidebar is \cs{sidebarwidth}.
%    \begin{macrocode}
\newlength{\sidebarhsep}
\newlength{\sidebarvsep}
\newlength{\sidebarwidth}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\sidebarfont}
% The font for typesetting the contents of a sidebar.
% \changes{v1.61803398d}{2010/02/05}{Added a default for \cs{sidebarfont}}
%    \begin{macrocode}
\newcommand{\sidebarfont}{\normalfont\normalsize}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\setsidebars}
% \cs{setsidebars}\marg{hsep}\marg{width}\marg{vsep}\marg{topsep}\marg{font}\marg{height}
% sets the main \cs{sidebar} parameters. A \verb?*? argument means leave the
% setting as is.
% \changes{v1.61803}{2008/01/30}{Added \cs{setsidebars} (mempatch v4.6)}
%    \begin{macrocode}
\newcommand*{\setsidebars}[6]{%
  \nametest{#1}{*}\ifsamename\else
    \setlength{\sidebarhsep}{#1}\@memznegtest{\sidebarhsep}%
  \fi
  \nametest{#2}{*}\ifsamename\else
    \setlength{\sidebarwidth}{#2}\@memznegtest{\sidebarwidth}%
  \fi
  \nametest{#3}{*}\ifsamename\else
    \setlength{\sidebarvsep}{#3}\@memnegtest{\sidebarvsep}%
  \fi
  \nametest{#4}{*}\ifsamename\else
    \setlength{\sidebartopsep}{#4}%
  \fi
  \nametest{#5}{*}\ifsamename\else
    \def\sidebarfont{#5}%
  \fi
  \nametest{#6}{*}\ifsamename\else
    \setsidebarheight{#6}%
    \ifdim\dimen\sideins>\z@\else
%%%%      \@memerror{\protect\sidebarheight\space is zero or negative}{\@ehd}%
      \@memwarn{\protect\sidebarheight\space is zero or negative}%
    \fi
  \fi}
\setsidebars{\marginparsep}%          sidebarhsep
            {\marginparwidth}%        sidebarwidth
            {\onelineskip}%           sidebarvsep
            {0pt}%                    sidebartopsep
            {\normalsize\normalfont}% sidebarfont
            {\textheight}%            sidebarheight

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\sidebarform}
% \cs{sidebarform} sets the `raggedness' in a sidebar. The current definition
% is less ragged than \cs{raggedright}. Examples: 
% \begin{verbatim}
%  for flushleftright \renewcommand{\sidebarform}{}
%  for raggedleft     \renewcommand{\sidebarform}{\raggedleft}
% \end{verbatim}
% \changes{v1.4}{2003/11/22}{Added \cs{sidebarform} (from patch v1.5)}
% \changes{v1.61803398}{2009/07/18}{Added bidi support to \cs{sidebarform}}
% \changes{v1.61803398d}{2010/02/05}{changed to make the text flush
% against the text}
%    \begin{macrocode}
\newcommand{\sidebarform}{%\rightskip=\z@ \@plus 2em}
  %\memRTLrightskip=\z@ \@plus 2em
  \ifmemtortm\raggedright\else\raggedleft\fi%
  % \ifmemtortm\memRTLrightskip=\z@ \@plus 2em\else\memRTLleftskip=\z@ \@plus 2em\fi
}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ifsidebaroneside}
% Flag for oneside.
% \changes{v1.61}{2004/04/05}{Added \cs{ifsidebaroneside}}
% \changes{v1.61803398d}{2010/02/07}{flaged as deprecated, the macro
% is not used at all, kept just to ensure that documents does not
% crash, TO BE DELETED}
%    \begin{macrocode}
\newif\ifsidebaroneside
  \if@twoside\sidebaronesidefalse\else\sidebaronesidetrue\fi

%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\sidebarmargin}
% \begin{macro}{\m@msidebar@margin}
% \changes{v1.61803398d}{2010/02/07}{removed the mention of
% \cs{sidebaroneside}, as it is deprecated}
% \cs{sidebarmargin}\marg{side} sets the side where sidebars will be printed.
% Valid arguments are: left, right, outer, or inner.
%
% \changes{v1.618}{2005/09/03}{Added \cs{sidebarmargin} (mempatch v3.2)}
% \changes{v1.61803398d}{2010/01/25}{Changed to match new general interface}
%    \begin{macrocode}
\newcommand*{\sidebarmargin}[1]{%
  \m@msetm@argin{#1}%
  \ifnum\m@mm@argin<\z@
    \@memwarn{Bad \string\sidebarmargin\space argument `#1'\MessageBreak
              set to `outer'}%
    \gdef\m@msidebar@margin{2}%   set as outer
  \else
    \global\let\m@msidebar@margin\m@mm@argin
  \fi}
%%%% default outer
\gdef\m@msidebar@margin{2}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\m@sideb@left}
% \begin{macro}{\m@sideb@right}
% Code used later to put sidebars into the desired margin.
% \changes{v1.61803}{2008/01/30}{Added \cs{m@sideb@left} and \cs{m@sideb@right}
%                    (mempatch v4.6)}
%    \begin{macrocode}
\newcommand*{\m@sideb@left}{%
  \@tempdimc \sidebarwidth
  \advance\@tempdimc\sidebarhsep
  \kern-\@tempdimc}
\newcommand*{\m@sideb@right}{%
  \@tempdimc \columnwidth%  or \hsize
  \advance\@tempdimc\sidebarhsep
  \kern\@tempdimc}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\sidecontents}
% This locates the horizontal position of a sidebar. On two column
% pages it is put in the margin next to the column where \cs{sidebar}
% is called, otherwise it is put in the outer (foredge) margin, except
% for the oneside option when it is put into the right hand margin.
% This can be separately controlled via \cs{ifsidebaroneside}.
% Emanuele Vicentini (private email, 2004/04/05)
% suggested to code for the oneside option.
% \changes{v1.61}{2004/04/05}{Changed \cs{sidecontents} for oneside option} 
% \changes{v1.618}{2005/09/03}{Changed \cs{sidecontents} for \cs{sidebarmargin}}
% \changes{v1.61803}{2008/01/30}{Modified \cs{sidecontents} (mempatch v4.6)}
% \changes{v1.61803398d}{2010/01/15}{changed to use
% \cs{m@mwhich@margin} for determining wheter to move right ot left}
%    \begin{macrocode}
\newcommand{\sidecontents}{\hbox to \z@{%
  \m@mwhich@margin{\m@msidebar@margin}%
  \ifmemtortm
    \m@sideb@right
  \else
    \m@sideb@left
  \fi
%    \end{macrocode}
% DA and I have gone to and fro on the next bit of code trying to get
% the top alignment correct. 
% \begin{verbatim}
% \vtop to0pt{%
%    \vskip\onelineskip
%    \unvbox\sideins \vss}%
% \end{verbatim}
% DA has the last word.
%    \begin{macrocode}
  \vtop to0pt{%
    \normalsize\normalfont\sidebarfont% select font so we know the strut size
    \vskip\topskip \vskip-\ht\strutbox
    \vskip\sidebartopsep% extra vertical shift
    \unvbox\sideins \vss}%
  \hss}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sidebar}
% \cs{sidebar}\marg{text} puts \meta{text} into a sidebar.
%
% Florence Henry in the thread \textit{Of memoir, sidebar, and
% justification}, 2003/04/02, pointed out that \texttt{itemize} in a
% \cs{sidebar} could overflow. DA gave the solution hint.
%
% DA says that having stacked insertions position properly is difficult.
% Here he uses the size of the strut to regulate both the height and the
% depth of each insertion (much as for footnotes). The following is his
% code and commentary.
% \changes{v1.4}{2003/11/22}{Revised \cs{sidebar}}
% \changes{v1.61803}{2008/01/30}{DA's rewrite of \cs{sidebar} (mempatch v4.6)}
%    \begin{macrocode}
\newcommand{\sidebar}[1]{%
  \insert\sideins{%
%    \end{macrocode}
% Begin the insertion with settings. The height of the strut box
% (dependant on the font) will determine the top alignment both initially
% and after a page break. The setting for maximum depth does not control
% anything; see the code further on instead.
% \changes{v1.61803398d}{2010/02/05}{removed
% \cs{normalfont}\cs{normalsize}, as these are now in the \cs{sidebarfont}}
% \changes{v3.6h}{2010/10/29}{the text should have the same baseline
% stretch as the rest of the page notes.}
%    \begin{macrocode}
    \hsize\sidebarwidth
    \@parboxrestore
    \def\baselinestretch{\m@m@footnote@spacing}%
%    \end{macrocode}
% \changes{v1.61803398d}{2010/02/05}{Added margin placement check
% inside \cs{sidebar}}
% Even though the margin placement is handled inside
% \cs{sidecontents}, there are some timming issues such that
% \cs{ifmemtortm} is executed too late for \cs{sidebar}s internals to
% make use of it. Fixed by adding the margin check to \cs{sidebar} as well.
%    \begin{macrocode}
    \m@mwhich@margin{\m@msidebar@margin}%    
    \sidebarform\sidebarfont
    \splittopskip=\ht\strutbox
    \splitmaxdepth=\dp\strutbox % doesn't do anything useful
%    \end{macrocode}
% Allow a free split at the top (so this whole insertion moves
% to the next page if it does not fit).
%    \begin{macrocode}
    \allowbreak
%    \end{macrocode}
% Control the (vertical) positioning of non-split entries. Footnotes (and
% previous versions of \cs{sidebar}) us a strut at the beginning of the text,
% but we will allow a baseline-skip to perform the same function. This
% method also introduces a \cs{parskip} when the paragraph begins, so we
% counteract that. (The problem with an initial strut is that it messes'
% up entries that begin with vertical space.)
%    \begin{macrocode}
    \prevdepth=\dp\strutbox    % supersedes a "top-strut"
    \vskip-\parskip
%    \end{macrocode}
% Now the user's sidebar entry:
%    \begin{macrocode}
    #1%
%    \end{macrocode}
% If the entry ended still in a paragraph, take the chance to insert a
% final strut; then end the paragraph.
%    \begin{macrocode}
    \ifvmode\else
      \unskip\@finalstrut\strutbox
    \fi\par
%    \end{macrocode}
% Explicitly force the effect of \cs{maxdepth} (\cs{splitmaxdepth}),
% but using the depth of the strut in the r\^{o}le of \cs{maxdepth}.
%    \begin{macrocode}
    \ifdim\prevdepth>\dp\strutbox \prevdepth=\dp\strutbox \fi
%    \end{macrocode}
% Now control how adjacent entries abut (whether or not a final strut got 
% inserted) and how an entry fits at the bottom of the page. Use \cs{vskip}s
% to move from the text bottom to where a strut would bottom out,
% but insert an allowed breakpoint at the baseline position
% (so that the entry baseline may match the page's baseline). Finally
% insert the extra separation between entries.
%    \begin{macrocode}
    \ifdim\prevdepth>99\p@
      \nobreak
      \vskip-\prevdepth
      \allowbreak
      \vskip\dp\strutbox
    \fi
    \vskip\sidebarvsep}}

%    \end{macrocode}
% \end{macro}
%
%
% \subsection{Footnotes}
%
%    For my reference, in case I want to fiddle with it even more
% than I have already done so, here is the kernel code (from \file{ltfloat.dtx}) 
% for footnotes.
% \DescribeMacro{\footins}
% The insert for footnotes.
% \begin{verbatim}
% \newinsert\footins
%   \skip\footins=\bigskipamount
%   \count\footins=1000
%   \dimen\footins=8in
% \end{verbatim}
%
% \DescribeMacro{\footnoterule}
% Draws the rule separating footnotes from the main text. It is executed
% after a \cs{vspace} of \verb?\skip\footins? and should take no vertical
% space.
% \begin{verbatim}
% \def\footnoterule{\kern-3\p@ \hrule \@width 2in \kern 2.6\p@}
%
% \@definecounter{footnote}
%   \def\thefootnote{\@arabic\c@footnote}
% \@definecounter{mpfootnote}
%   \def\thempfootnote{\itshape\@alph\c@mpfootnote}
% \end{verbatim}
%
% \DescribeMacro{\@makefnmark}
% Generates the footnote marker from \cs{@thefnmark}.
% \begin{verbatim}
% \def\@makefnmark{\hbox{\@textsuperscript{\normalfont\@thefnmark}}}
%
% \DeclareRobustCommand*\textsuperscript[1]{%
%    \@textsuperscript{\selectfont#1}}
% \def\@textsuperscript#1{%
%    {\m@th\ensuremath{^{\mbox{\fontsize\sf@size\z@#1}}}}}
%
% \newdimen\footnotesep
% \end{verbatim}
%
% \DescribeMacro{\footnote}
% \cs{footnote}\oarg{num}\marg{text} is what the user uses for footnoting.
% It defines \cs{@thefnmark} and calls \cs{@footnotemark} and 
% \cs{@footnotetext} to do the work.
% \begin{verbatim}
% \def\footnote{\@ifnextchar[\@xfootnote{\stepcounter\@mpfn
%   \protected@xdef\@thefnmark{\thempfn}%
%   \@footnotemark\@footnotetext}}
% \end{verbatim}
%
% \DescribeMacro{\@xfootnote}
% Handles the optional \meta{num} argument to \cs{footnote}.
% It defines \cs{@thefnmark} and calls \cs{@footnotemark} and 
% \cs{@footnotetext} to do the work.
% \begin{verbatim}
% \def\@xfootnote[#1]{%
%   \begingroup
%     \csname c@\@mpfn\endcsname #1\relax
%     \unrestored@protected@xdef\@thefnmark{\thempfn}%
%   \endgroup
%   \@footnotemark\@footnotetext}
% \end{verbatim}
%
% \DescribeMacro{\@footnotetext}
% \cs{@footnotetext}\marg{text} sets up for typeseting the footnote 
% (at the bottom of the page). It calls \cs{@makefntext}\marg{text}
% to actually do the typesetting (\cs{@makefntext} has to be supplied
% by a class or package).
% \begin{verbatim}
% \long\def\@footnotetext#1{%
%   \insert\footins{%
%     \reset@font\footnotesize
%     \interlinepenalty\interfootnotelinepenalty
%     \splittopskip\footnotesep
%     \splitmaxdepth \dp\strutbox \floatingpenalty \@MM
%     \hsize\columnwidth \@parboxrestore
%     \def\@currentcounter{footnote}% added later
%     \protected@edef\@currentlabel{%
%       \csname p@footnote\endcsname\@thefnmark}%
%     \color@begingroup
%       \@makefntext{%
%         \rule\z@\footnotesep\ignorespaces#1\@finalstrut\strutbox}%
%     \color@endgroup}}
% \end{verbatim}
%
% \DescribeMacro{\footnotemark}
% \cs{footnotemark}\oarg{num} the user uses this to produce just a 
% footnote mark in the text.
% \begin{verbatim}
% \def\footnotemark{%
%    \@ifnextchar[\@xfootnotemark
%      {\stepcounter{footnote}%
%       \protected@xdef\@thefnmark{\thefootnote}%
%       \@footnotemark}}
% \end{verbatim}
%
% \DescribeMacro{\@xfootnotemark}
% Handles the optional \meta{num} argument to \cs{footnotemark}.
% \begin{verbatim}
% \def\@xfootnotemark[#1]{%
%    \begingroup
%      \c@footnote #1\relax
%      \unrestored@protected@xdef\@thefnmark{\thefootnote}%
%    \endgroup
%    \@footnotemark}
% \end{verbatim}
%
% \DescribeMacro{\@footnotemark}
% Typesets the mark in the main text, via \cs{@makefnmark}.
% \begin{verbatim}
% \def\@footnotemark{%
%    \leavevmode
%    \ifhmode\edef\@x@sf{\the\spacefactor}\nobreak\fi
%    \@makefnmark
%    \ifhmode\spacefactor\@x@sf\fi
%    \relax}
% \end{verbatim}
%
% \DescribeMacro{\footnotetext}
% \cs{footnotetext}\oarg{num}\marg{text} is user view for creating a footnote
% without a marker in the main text.
% \begin{verbatim}
% \def\footnotetext{%
%    \@ifnextchar [\@xfootnotenext
%       {\protected@xdef\@thefnmark{\thempfn}%
%       \@footnotetext}}
% \end{verbatim}
%
% \DescribeMacro{\@xfootnotetext}
% Handles the optional \meta{num} argument to \cs{footnotetext}.
% \begin{verbatim}
% \def\@xfootnotenext[#1]{%
%   \begingroup
%     \csname c@\@mpfn\endcsname #1\relax
%     \unrestored@protected@xdef\@thefnmark{\thempfn}%
%   \endgroup
%   \@footnotetext}
% \end{verbatim}
%
% \DescribeMacro{\@mpfn}
% \DescribeMacro{\thempfn}
% \begin{verbatim}
% \def\@mpfn{footnote}
% \def\thempfn{\thefootnote}
% \end{verbatim}
%
% And from \file{ltboxes.dtx} for the \texttt{minipage} environment. 
%
% \DescribeMacro{\@mpfn}
% \DescribeMacro{\thempfn}
% \DescribeMacro{\@footnotetext}
% When setting up
% the environment, it includes:
% \begin{verbatim}
% \def\@mpfn{mpfootnote}\def\thempfn{\thempfootnote}\c@mpfootnote\z@
% \let\@footnotetext\@mpfootnotetext
% \end{verbatim}
%
% \DescribeMacro{\@mpfootnotetext}
% Later it defines \cs{@mpfootnotetext}\marg{text} as the minipage version
% of \cs{@footnotetext}.
% \begin{verbatim}
% \long\def\@mpfootnotetext#1{%
%   \global\setbox\@mpfootins\vbox{%
%     \unvbox\@mpfootins
%     \reset@font\footnotesize
%     \hsize\columnwidth
%     \@parboxrestore
%     \def\@currentcounter{mpfootnote}% forgotten
%     \protected@edef\@currentlabel{%
%       \csname p@mpfootnote\endcsname\@thefnmark}%
%     \color@begingroup
%       \@makefntext{%
%         \rule\z@\footnotesep\ignorespaces#1\@finalstrut\strutbox}%
%     \color@endgroup}}
% \end{verbatim}
%
% That completes the kernel extracts.
%
% \begin{macro}{\footnoterule}
%    Usually, footnotes are separated from the main body of the text
%    by a small rule. This rule is drawn by the macro \cs{footnoterule}.
%    We have to make sure that the rule takes no vertical space (see
%    \file{plain.tex}) so we compensate for the natural heigth of the
%    rule of 0.4pt by adding the right amount of vertical skip.
%
%    To prevent the rule from colliding with the footnote we first add
%    a little negative vertical skip, then we put the rule and make
%    sure we end up at the same point where we begun this operation.
%  \changes{v3.6k}{2013/05/08}{Added \cs{normalcolor}, this seems to
%  fix a color leak into paragraph footnotes.}
%    \begin{macrocode}
\renewcommand{\footnoterule}{%
  \kern-3\p@
  \normalcolor% added 2013/05/08
  \hrule width .4\columnwidth
  \kern 2.6\p@}
%    \end{macrocode}
% And just to make sure that we are using memoir's font-dependent
% skips:
%    \begin{macrocode}
\skip\footins=\bigskipamount
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\c@footnote}
%    Footnotes are numbered per chapter. The counter is predefined.
%    \begin{macrocode}
\@addtoreset{footnote}{chapter}
%    \end{macrocode}
% \end{macro}
%
%    The footnote mechanism of \LaTeX{} calls the macro \cs{@makefntext}
%    to produce the actual footnote. The macro gets the text of the
%    footnote as its argument and should use \cs{@thefnmark} as the mark
%    of the footnote. The macro \cs{@makefntext} is called when
%    effectively inside a \cs{parbox} of width \cs{columnwidth} (i.e.,
%    with \cs{hsize} = \cs{columnwidth}).
%
%   An example of what can be achieved is given by the following piece
%   of \TeX{} code.
% \begin{verbatim}
%          \long\def\@makefntext#1{%
%             \@setpar{\@@par
%                      \@tempdima = \hsize
%                      \advance\@tempdima-10pt
%                      \parshape \@ne 10pt \@tempdima}%
%             \par
%             \parindent 1em\noindent
%             \hbox to \z@{\hss\@makefnmark}#1}
% \end{verbatim}
%    The effect of this definition is that all lines of the footnote
%    are indented by 10pt, while the first line of a new paragraph is
%    indented by 1em. To change these dimensions, just substitute the
%    desired value for `10pt' (in both places) or `1em'.  The mark is
%    flushright against the footnote.
%
%    The standard classes use a simpler macro, in which the
%    footnote text is set like an ordinary text paragraph, with no
%    indentation except on the first line of a paragraph, and the
%    first line of the footnote. Thus, all the macro must do is set
%    \cs{parindent} to the appropriate value for succeeding paragraphs
%    and put the proper indentation before the mark.
% \begin{verbatim}
% \newcommand{\@makefntext}[1]{%
%     \parindent 1em%
%     \noindent
%     \hb@xt@1.8em{\hss\@makefnmark}#1}
% \end{verbatim}
%
% This class provides a configurable specification.
%
% Normally, if two or more footnotes are sequentially applied: \\
% \verb?...text\footnote{first}\footnote{second}...? \\
% the markers in the text run together 
% (e.g., \ldots text\textsuperscript{12}). 
% The class provides a separator between the markers
% (e.g., \ldots text\textsuperscript{1,2}).
% The underlying ideas for this are from the \Lpack{ledmac} 
% package~\cite{LEDMAC},
% which in turn got them from the \Lpack{footmisc} package~\cite{FOOTMISC}.
% \changes{v1.4}{2003/11/22}{Added footnote separator (from patch v1.5)}
%
% \begin{macro}{\multfootsep}
% The separator between multiple footnote markers.
%    \begin{macrocode}
\newcommand*{\multfootsep}{\textsuperscript{\normalfont,}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\multiplefootnotemarker}
% \begin{macro}{\m@mmf@prepare}
% \cs{m@mmf@prepare} is a pair of self-cancelling kerns.
%    \begin{macrocode}
\newcommand*{\multiplefootnotemarker}{3sp}
\newcommand*{\m@mmf@prepare}{%
  \kern-\multiplefootnotemarker
  \kern\multiplefootnotemarker\relax}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\m@mmf@check}
% If \cs{m@mmf@check} recognises the last kern as \cs{multiplefootnotemarker}
% it typesets \cs{multfootsep}.
%    \begin{macrocode}
\newcommand*{\m@mmf@check}{%
  \ifdim\lastkern=\multiplefootnotemarker\relax
    \edef\@x@sf{\the\spacefactor}%
    \unkern
    \multfootsep
    \spacefactor\@x@sf\relax
  \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@footnotemark}
% We have to modify the kernel's % \cs{@footnotetext} and 
% \cs{@footnotemark} 
% to implement the separator.
% \changes{v1.618}{2005/09/03}{Stop body font changes leaking into footnotes (mempatch v3.7)}
% \changes{v1.61803}{2008/01/30}{Keep single spacing in footnotes (mempatch v4.6)}
% \changes{v3.6g}{2010/09/19}{Made the 'single spacing' configurable.}
% \changes{v3.6h}{2010/20/22}{\cs{@footnotetext} is redefined later
% on, so the \cs{m@mold@footnotetext} needs to be moved, we also
% remove this version of \cs{@footnotetext} such that people do
% not mistake this for the `real' \cs{@footnotetext}}.
%    \begin{macrocode}
\renewcommand*{\@footnotemark}{%
  \leavevmode
  \ifhmode
    \edef\@x@sf{\the\spacefactor}%
    \m@mmf@check
    \nobreak
  \fi
  \@makefnmark
  \m@mmf@prepare
  \ifhmode\spacefactor\@x@sf\fi
  \relax}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\mem@pn@multiple@marker}
%  This controls the multiple marker handling for successive page
%  notes, i.e., adding a comma between them. 
% \changes{v3.6k}{2013/05/16}{Added hooks, they are not intended for users}
%    \begin{macrocode}
\newcommand{\mem@pn@multiple@marker}[1]{%
  \leavevmode
  \ifhmode
    \edef\@x@sf{\the\spacefactor}%
    \m@mmf@check
    \nobreak
  \fi
  \@nameuse{mem@pnmm@start@hook}%
  #1%
  \@nameuse{mem@pnmm@end@hook}%
  \m@mmf@prepare
  \ifhmode\spacefactor\@x@sf\fi
  \relax}
      
%    \end{macrocode}
%   
% \end{macro}
% %
% \begin{macro}{\footmarkwidth}
% \begin{macro}{\footmarksep}
% \begin{macro}{\footparindent}
% The mark is typset right justified in a box with width \cs{footmarkwidth}.
% Second and later lines of the text are offset \cs{footmarksep} from the
% end of the box. Paragraphs in footnotes are indented by \cs{parindent}.
%    \begin{macrocode}
\newlength{\footmarkwidth}
\newlength{\footmarksep}
\newlength{\footparindent}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\footmarkstyle}
% \begin{macro}{\footscript}
% The marker is typeset according to \cs{footscript}\marg{marker}. This
% can be specified by the user via \cs{footmarkstyle}.
%    \begin{macrocode}
\newcommand*{\footmarkstyle}[1]{\def\footscript##1{#1}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\makefootmarkhook}
% A vacuous macro that the user can redefine to do something useful?
%    \begin{macrocode}
\newcommand{\makefootmarkhook}{}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\footfootmark}
% This macro typesets the footnote marker.
%    \begin{macrocode}
\newcommand{\footfootmark}{%
  \ifdim\footmarkwidth < \z@
%    \end{macrocode}
% Negative width, mark is in the margin.
%    \begin{macrocode}
    \llap{\hb@xt@ -\footmarkwidth{%
            \hss\normalfont\footscript{\@thefnmark}}%
          \hspace*{-\footmarkwidth}}%
  \else
    \ifdim\footmarkwidth = \z@
%    \end{macrocode}
% Zero width, mark is at (inside) the margin.
%    \begin{macrocode}
      {\normalfont\footscript{\@thefnmark}}%
    \else
%    \end{macrocode}
% Positive width.
%    \begin{macrocode}
      \hb@xt@\footmarkwidth{\hss\normalfont\footscript{\@thefnmark}}%
    \fi
  \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\makefootmark}
% \begin{macro}{\@makefntext}
% The class version of \cs{@makefntext}.
%    \begin{macrocode}
\newcommand{\makefootmark}[1]{%
  \leavevmode
  \parindent \footparindent\noindent
  \leftskip\footmarksep\relax
  \advance\leftskip \footmarkwidth \null\nobreak\hskip -\leftskip\relax
  \makefootmarkhook\relax
  \footfootmark #1}
%    \end{macrocode}
% In the thread \textit{memoir and footnote.sty trouble}, 2003/04/02,
% Patrik Nyman noted that in order
% to stop \file{footnote.sty} (from \texttt{mdwtools}) barfing my original \\
% \verb?\newcommand{\@makefntext}[1]{\makefootmark{#1}}? \\
% had to be changed.
% \changes{v1.4}{2004/11/22}{Revised \cs{@makefntext}}
%    \begin{macrocode}
\newcommand{\@makefntext}[1]{\makefootmark #1}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% All that now remains for the footer part is to set the defaults.
%    \begin{macrocode}
\footmarkstyle{\textsuperscript{#1}}
\setlength{\footmarkwidth}{1.8em}
\setlength{\footmarksep}{-1.8em}
\setlength{\footparindent}{1em}

%    \end{macrocode}
%
% \begin{macro}{\@makefnmark}
%    The footnote markers that are printed in the text to point to the
%    footnotes should be produced by the macro \cs{@makefnmark}. We use
%    the default definition for it.
%    \begin{macrocode}
%\renewcommand\@makefnmark{\hbox{\@textsuperscript{%
%                                \normalfont\@thefnmark}}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\footref}
%    Sometimes it is desireable to reference a footnote more than
% once.
%    If a footnote is labelled (e.g., \verb?\footnote{text\label{fn}}?) then
% the macro \cs{footref}\marg{fn} will print the footnote marker.
% The code is essentially a much simplified version of \cs{footnotemark}
% from \file{ltfloat.dtx}.
% \changes{v1.0}{2001/10/30}{Added \cs{footref}}
%    \begin{macrocode}
% \changes{v3.7o}{2021/02/24}{in 2021/05 \cs{footref} will be in the
% kernel, thus we make it provide}
\providecommand{\footref}[1]{%
  \begingroup
    \unrestored@protected@xdef\@thefnmark{\ref{#1}}%
  \endgroup
  \@footnotemark}

%    \end{macrocode}
% \end{macro}
%
% The following code for footnotes that can include verbatims is based
% on Jeremy Gibbons \textit{`Footnotes with verbatim material'}
% in the column \textit{`Hey --- it works'} (edited by Jeremy Gibbons), 
% TeX and TUG NEWS, vol 2 no. 4, p 9, October 1993. I have updated
% the basic code so that it works for LaTeX2e.
%
% \begin{macro}{\verbfootnote}
% \begin{macro}{\@xverbfootnote}
% \cs{verbfootnote} is just like \cs{footnote} except that it can contain
% verbatim material.
%    \begin{macrocode}
\def\verbfootnote{\@ifnextchar[\@xverbfootnote{\stepcounter\@mpfn
  \protected@xdef\@thefnmark{\thempfn}%
  \@footnotemark\@verbfootnotetext}}

\def\@xverbfootnote[#1]{%
  \begingroup
    \csname c@\@mpfn\endcsname #1\relax
    \unrestored@protected@xdef\@thefnmark{\thempfn}%
  \endgroup
  \@footnotemark\@verbfootnotetext}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@verbfootnotetext}
% This is the secret ingredient. It is based on the \cs{footnote} macro
% in \theTeXbook{} page 363, which somehow manages to read an argument 
% with verbatims. As Knuth says that it is subtle and involves trickery,
% don't expect me to even try to explain anything. 
%
% I'm not at all sure about the color bits, though!
% \changes{v1.618}{2005/09/02}{Fixed colors in \cs{verbfootnote} (mempatch v2.3)}
% \changes{v3.8}{2023/07/26}{added the missing \cs{@currentcounter}}
% \changes{v3.8}{2023/07/27}{replaced hardcoded \cs{foornotesize}
% by \cs{foottextfont}}
%    \begin{macrocode}
\long\def\@verbfootnotetext{%
  \insert\footins\bgroup
    \foottextfont%
    \interlinepenalty\interfootnotelinepenalty
    \splittopskip\footnotesep
    \splitmaxdepth \dp\strutbox \floatingpenalty \@MM
    \hsize\columnwidth \@parboxrestore
    \def\@currentcounter{footnote}%
    \edef\@currentlabel{\csname p@footnote\endcsname\@thefnmark}%
%%%%    \color@begingroup    
    \@makefntext{\rule{\z@}{\footnotesep}\ignorespaces}%
    \futurelet\next\fo@t
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\fo@t}
% \begin{macro}{\f@@t}
% \begin{macro}{\f@t}
% \begin{macro}{\@foot}
% Guess what these do.
% \changes{v1.61803}{2008/01/30}{Added \cs{m@mmf@prepare} to \cs{@foot} to 
%       implement the multifootnotemark separator (noted by zarko, CTT 2005/01/15)}
%    \begin{macrocode}
\def\fo@t{\ifcat\bgroup\noexpand\next \let\next\f@@t
          \else \let\next\f@t\fi \next}
\def\f@@t{\bgroup\aftergroup\@foot\let\next}
\def\f@t#1{%
  \color@begingroup
  #1\@foot
  \color@endgroup}
\def\@foot{%
  \strut\egroup
%%%%  \color@endgroup
  \m@mmf@prepare
  }

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@verbmpfootnotetext}
%    Footnotes in minipages are a little different, so another
% version of \cs{...footnotetext}. 
% \changes{v3.8}{2023/07/26}{added the missing \cs{@currentcounter}}
% \changes{v3.8}{2023/07/27}{replaced hardcoded \cs{foornotesize}
% by \cs{foottextfont}}
%    \begin{macrocode}
\long\def\@verbmpfootnotetext{%
  \global\setbox\@mpfootins\vbox{%
    \reset@font\foottextfont
    \unvbox\@mpfootins
    \bgroup
    \hsize\columnwidth
    \@parboxrestore
    \def\@currentcounter{mpfootnote}%
    \edef\@currentlabel{\csname p@mpfootnote\endcsname\@thefnmark}%
    \color@begingroup
    \@makefntext{\rule{\z@}{\footnotesep}\ignorespaces}%
    }
    \futurelet\next\fo@t
} 

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@minipagerestore}
% To get the \cs{verbfootnote} to work in a \texttt{minipage} we have to use
% \cs{@verbmpfootnotetext} instead of \cs{@verbfootnotetext}. There is
% a nice hook in the kernel \texttt{minipage} code for this. 
%
% As of version 1.61803 the following code is placed earlier. \\
% \verb?\def\@minipagerestore{\let\@verbfootnotetext\@verbmpfootnotetext}?
% \end{macro}
%
%
% \subsection{Major extensions for footnotes}
%
%    \begin{macrocode}
%%%%%%%%%%%%%% major extension to footnoting 

%    \end{macrocode}
%
% This all requires modifications to the output routine's \cs{@makecol},
% which will be done later. 
%
% \begin{macro}{\setfootnoterule}
% Per Starb\"{a}ck found (CTT \textit{feetbelowfloat in memoir}, 2006/11/24)
% that \cs{feetbelowfloat} did not affect anything when \cs{raggedbottom}
% is in effect.
%
% \cs{setfootnoterule}\oarg{vfill}\marg{uplift}\marg{width}\marg{thickness}
% defines the \cs{footnoterule}. Memoir's default setting is \\
% \verb?\setfootnoterule{3pt}{0.4\columnwidth}{\normalrulethickness}? \\
% To force footnotes to the bottom after a \cs{raggedbottom} use \\
% \verb?\setfootnoterule[\vfill]{3pt}{0.4\columnwidth}{\normalrulethickness}?
% \changes{v1.61803}{2008/01/30}{Added \cs{setfootnoterule} (memptatch v4.6)}
%  \changes{v3.6k}{2013/05/08}{Added \cs{normalcolor}, this seems to
%  fix a color leak into paragraph footnotes.}
%    \begin{macrocode}
\newcommand*{\setfootnoterule}[4][]{%
  \def\footnoterule{\kern -#2\relax #1\relax
    \normalcolor% added 2013/05/08
    \hrule width #3\relax
    \kern #2\kern-#4}}
\setfootnoterule{3pt}{0.4\columnwidth}{\normalrulethickness}

%    \end{macrocode}
% \end{macro}
%
% All sorts of extra kinds of footnotes.
%
% \begin{macro}{\m@mdoextrafeet}
% \begin{macro}{\extrafeetins}
% \begin{macro}{\extrafeetinshook}
% These macros are hooks into \cs{@makecol}.
% \changes{v1.618}{2005/09/02}{Fixed memoir/listings spacing problem (from Cartsten Heinz, mempatch v2.3)}
% \changes{v1.618}{2005/09/03}{Set \cs{boxmaxdepth} in \cs{extrafeetins} (mmempatch v3.1)}
%    \begin{macrocode}
\newcommand{\m@mdoextrafeet}{\extrafeetins}
\newcommand*{\extrafeetins}{%
  \setbox\@outputbox \vbox{%
    \boxmaxdepth \@maxdepth
    \unvbox\@outputbox
    \ifvoid\footinsv@r\else\@footstartv@r\@footgroupv@r\fi
    \extrafeetinshook}}
\newcommand{\extrafeetinshook}{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\m@mdodoreinextrafeet}
% \begin{macro}{\extrafeetreinshook}
% Hooks into \cs{@reinserts} for multiple footnote kinds.
%    \begin{macrocode}
\newcommand{\m@mdodoreinextrafeet}{%
  \ifvoid\footinsv@r\else\insert\footinsv@r{\unvbox\footinsv@r}\fi
  \extrafeetreinshook}
\newcommand{\extrafeetreinshook}{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
%
% \begin{macro}{\foottextfont}
% \begin{macro}{\footinsdim}
% \begin{macro}{\@preamfntext}
% General macros.
%    \begin{macrocode}
\newcommand{\foottextfont}{\footnotesize}
\newlength{\footinsdim}
  \setlength{\footinsdim}{8in}   % standard for \dimen\footins
\newcommand{\@preamfntext}{%
  \interlinepenalty\interfootnotelinepenalty
  \floatingpenalty \@MM
  \splittopskip=\footnotesep
  \splitmaxdepth=\dp\strutbox
  \@parboxrestore}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% We are going to change some of the kernel footnote macros
%
% \begin{macro}{\@mpfootnotetext}
% \begin{macro}{\@plainmpfootnotetext}
% \changes{v1.6180}{2006/06/12}{Stop font changes leaking into footnotes.
%                  The v1.618 change was too early}
% \changes{v3.6g}{2010/09/19}{made 'single spacing' configurable'}
% \changes{v3.8}{2023/07/26}{added the missing \cs{@currentcounter}}
% \changes{v3.8}{2023/07/27}{removed group around \cs{footnotetext}}
%    \begin{macrocode}
\renewcommand{\@mpfootnotetext}[1]{%
  \global\setbox\@mpfootins\vbox{%
    \unvbox\@mpfootins
    \def\baselinestretch{\m@m@footnote@spacing}%
    \foottextfont \hsize\columnwidth \@parboxrestore
    \def\@currentcounter{mpfootnote}%
    \protected@edef\@currentlabel{%
      \csname p@mpfootnote\endcsname\@thefnmark}%
  \color@begingroup
  \reset@font%        
    \@makefntext{%
      \rule\z@\footnotesep\ignorespaces\foottextfont #1%
      \@finalstrut\strutbox}%
  \color@endgroup}}

%    \end{macrocode}
% Save our revised version of \cs{@mpfootnotetext}
% \changes{v3.6h}{2010/10/22}{\cs{m@mold@mpfootnotetext} renamed to \cs{@plainmpfootnotetext}}
%    \begin{macrocode}
\let\@plainmpfootnotetext\@mpfootnotetext

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% We also to patch the minipage environment. We can use 
% \cs{@minipagerestore} for the \texttt{begin} part (done earlier), 
% but have to 
% modify \cs{endminipage}
%
% \begin{macro}{\m@mdoextrafeetmini}
% \begin{macro}{\extrafeetminihook}
% \begin{macro}{\@minipagerestore}
%    \begin{macrocode}
\newcommand{\m@mdoextrafeetmini}{%
  \extrafeetminihook}
\newcommand{\extrafeetminihook}{}
%%%%\renewcommand{\@minipagerestore}{\m@mdoextrafeetmini}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\extrafeetendmini}
% \begin{macro}{\extrafeetendminihook}
%    \begin{macrocode}
\newcommand{\extrafeetendmini}{%
  \ifvoid\@mpfootinsv@r\else
    \vskip\skip\@mpfootins
    \normalcolor\footnoterule\mp@footgroupv@r
  \fi
  \extrafeetendminihook}
\newcommand{\extrafeetendminihook}{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\m@mdoextrafeetendmini}
% \begin{macro}{\endminipage}
% This is our patched version of \cs{endminipage}.
%    \begin{macrocode}
\newcommand{\m@mdoextrafeetendmini}{\extrafeetendmini}
\def\endminipage{%
  \par
  \unskip
  \ifvoid\@mpfootins\else
    \vskip\skip\@mpfootins
    \normalcolor
    \footnoterule
    \unvbox\@mpfootins
  \fi
  \m@mdoextrafeetendmini
  \@minipagefalse
  \color@endgroup
  \egroup
  \expandafter\@iiiparbox\@mpargs{\unvbox\@tempboxa}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\plainfootnotes}
% The declaration for standard footnotes; easy, just use the saved
% versions of \cs{@footnotetext} and \cs{@mpfootnotetext}.
% \changes{v3.6h}{2010/10/22}{\cs{m@mold@footnotetext} renamed
% \cs{@plainfootnotetext} and \cs{m@mold@mpfootnotetext} as \cs{@plainmpfootnotetext}}
%    \begin{macrocode}
\newcommand{\plainfootnotes}{%
  \let\@footnotetext\@plainfootnotetext
  \let\@mpfootnotetext\@plainmpfootnotetext}

%    \end{macrocode}
% \end{macro}
%
% Now for lots of somewhat tedious code, interspersed with complex
% `Dirty Tricks' type things.
%
% Robert Schlicht (Private email, 2004/03/12) [RS] has provided
% valuable help in tuning up the code.
% 
%
% \begin{macro}{\newfootnoteseries}
% \cs{newfootnoteseries}\marg{series} creates the set of macros required
% for footnote code (see the kernel code presented earlier).
% The created macros have \meta{series} appended to their name.
% \changes{v1.61}{2004/03/14}{Added skip setup to \cs{newfootnoteseries}}
% \changes{v1.61}{2004/03/24}{Use \cs{newcounter} instead of \cs{newcount}
%                 in \cs{newfootnoteseries}}
%    \begin{macrocode}
\newcommand{\newfootnoteseries}[1]{%
  \expandafter\newinsert\csname footins#1\endcsname%  -> \footins#1
  \expandafter\skip\csname footins#1\endcsname \bigskipamount%
%%%                                      - > \skip\footins#1 % [RS]
  \newcounter{footnote#1}%                       -> \c@footnote#1
  \@nameuse{c@footnote#1} \z@%                   -> \c@footnote#1=0
  \global\@namelet{p@footnote#1} \@empty%        -> \p@footnote#1 
  \@namedef{thefootnote#1}{\arabic{footnote#1}}% -> \thefootnote#1
  \@namedef{foottextfont#1}{\foottextfont}%      -> \foottextfont#1
  \m@makefootnote{#1}%                           -> \footnote#1
  \m@make@xfootnote{#1}%                         -> \@xfootnote#1
  \m@make@footnotetext{#1}%                      -> \@footnotetext#1
  \m@makefootnotemark{#1}%                       -> \footnotemark#1
  \m@make@xfootnotemark{#1}%                     -> \@xfootnotemark#1
  \m@make@footnotemark{#1}%                      -> \@footnotemark#1
  \m@makefootnotetext{#1}%                       -> \footnotetext#1
  \m@make@xfootnotenext{#1}%                     -> \@xfootnotenext#1
  \m@make@mpfn{#1}%                              -> \@mpfn#1
  \m@makethempfn{#1}%                            -> \thempfn#1
  \m@make@makefnmark{#1}%                        -> \@makefnmark#1
  \m@makefootref{#1}%                            -> \footref#1
  \m@makefootfootmark{#1}%                       -> \footfootmark#1
  \m@makemakefootmark{#1}%                       -> \makefootmark#1
  \m@makefootmarkstyle{#1}%                      -> \footmarkstyle#1
%    \end{macrocode}
% \changes{3.7i}{2019/05/24}{@makefntext\#1 should of course be
% long. Reported on TSE by meide, https://tex.stackexchange.com/q/491303/3929}
%    \begin{macrocode}
  \@namelongdef{@makefntext#1}##1{\@nameuse{makefootmark#1} ##1}%
  \m@make@footstart{#1}%                         -> \@footstart#1
  \m@make@footgroup{#1}%                         -> \@footgroup#1
  \expandafter\newinsert\csname @mpfootins#1\endcsname% -> \@mpfootins#1
  \newcounter{mpfootnote#1}%                     -> \c@mpfootnote#1
  \global\@namelet{p@mpfootnote#1}\@empty
  \@namedef{thempfootnote#1}{\itshape\alph{mpfootnote#1}}%
  \m@make@mpfootnotetext{#1}%                    -> \@mpfootnotetext#1
%    \end{macrocode}
% Reset the counter per chapter, except for articles.
% \changes{v1.6}{2004/03/14}{Added chapter reset for footnote series [RS]}
%    \begin{macrocode}
  \ifartopt\else%  [RS]
    \expandafter\@cons\csname cl@chapter\endcsname {{footnote#1}}%
  \fi
%    \end{macrocode}
% Add the footnote to the (re)insert hooks.
%    \begin{macrocode}
  \g@addto@macro{\extrafeetinshook}{%
    \ifvoid\@nameuse{footins#1}\else
      \@nameuse{@footstart#1}\@nameuse{@footgroup#1}\fi}
  \g@addto@macro{\extrafeetreinshook}{%
    \ifvoid\@nameuse{footins#1}\else
      \insert\@nameuse{footins#1}{\unvbox\@nameuse{footins#1}}\fi}
  \g@addto@macro{\extrafeetendminihook}{%
    \ifvoid\@nameuse{@mpfootins#1}\else
      \vskip\skip\@mpfootins
      \normalcolor\footnoterule\@nameuse{mp@footgroup#1}\fi}
  \g@addto@macro{\extrafeetminihook}{%
    \@namedef{@mpfn#1}{mpfootnote#1}
    \@namedef{thempfn#1}{\@nameuse{thempfootnote#1}}
    \csname c@mpfootnote#1\endcsname\z@
     \expandafter\let\expandafter\@t@mp \csname @mpfootnotetext#1\endcsname
     \expandafter\let \csname @footnotetext#1\endcsname \@t@mp}
  \g@addto@macro{\@mem@extranofeet}{%  % [RS]
    \ifvoid\@nameuse{footins#1}\else\@mem@nofootfalse\fi}
  \plainfootstyle{#1}%
}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@makefootnote}
% \cs{m@makefootnote}\marg{series} creates  \cs{footnote<series>}
% \changes{v1.4}{2004/01/21}{In \cs{m@makefootnote} changed \cs{advance}
% to \cs{stepcounter} to make change global}
%    \begin{macrocode}
\newcommand{\m@makefootnote}[1]{
  \@namedef{footnote#1}{\@ifnextchar[
    {\@nameuse{@xfootnote#1}}{%\advance \@nameuse{c@\@mpfn#1} by \@ne
                              \stepcounter{\@mpfn#1}%
      \@name@p@xdef{@thefnmark#1}{\@nameuse{thempfn#1}}%
      \@nameuse{@footnotemark#1}\@nameuse{@footnotetext#1}}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@xfootnote}
% \cs{m@make@xfootnote}\marg{series} creates \cs{@xfootnote<series>}
%    \begin{macrocode}
\newcommand{\m@make@xfootnote}[1]{
  \@namedef{@xfootnote#1}[##1]{%
  \begingroup
    \csname c@\@mpfn#1\endcsname ##1\relax
    \@name@unresp@xdef{@thefnmark#1}{\@nameuse{thempfn#1}}%
  \endgroup
  \@nameuse{@footnotemark#1}\@nameuse{@footnotetext#1}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@footnotetext}
% \cs{m@make@footnotetext}\marg{series} creates \cs{@footnotetext<series>}
% \changes{v1.6180339a}{2008/08/07}{Removed a space from 
%     \cs{m@make@footnotetext} and \cs{m@make@mpfootnotetext} 
%     (courtesy David Wilson)}
% \changes{v3.6g}{2010/09/19}{made 'single spacing' configurable}
% \changes{v3.8}{2023/07/26}{added the missing \cs{@currentcounter}}
% \changes{v3.8}{2023/07/27}{removed group around \cs{footnotetextX}}
%    \begin{macrocode}
\newcommand{\m@make@footnotetext}[1]{%
  \@namelongdef{@footnotetext#1}##1{%
    \insert\@nameuse{footins#1}{%
      \def\baselinestretch{\m@m@footnote@spacing}% 
      \reset@font\@nameuse{foottextfont#1}%
      \@preamfntext
      \hsize\columnwidth
      \def\@currentcounter{footnote}%
      \protected@edef\@currentlabel{%
        \csname p@footnote#1\endcsname\@nameuse{@thefnmark#1}}% 
      \color@begingroup
      \@nameuse{@makefntext#1}{%
%    \end{macrocode}
% \changes{v3.8.2}{2024/01/03}{Bug: \#\#1 needs to be outside of \cs{@nameuse}, reported in \url{https://tex.stackexchange.com/questions/706033/footnotes-defined-with-newfootnoteseries-dont-work/}}
%    \begin{macrocode}
        \rule\z@\footnotesep\ignorespaces\@nameuse{foottextfont#1}##1%
        \@finalstrut\strutbox}%
  \color@endgroup}%
  \m@mmf@prepare}%
}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@mpfootnotetext}
% \cs{m@make@mpfootnotetext}\marg{series} creates \cs{@mpfootnotetext<series>}
% \changes{v3.6g}{2010/09/19}{made 'single spacing' configurable}
% \changes{v3.8}{2023/07/26}{added the missing \cs{@currentcounter}}
% \changes{v3.8}{2023/07/27}{removed group around \cs{footnotetextX}}
%    \begin{macrocode}
\newcommand{\m@make@mpfootnotetext}[1]{%
  \@namelongdef{@mpfootnotetext#1}##1{%
    \global\setbox\@nameuse{@mpfootins#1}\vbox{%
      \unvbox\@nameuse{@mpfootins#1}%
      \def\baselinestretch{\m@m@footnote@spacing}%  
      \reset@font\@nameuse{foottextfont#1}%
      \hsize\columnwidth \@parboxrestore
      \def\@currentcounter{mpfootnote}%
      \protected@edef\@currentlabel{%
        \csname p@mpfootnote#1\endcsname\@nameuse{@thefnmark#1}}%
    \color@begingroup
      \@nameuse{@makefntext#1}{%
        \rule\z@\footnotesep\ignorespaces\@nameuse{foottextfont#1}##1%
        \@finalstrut\strutbox}%
    \color@endgroup}%
    \m@mmf@prepare}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@makefootnotemark}
% \changes{v1.61}{2004/03/24}{Changed \cs{advance} to \cs{stepcounter}
%                 in \cs{m@makefootnotemark}}
% \cs{m@makefootnotemark}\marg{series} creates \cs{footnotemark<series>}
%    \begin{macrocode}
\newcommand{\m@makefootnotemark}[1]{
\@namedef{footnotemark#1}{%
  \@ifnextchar[ {\@nameuse{@xfootnotemark#1}}
    {%\advance\@nameuse{c@footnote#1} by \@ne%
     \stepcounter{footnote#1}%
     \@name@p@xdef{@thefnmark#1}{\@nameuse{thefootnote#1}}%
     \@nameuse{@footnotemark#1}}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@xfootnotemark}
% \cs{m@make@xfootnotemark}\marg{series} creates \cs{@xfootnotemark<series>}
%    \begin{macrocode}
\newcommand{\m@make@xfootnotemark}[1]{%
  \@namedef{@xfootnotemark#1}[##1]{%
  \begingroup
    \@nameuse{c@footnote#1} ##1\relax
    \@name@unresp@xdef{@thefnmark#1}{\@nameuse{thefootnote#1}}%
  \endgroup
  \@nameuse{@footnotemark#1}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@footnotemark}
% \cs{m@make@footnotemark}\marg{series} creates \cs{@footnotemark<series>}
%    \begin{macrocode}
\newcommand{\m@make@footnotemark}[1]{%
\@namedef{@footnotemark#1}{%
  \leavevmode
  \ifhmode
    \edef\@x@sf{\the\spacefactor}%
    \m@mmf@check
    \nobreak
  \fi
  \@nameuse{@makefnmark#1}%
  \m@mmf@prepare
  \ifhmode\spacefactor\@x@sf\fi
  \relax}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@makefootmarkstyle}
% \cs{m@makefootmarkstyle}\marg{series} creates \cs{footmarkstyle<series>}
%    \begin{macrocode}
\newcommand{\m@makefootmarkstyle}[1]{%
 \@namedef{footmarkstyle#1}##1{%
    \@namedef{footscript#1}####1{##1}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@makefootnotetext}
% \cs{m@makefootnotetext}\marg{series} creates \cs{footnotetext<series>}
%    \begin{macrocode}
\newcommand{\m@makefootnotetext}[1]{%
\@namedef{footnotetext#1}{%
  \@ifnextchar[  {\@nameuse{@xfootnotenext#1}}%
  {\@name@p@xdef{@thefnmark#1}{\@nameuse{thempfn#1}}%
  \@nameuse{@footnotetext#1}}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@xfootnotenext}
% \cs{m@make@xfootnotenext}\marg{series} creates \cs{@xfootnotenext<series>}
%    \begin{macrocode}
\newcommand{\m@make@xfootnotenext}[1]{
\@namedef{@xfootnotenext#1}[##1]{%
  \begingroup
    \csname c@\@mpfn#1\endcsname ##1\relax
    \@name@unresp@xdef{@thefnmark#1}{\@nameuse{thempfn#1}}%
  \endgroup
  \@nameuse{@footnotetext#1}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@mpfn}
% \cs{m@make@mpfn}\marg{series} creates \cs{@mpfn<series>}
%    \begin{macrocode}
\newcommand{\m@make@mpfn}[1]{%
  \@namedef{@mpfn#1}{\@nameuse{footnote#1}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@makethempfn}
% \cs{m@makethempfn}\marg{series} creates \cs{thempfn<series>}
%    \begin{macrocode}
\newcommand{\m@makethempfn}[1]{%
  \@namedef{thempfn#1}{\@nameuse{thefootnote#1}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@makefnmark}
% \cs{m@make@makefnmark}\marg{series} creates \cs{@makefnmark<series>}
%    \begin{macrocode}
\newcommand{\m@make@makefnmark}[1]{%
  \@namedef{@makefnmark#1}{%
    \hbox{\@textsuperscript{\normalfont\@nameuse{@thefnmark#1}}}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@makefootref}
% \cs{m@makefootref}\marg{series} creates \cs{footref<series>}
%    \begin{macrocode}
\newcommand{\m@makefootref}[1]{%
  \@namedef{footref#1}##1{%
    \begingroup
      \@name@unresp@xdef{@thefnmark#1}{\ref{##1}}%
    \endgroup
    \@nameuse{@footnotemark#1}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@makefootfootmark}
% \cs{m@makefootfootmark}\marg{series} creates \cs{footfootmark<series>}
%    \begin{macrocode}
\newcommand{\m@makefootfootmark}[1]{%
  \@namedef{footfootmark#1}{%
    \ifdim\footmarkwidth < \z@
      \llap{\hb@xt@ -\footmarkwidth{%
            \hss\normalfont\@nameuse{footscript#1}%
            {\@nameuse{@thefnmark#1}}}%
            \hspace*{-\footmarkwidth}}%
    \else
      \ifdim\footmarkwidth = \z@
        {\normalfont\@nameuse{footscript#1}{\@nameuse{@thefnmark#1}}}%
      \else
        \hb@xt@\footmarkwidth{%
            \hss\normalfont\@nameuse{footscript#1}%
            {\@nameuse{@thefnmark#1}}}%
      \fi
    \fi}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@makemakefootmark}
% \changes{v1.61}{2004/03/23}{Removed extraneous space from \cs{m@makemakefootmark}}
% \cs{m@makemakefootmark}\marg{series} creates \cs{makefootmark<series>}
%    \begin{macrocode}
\newcommand{\m@makemakefootmark}[1]{%
  \@namedef{makefootmark#1}##1{%
    \leavevmode
    \parindent \footparindent\noindent
    \leftskip\footmarksep\relax
    \advance\leftskip \footmarkwidth 
    \null\nobreak\hskip -\leftskip\relax
    \makefootmarkhook\relax
    \@nameuse{footfootmark#1}##1}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@footgroup}
% \cs{m@make@footgroup}\marg{series} creates \cs{@footgroup<series>}
%    \begin{macrocode}
\newcommand{\m@make@footgroup}[1]{%
  \@namedef{@footgroup#1}{\unvbox\@nameuse{footins#1}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@makemp@footgroup}
% \cs{m@makemp@footgroup}\marg{series} creates \cs{mp@footgroup<series>}
%    \begin{macrocode}
\newcommand{\m@makemp@footgroup}[1]{%
  \@namedef{mp@footgroup#1}{\unvbox\@nameuse{@mpfootins#1}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@footstart}
% \cs{m@make@footstart}\marg{series} creates \cs{@footstart<series>}.
%
% The footnote series should of course use
% the skip associated with that series not just
% \cs{vskip}\cs{bigskipamount}. 
% \changes{v3.7d}{2015/04/22}{Changed the \cs{vskip}}
% \changes{v3.7d}{2015/04/22}{Added the feet at bottom part}
%    \begin{macrocode}
\newcommand{\m@make@footstart}[1]{%
  \@namedef{@footstart#1}{%
    %\vskip\bigskipamount
    \mem@if@flushbottomF\m@mopfn@bottom
    \vskip\skip\csname footins#1\endcsname
    \leftskip=\z@
    \rightskip=\z@
    \footnoterule}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\plainfootstyle}
% \cs{plainfootstyle}\marg{series} specifies a plain (normal) footnote
% style for \meta{series}.
%    \begin{macrocode}
\newcommand{\plainfootstyle}[1]{%
  \m@make@footnotetext{#1}%
  \m@make@footgroup{#1}%
  \m@make@footstart{#1}%
  \m@make@mpfootnotetext{#1}%
  \m@makemp@footgroup{#1}%
  \@nameuse{footmarkstyle#1}{\textsuperscript{##1}}
  \expandafter\dimen\csname footins#1\endcsname=\footinsdim
  \expandafter\count\csname footins#1\endcsname=1000\relax}

%    \end{macrocode}
% \end{macro}
%
% Now the basic code for footnote declarations (we will be
% using \texttt{footnotev@r} instead of the regular \texttt{footnote}).
%
% \begin{macro}{\footinsv@r}
% Define the new \cs{footinsv@r} insert. 
%    \begin{macrocode}
\newinsert\footinsv@r
  \skip\footinsv@r\bigskipamount
  \count\footinsv@r=1000 % no magnifcation
  \dimen\footinsv@r=\footinsdim
%    \end{macrocode}
% \end{macro}
% Create a new \verb?v@r? footnote series.
%    \begin{macrocode}
\m@make@footstart{v@r}
%    \end{macrocode}
% 
% \begin{macro}{\@footgroupv@r}
% Initialise the \texttt{footgroup} for the series to do nothing.
%    \begin{macrocode}
\newcommand{\@footgroupv@r}{}

%    \end{macrocode}
% \end{macro}
%
% And also for minipages:
% \begin{macro}{\@mpfootinsv@r}
% \begin{macro}{\mp@footgroupv@r}
%    \begin{macrocode}
\newinsert\@mpfootinsv@r
\newcommand{\mp@footgroupv@r}{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \Lpack{ledmac} package style footnotes (see \file{ledmac.dtx} for 
% more detailed explanations).
%
% The two- and three-column notes use a macro \cs{m@mrigidbalance}
% to split text into a number of columns. This is based on \theTeXbook,
% page 397.
% \begin{macro}{\m@m@k}
% \begin{macro}{\m@m@h}
%    \begin{macrocode}
\newcount\m@m@k \newdimen\m@m@h
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\m@mrigidbalance}
% \begin{macro}{\m@mdosplits}
% \begin{macro}{\m@msplitoff}
% \cs{m@mrigidbalance}\marg{box}\marg{num}\marg{length} splits a
% \meta{box} (of text) into \meta{num} columns with \meta{length}
% space between the top baseline and the top of the \cs{vbox}.
%    \begin{macrocode}
\newcommand*{\m@mrigidbalance}[3]{\setbox0=\box#1 \m@m@k=#2 \m@m@h=#3
  \@@line{\splittopskip=\m@m@h \vbadness=\@M \hfilneg
  \valign{##\vfill\cr\m@mdosplits}}}
\newcommand*{\m@mdosplits}{\ifnum\m@m@k>0 \noalign{\hfil}\m@msplitoff
  \global\advance\m@m@k-1\cr\m@mdosplits\fi}
\newcommand*{\m@msplitoff}{\dimen0=\ht0
  \divide\dimen0 by\m@m@k \advance\dimen0 by\m@m@h
  \setbox2 \vsplit0 to \dimen0
  \unvbox2 }

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \subsubsection{Two column footnotes}
%
% \begin{macro}{\twocolumnfootnotes}
% Declaration for two column footnotes. This causes the standard
% \cs{footnote} and friends to internally use the \verb?v@r? series,
% which here produces two column footnotes.
% \changes{v1.61}{2004/03/14}{Made [RS] change to \cs{twocolumnfootnotes}}
%    \begin{macrocode}
\newcommand{\twocolumnfootnotes}{%
  \@namedef{foottextfontv@r}{\foottextfont}%  % [RS]
  \let\@footnotetext\@twocolfootnotetext
  \dimen\footinsv@r=2\footinsdim
  \count\footinsv@r=500\relax
  \m@make@twocol@footgroup{v@r}%
  \let\@footgroupv@r\@twocol@footgroupv@r
  \let\@mpfootnotetext\@mptwocolfootnotetext 
  \m@make@mptwocol@footgroup{v@r}%
  \let\mp@footgroupv@r\@mptwocol@footgroupv@r}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@twocolfootnotetext}
% \cs{@twocolfootnotetext}\marg{text} is the two column version of
% \cs{@footnotetext} for the \verb?v@r? series.
% \changes{v1.618}{2005/09/03}{Added missing percent to \cs{@twocolfootnotetext} (mempatch v3.1)}
% \changes{v3.6g}{2010/09/19}{made 'single spacing' configurable}
% \changes{v3.8}{2023/07/26}{added the missing \cs{@currentcounter}}
%    \begin{macrocode}
\newcommand{\@twocolfootnotetext}[1]{\insert\footinsv@r{%
  \def\baselinestretch{\m@m@footnote@spacing}%   
  \reset@font\foottextfont
  \@preamfntext
  \def\@currentcounter{footnote}%
  \protected@edef\@currentlabel{%
    \csname p@footnote\endcsname\@thefnmark}%
  \color@begingroup
    \@twocolfootfmt{#1}%
  \color@endgroup}%
  \m@mmf@prepare}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@preamtwofmt}
% Give each column 0.45 of the textwidth.
%    \begin{macrocode}
\newcommand{\@preamtwofmt}{%
  \hsize .45\hsize
  \parindent=\z@
  \tolerance=5000\relax
  \raggedright
  \leavevmode}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@twocolfootfmt}
% \cs{@twocolfootfmt}
% \changes{v3.8}{2023/07/27}{removed group around \cs{footnotetext}}
%    \begin{macrocode}
\newcommand{\@twocolfootfmt}[1]{%
  \@preamtwofmt
  {\footfootmark\strut \foottextfont #1\strut\par}\allowbreak}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@mptwocolfootnotetext}
% \cs{@mptwocolfootnotetext}\marg{text} is the two column version
% of \cs{@mpfootnotetext} for the \verb?v@r? series for minipages.
% \changes{v3.6g}{2010/09/19}{made 'single spacing' configurable}
% \changes{v3.8}{2023/07/26}{added the missing \cs{@currentcounter}}
%    \begin{macrocode}
\newcommand{\@mptwocolfootnotetext}[1]{%
  \global\setbox\@mpfootinsv@r\vbox{%
    \unvbox\@mpfootinsv@r
    \def\baselinestretch{\m@m@footnote@spacing}%   
    \reset@font\foottextfont 
    \hsize\columnwidth \@parboxrestore
    \def\@currentcounter{mpfootnote}%
    \protected@edef\@currentlabel{%
      \csname p@mpfootnote\endcsname\@thefnmark}%
  \color@begingroup
    \@twocolfootfmt{#1}%
  \color@endgroup}%
  \m@mmf@prepare}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\twocolumnfootstyle}
% \cs{twocolumnfootstyle}\marg{series} specifies a two column footnote 
% style for \meta{series}.
%    \begin{macrocode}
\newcommand{\twocolumnfootstyle}[1]{%
  \m@make@twocolfootnotetext{#1}%
  \m@make@mptwocolfootnotetext{#1}%
  \m@make@twocolfootfmt{#1}%
  \m@make@twocol@footgroup{#1}%
  \m@make@mptwocol@footgroup{#1}%
  \m@make@footstart{#1}%
  \@namelongdef{@footnotetext#1}##1{%
     \@nameuse{@twocolfootnotetext#1}{##1}}%
  \@namelongdef{@mpfootnotetext#1}##1{%
     \@nameuse{@mptwocolfootnotetext#1}{##1}}%
  \@namedef{@footgroup#1}{\@nameuse{@twocol@footgroup#1}}%
  \@namedef{mp@footgroup#1}{\@nameuse{@mptwocol@footgroup#1}}%
  \expandafter\dimen\csname footins#1\endcsname=2\footinsdim
  \expandafter\count\csname footins#1\endcsname=500\relax}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@twocolfootnotetext}
% \cs{m@make@twocolfootnotetext}\marg{series} creates 
% \cs{@twocolfootnotetext}\meta{series}
% \changes{v3.6g}{2010/09/19}{made 'single spacing' configurable}
% \changes{v3.8}{2023/07/26}{added the missing \cs{@currentcounter}}
%    \begin{macrocode}
\newcommand{\m@make@twocolfootnotetext}[1]{%
  \@namelongdef{@twocolfootnotetext#1}##1{%
    \insert\@nameuse{footins#1}{%
    \def\baselinestretch{\m@m@footnote@spacing}%   
    \reset@font\@nameuse{foottextfont#1}%
    \@preamfntext
    \def\@currentcounter{footnote}%
    \protected@edef\@currentlabel{%
      \csname p@footnote#1\endcsname \@nameuse{@thefnmark#1}}%
    \color@begingroup
      \@nameuse{@twocolfootfmt#1}{##1}%
    \color@endgroup}%
    \m@mmf@prepare}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@mptwocolfootnotetext}
% \cs{m@make@mptwocolfootnotetext}\marg{series} creates
% \cs{@mptwocolfootnotetext}\meta{series}
% \changes{v3.6g}{2010/09/19}{made 'single spacing' configurable}
% \changes{v3.8}{2023/07/26}{added the missing \cs{@currentcounter}}
%    \begin{macrocode}
\newcommand{\m@make@mptwocolfootnotetext}[1]{%
\@namelongdef{@mptwocolfootnotetext#1}##1{%
  \global\setbox\@nameuse{@mpfootins#1}\vbox{%
    \unvbox\@nameuse{@mpfootins#1}
    \def\baselinestretch{\m@m@footnote@spacing}%   
    \reset@font\@nameuse{foottextfont#1}%
    \hsize\columnwidth \@parboxrestore
    \def\@currentcounter{mpfootnote}%
    \protected@edef\@currentlabel{%
      \csname p@mpfootnote#1\endcsname\@nameuse{@thefnmark#1}}%
  \color@begingroup
    \@nameuse{@twocolfootfmt#1}{##1}%
  \color@endgroup}\m@mmf@prepare}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@twocolfootfmt}
% \cs{m@make@twocolfootfmt}\marg{series} creates
% \cs{@twocolfootfmt}\meta{series} 
% \changes{v1.61}{2004/03/14}{Removed space from \cs{m@make@twocolfootfmt} [RS]}
% \changes{v3.8}{2023/07/27}{removed group around \cs{footnotetextX}}
%    \begin{macrocode}
\newcommand{\m@make@twocolfootfmt}[1]{%
  \@namedef{@twocolfootfmt#1}##1{%
    \@preamtwofmt
    {\@nameuse{footfootmark#1}\strut
      \@nameuse{foottextfont#1}##1\strut\par}\allowbreak}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@twocol@footgroup}
% \cs{m@make@twocol@footgroup}\marg{series} creates
% \cs{@twocol@footgroup}\meta{series} 
%    \begin{macrocode}
\newcommand{\m@make@twocol@footgroup}[1]{%
  \@namedef{@twocol@footgroup#1}{{%
    \@nameuse{foottextfont#1} \splittopskip=\ht\strutbox
     \m@mrigidbalance{\@nameuse{footins#1}}{\tw@}{\splittopskip}}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@mptwocol@footgroup}
% \cs{m@make@mptwocol@footgroup}\marg{series} creates
% \cs{@mptwocol@footgroup}\meta{series}
%    \begin{macrocode}
\newcommand{\m@make@mptwocol@footgroup}[1]{%
\@namedef{@mptwocol@footgroup#1}{{%
  \@nameuse{foottextfont#1} \splittopskip=\ht\strutbox
  \m@mrigidbalance{\@nameuse{@mpfootins#1}}{\tw@}{\splittopskip}}}}

%    \end{macrocode}
% \end{macro}
%
%
% \subsubsection{Three column footnotes}
%
% \begin{macro}{\threecolumnfootnotes}
% Declaration for three column footnotres.
% \changes{v1.61}{2004/03/14}{Made [RS] change to \cs{threecolumnfootnotes}}
%    \begin{macrocode}
\newcommand{\threecolumnfootnotes}{%
  \@namedef{foottextfontv@r}{\foottextfont}%  % [RS]
  \let\@footnotetext\@threecolfootnotetext
  \dimen\footinsv@r=3\footinsdim
  \count\footinsv@r=333\relax
  \m@make@threecol@footgroup{v@r}%
  \let\@footgroupv@r\@threecol@footgroupv@r
  \let\@mpfootnotetext\@mpthreecolfootnotetext 
  \m@make@mpthreecol@footgroup{v@r}%
  \let\mp@footgroupv@r\@mpthreecol@footgroupv@r}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@threecolfootnotetext}
% \cs{@threecolfootnotetext}\marg{text} is the three column version of
% \cs{@footnotetext}
% \changes{v3.6g}{2010/09/19}{made 'single spacing' configurable}
% \changes{v3.8}{2023/07/26}{added the missing \cs{@currentcounter}}
%    \begin{macrocode}
\newcommand{\@threecolfootnotetext}[1]{\insert\footinsv@r{%
  \def\baselinestretch{\m@m@footnote@spacing}%   
  \reset@font\foottextfont
  \@preamfntext
  \def\@currentcounter{footnote}%
  \protected@edef\@currentlabel{%
    \csname p@footnote\endcsname\@thefnmark}%
  \color@begingroup
    \@threecolfootfmt{#1}%
  \color@endgroup}\m@mmf@prepare}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@preamthreefmt}
% Give each column 0.3 of the text width.
%    \begin{macrocode}
\newcommand{\@preamthreefmt}{%
  \hsize .3\hsize
  \parindent=\z@
  \tolerance=5000\relax
  \raggedright
  \leavevmode}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@threecolfootfmt}
%
% \changes{v3.8}{2023/07/27}{removed group around \cs{footnotetext}}
%    \begin{macrocode}
\newcommand{\@threecolfootfmt}[1]{%
  \@preamthreefmt
  {\footfootmark\strut \foottextfont #1\strut\par}\allowbreak}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@mpthreecolfootnotetext}
% \cs{@mpthreecolfootnotetext}\marg{text} is the three column version of
% \cs{@mpfootnotetext}
% \changes{v3.6g}{2010/09/19}{made 'single spacing' configurable}
% \changes{v3.8}{2023/07/26}{added the missing \cs{@currentcounter}}
%    \begin{macrocode}
\newcommand{\@mpthreecolfootnotetext}[1]{%
  \global\setbox\@mpfootinsv@r\vbox{%
    \unvbox\@mpfootinsv@r
    \def\baselinestretch{\m@m@footnote@spacing}%  
    \reset@font\foottextfont 
    \hsize\columnwidth \@parboxrestore
    \def\@currentcounter{mpfootnote}%
    \protected@edef\@currentlabel{%
      \csname p@mpfootnote\endcsname\@thefnmark}%
  \color@begingroup
    \@threecolfootfmt{#1}%
  \color@endgroup}\m@mmf@prepare}

%    \end{macrocode}
% \end{macro}
%
%
%
% \begin{macro}{\threecolumnfootstyle}
% \cs{threecolumnfootstyle}\marg{series} specifies three column footnote style
% for \meta{series}
%    \begin{macrocode}
\newcommand{\threecolumnfootstyle}[1]{%
  \m@make@threecolfootnotetext{#1}%
  \m@make@mpthreecolfootnotetext{#1}%
  \m@make@threecolfootfmt{#1}%
  \m@make@threecol@footgroup{#1}%
  \m@make@mpthreecol@footgroup{#1}%
  \m@make@footstart{#1}%
  \@namelongdef{@footnotetext#1}##1{%
    \@nameuse{@threecolfootnotetext#1}{##1}}%
  \@namelongdef{@mpfootnotetext#1}##1{%
    \@nameuse{@mpthreecolfootnotetext#1}{##1}}%
  \@namedef{@footgroup#1}{\@nameuse{@threecol@footgroup#1}}%
  \@namedef{mp@footgroup#1}{\@nameuse{@mpthreecol@footgroup#1}}%
  \expandafter\dimen\csname footins#1\endcsname=3\footinsdim
  \expandafter\count\csname footins#1\endcsname=333\relax}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@threecolfootnotetext}
% \cs{m@make@threecolfootnotetext}\marg{series} creates
% \cs{@threecolfootnotetext}\meta{series}
% \changes{v3.6g}{2010/09/19}{made 'single spacing' configurable}
% \changes{v3.8}{2023/07/26}{added the missing \cs{@currentcounter}}
%    \begin{macrocode}
\newcommand{\m@make@threecolfootnotetext}[1]{%
\@namelongdef{@threecolfootnotetext#1}##1{%
  \insert\@nameuse{footins#1}{%
  \def\baselinestretch{\m@m@footnote@spacing}%  
  \reset@font\@nameuse{foottextfont#1}%
  \@preamfntext
  \def\@currentcounter{footnote}%
  \protected@edef\@currentlabel{%
    \csname p@footnote#1\endcsname \@nameuse{@thefnmark#1}}%
  \color@begingroup
    \@nameuse{@threecolfootfmt#1}{##1}%
  \color@endgroup}\m@mmf@prepare}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@mpthreecolfootnotetext}
% \cs{m@make@mpthreecolfootnotetext}\marg{series} creates
% \cs{@mpthreecolfootnotetext}\meta{series}
% \changes{v3.6g}{2010/09/19}{made 'single spacing' configurable}
% \changes{v3.8}{2023/07/26}{added the missing \cs{@currentcounter}}
%    \begin{macrocode}
\newcommand{\m@make@mpthreecolfootnotetext}[1]{%
\@namelongdef{@mpthreecolfootnotetext#1}##1{%
  \global\setbox\@nameuse{@mpfootins#1}\vbox{%
    \unvbox\@nameuse{@mpfootins#1}
    \def\baselinestretch{\m@m@footnote@spacing}%   
    \reset@font\@nameuse{foottextfont#1}%
    \hsize\columnwidth \@parboxrestore
    \def\@currentcounter{mpfootnote}%
    \protected@edef\@currentlabel{%
      \csname p@mpfootnote#1\endcsname\@nameuse{@thefnmark#1}}%
  \color@begingroup
    \@nameuse{@threecolfootfmt#1}{##1}%
  \color@endgroup}\m@mmf@prepare}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@threecolfootfmt}
% \cs{m@make@threecolfootfmt}\marg{series} creates
% \cs{@threecolfootfmt}\meta{series}
% \changes{v1.61}{2004/03/14}{Removed space from \cs{m@make@threecolfootfmt} [RS]}
% \changes{v3.8}{2023/07/27}{removed group around \cs{footnotetext}}
%    \begin{macrocode}
\newcommand{\m@make@threecolfootfmt}[1]{%
\@namelongdef{@threecolfootfmt#1}##1{%
  \@preamthreefmt
  {\@nameuse{footfootmark#1}\strut 
    \@nameuse{foottextfont#1}##1\strut\par}\allowbreak}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@threecol@footgroup}
% \cs{m@make@threecol@footgroup}\marg{series} creates
% \cs{@threecol@footgroup}\meta{series} 
%    \begin{macrocode}
\newcommand{\m@make@threecol@footgroup}[1]{%
\@namedef{@threecol@footgroup#1}{{%
  \@nameuse{foottextfont#1} \splittopskip=\ht\strutbox
  \m@mrigidbalance{\@nameuse{footins#1}}{\thr@@}{\splittopskip}}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@mpthreecol@footgroup}
% \cs{m@make@mpthreecol@footgroup}\marg{series} creates
% \cs{@mpthreecol@footgroup}\meta{series} 
%    \begin{macrocode}
\newcommand{\m@make@mpthreecol@footgroup}[1]{%
\@namedef{@mpthreecol@footgroup#1}{{%
  \@nameuse{foottextfont#1} \splittopskip=\ht\strutbox
  \m@mrigidbalance{\@nameuse{@mpfootins#1}}{\thr@@}{\splittopskip}}}}

%    \end{macrocode}
% \end{macro}
%
%
% \subsubsection{Paragraphed footnotes}
%
% Paragraphed footnotes are based on \theTeXbook, page 398ff, in the 
% Dirty Tricks appendix. It does a lot of box manipulations.
%
% \begin{macro}{\m@munvxh}
% \cs{m@munvxh}\marg{vbox}: unvbox, extract the last line, and unhbox it.
%    \begin{macrocode}
\newcommand{\m@munvxh}[1]{%
  \setbox0=\vbox{\unvbox#1%
    \global\setbox1=\lastbox}%
  \unhbox1
  \unskip
  \unskip
  \unpenalty
  \hskip\m@mipn@skip}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@mungebox}
%
%    \begin{macrocode}
\newcommand{\m@mungebox}{%
  \setbox0=\hbox{\m@munvxh0}%
  \dp0=\z@
  \ht0=\footfudgefactor\wd0
  \box0
  \penalty0}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@mipn@skip}
% \begin{macro}{\m@minterparanoteglue}
% These are `inter-para-note-skip' and `inter-parafootnote' glue, for 
% paragraphed footnotes.
%    \begin{macrocode}
\newskip\m@mipn@skip
\newcommand*{\m@minterparanoteglue}[1]{%
  {\foottextfont\global\m@mipn@skip=#1\relax}}
\m@minterparanoteglue{1em plus.4em minus.4em}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\m@mmakehboxofhboxes}
% Make an hbox of hboxes.
%    \begin{macrocode}
\newcommand*{\m@mmakehboxofhboxes}{\setbox0=\hbox{}%
  \loop
    \unpenalty
    \setbox2=\lastbox
  \ifhbox2
    \setbox0=\hbox{\box2\unhbox0}
  \repeat}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@mremovehboxes}
%    \begin{macrocode}
\newcommand*{\m@mremovehboxes}{\setbox0=\lastbox
  \ifhbox0{\m@mremovehboxes}\unhbox0 \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\footfudgefiddle}
% TeX uses \verb?\footfufgefactor? to estimate the space required for
% paragraphed footnotes. If it underestimates then the notes approach,
% or cover, the footer. \verb?\footfudgefiddle? can be changed (upward) from
% its default to improve matters.
%    \begin{macrocode}
\newcommand*{\footfudgefiddle}{64}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\paragraphfootnotes}
% Declaration for paragraphed footnotes.
% \changes{v1.61}{2004/03/14}{Made [RS] change to \cs{paragraphfootnotes}}
%    \begin{macrocode}
\newcommand{\paragraphfootnotes}{%
  \@namedef{foottextfontv@r}{\foottextfont}%  % [RS]
  \let\@footnotetext\@parafootnotetext
  \dimen\footinsv@r=\footinsdim
  \count\footinsv@r=1000\relax
  \m@make@para@footgroup{v@r}%
  \let\@footgroupv@r\@para@footgroupv@r
  \let\@mpfootnotetext\@mpparafootnotetext 
  \m@make@mppara@footgroup{v@r}%
  \let\mp@footgroupv@r\@mppara@footgroupv@r
  {\foottextfont
   \dimen0=\baselineskip
%    \end{macrocode}
% Multiplying \cs{dimen0} by 1024 can lead to arithmetic overflow if
% \cs{baselineskip} is too large, for example under
% \cs{DoubleSpacing}. Instead we only multiply by 256 and then
% multiply again by 4 after the division by \cs{hsize}.
% \changes{v3.7r}{2022/07/28}{Changed calculation}
%    \begin{macrocode}
   %\multiply\dimen0 by 1024
   \multiply\dimen0 by 256
   \divide\dimen0   by \hsize
   \multiply\dimen0 by 4
   \multiply\dimen0 by \footfudgefiddle
   \xdef\footfudgefactor{\expandafter\strip@pt\dimen0 }}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@parafootnotetext}
% \cs{@parafootnotetext}\marg{text} is a paragraph version of
% \cs{@footnotetext}
% \changes{v3.6g}{2010/09/19}{made 'single spacing' configurable}
% \changes{v3.8}{2023/07/26}{added the missing \cs{@currentcounter}}
%    \begin{macrocode}
\newcommand{\@parafootnotetext}[1]{\insert\footinsv@r{
  \def\baselinestretch{\m@m@footnote@spacing}%  
  \reset@font\foottextfont
  \@preamfntext
  \def\@currentcounter{footnote}%
  \protected@edef\@currentlabel{%
    \csname p@footnote\endcsname\@thefnmark}%
  \setbox0=\vbox{\hsize=\maxdimen
    \color@begingroup
      \noindent \@parafootfmt{#1}%
    \color@endgroup}%
  \m@mungebox}\m@mmf@prepare}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@parafootfmt}
% \cs{@parafootfmt}\marg{text} is a paragraph version of
% \cs{@footfmt}
% \changes{v3.8}{2023/07/27}{removed group around \cs{footnotetext}}
%    \begin{macrocode}
\newcommand{\@parafootfmt}[1]{%
  \parindent=\z@
  \parfillskip=0pt \@plus 1fil
  {\footfootmark\strut \foottextfont #1\penalty-10}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@mpparafootnotetext}
% \cs{@mpparafootnotetext}\marg{text} is a paragraph version of
% \cs{@mpfootnotetext}
% \changes{v3.6g}{2010/09/19}{made 'single spacing' configurable}
% \changes{v3.8}{2023/07/26}{adding the missing \cs{@currentcounter}}
%    \begin{macrocode}
\newcommand{\@mpparafootnotetext}[1]{%
  \global\setbox\@mpfootinsv@r\vbox{%
    \unvbox\@mpfootinsv@r
    \def\baselinestretch{\m@m@footnote@spacing}%   
    \reset@font\foottextfont 
    \hsize\columnwidth \@parboxrestore
    \def\@currentcounter{mpfootnote}%
    \protected@edef\@currentlabel{%
      \csname p@mpfootnote\endcsname\@thefnmark}%
    \setbox0=\vbox{\hsize=\maxdimen
      \color@begingroup
      \noindent \@parafootfmt{#1}%
      \color@endgroup}%
  \m@mungebox}\m@mmf@prepare}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\paragraphfootstyle}
% \cs{paragraphfootstyle}\marg{series} specifies paragraphed footnote style
% for \meta{series}.
%    \begin{macrocode}
\newcommand{\paragraphfootstyle}[1]{%
  \m@make@parafootnotetext{#1}%
  \m@make@mpparafootnotetext{#1}%
  \m@make@parafootfmt{#1}%
  \m@make@para@footgroup{#1}%
  \m@make@mppara@footgroup{#1}%
  \m@make@para@footstart{#1}%
  \@namelongdef{@footnotetext#1}##1{%
    \@nameuse{@parafootnotetext#1}{##1}}%
  \@namelongdef{@mpfootnotetext#1}##1{%
    \@nameuse{@mpparafootnotetext#1}{##1}}%
  \@namedef{@footgroup#1}{\@nameuse{@para@footgroup#1}}%
  \@namedef{mp@footgroup#1}{\@nameuse{@mppara@footgroup#1}}%
  \@namedef{@footstart#1}{\@nameuse{@para@footstart#1}}%
  \expandafter\dimen\csname footins#1\endcsname=\footinsdim
  \expandafter\count\csname footins#1\endcsname=1000\relax
  {\@nameuse{foottextfont#1}%
   \dimen0=\baselineskip
%    \end{macrocode}
% Similar issue with arithmetic overflow as mentioned with \cs{paragraphfootnotes}.
% \changes{v3.7r}{2022/07/28}{Changed calculation}
%    \begin{macrocode}
   %\multiply\dimen0 by 1024
   \multiply\dimen0 by 256
   \divide\dimen0   by \hsize
   \multiply\dimen0 by 4
%    \end{macrocode}
% \changes{v3.7r}{2022/07/28}{Changed 64 to \cs{footfudgefiddle}}
%    \begin{macrocode}
   \multiply\dimen0 by \footfudgefiddle
   \xdef\footfudgefactor{\expandafter\strip@pt\dimen0 }}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@parafootnotetext}
% \cs{m@make@parafootnotetext}\marg{series} creates
% \cs{@parafootnotetext}\meta{series} 
% \changes{v3.6g}{2010/09/19}{made 'single spacing' configurable}
% \changes{v3.8}{2023/07/26}{added the missing \cs{@currentcounter}}
%    \begin{macrocode}
\newcommand{\m@make@parafootnotetext}[1]{%
\@namelongdef{@parafootnotetext#1}##1{%
  \insert\@nameuse{footins#1}{
  \def\baselinestretch{\m@m@footnote@spacing}%   
  \reset@font\@nameuse{foottextfont#1}%
  \@preamfntext
  \def\@currentcounter{footnote}%
  \protected@edef\@currentlabel{%
    \csname p@footnote#1\endcsname \@nameuse{@thefnmark#1}}%
  \setbox0=\vbox{\hsize=\maxdimen
    \color@begingroup
      \noindent \@nameuse{@parafootfmt#1}{##1}%
    \color@endgroup}%
  \m@mungebox}\m@mmf@prepare}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@mpparafootnotetext}
% \cs{m@make@mpparafootnotetext}\marg{series} creates
% \cs{@mpparafootnotetext}\meta{series} 
% \changes{v3.6g}{2010/09/19}{made 'single spacing' configurable}
% \changes{v3.8}{2023/07/26}{added the missing \cs{@currentcounter}}
%    \begin{macrocode}
\newcommand{\m@make@mpparafootnotetext}[1]{%
\@namelongdef{@mpparafootnotetext#1}##1{%
  \global\setbox\@nameuse{@mpfootins#1}\vbox{%
    \unvbox\@nameuse{@mpfootins#1}
    \def\baselinestretch{\m@m@footnote@spacing}%   
    \reset@font\@nameuse{foottextfont#1}%
    \hsize\columnwidth \@parboxrestore
    \def\@currentcounter{mpfootnote}%
    \protected@edef\@currentlabel{%
      \csname p@mpfootnote#1\endcsname\@nameuse{@thefnmark#1}}%
    \setbox0=\vbox{\hsize=\maxdimen
      \color@begingroup
        \noindent \@nameuse{@parafootfmt#1}{##1}%
      \color@endgroup}%
    \m@mungebox}\m@mmf@prepare}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@parafootfmt}
% \cs{m@make@parafootfmt}\marg{series} creates
% \cs{@parafootfmt}\meta{series} 
% \changes{v1.61}{2004/03/14}{Removed space from \cs{m@make@parafootfmt} [RS]}
% \changes{v3.8}{2023/07/27}{removed group around \cs{footnotetextX}}
%    \begin{macrocode}
\newcommand{\m@make@parafootfmt}[1]{%
\@namelongdef{@parafootfmt#1}##1{%
  \parindent=\z@
  \parfillskip=0pt \@plus 1fil
  {\@nameuse{footfootmark#1}\strut 
   \@nameuse{foottextfont#1}##1\penalty-10}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@para@footgroup}\marg{series} creates
% \cs{@para@footgroup}\meta{series}
%    \begin{macrocode}
\newcommand{\m@make@para@footgroup}[1]{%
\@namedef{@para@footgroup#1}{%
  \unvbox\@nameuse{footins#1}
  \m@mmakehboxofhboxes
  \setbox0=\hbox{\unhbox0 \m@mremovehboxes}%
  \@nameuse{foottextfont#1}%
  \noindent\unhbox0\par}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@mppara@footgroup}
% \cs{m@make@mppara@footgroup}\marg{series} creates
% \cs{@mppara@footgroup}\meta{series} 
%    \begin{macrocode}
\newcommand{\m@make@mppara@footgroup}[1]{%
\@namedef{@mppara@footgroup#1}{%
  \unvbox\@nameuse{@mpfootins#1}
  \m@mmakehboxofhboxes
  \setbox0=\hbox{\unhbox0 \m@mremovehboxes}%
  \@nameuse{foottextfont#1}%
  \noindent\unhbox0\par}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@para@footstart}
% \cs{m@make@para@footstart}\marg{series} creates
% \cs{@para@footstart}\meta{series} 
%    \begin{macrocode}
\newcommand{\m@make@para@footstart}[1]{%
\@namedef{@para@footstart#1}{%
  \vskip\bigskipamount
  \leftskip=\z@
  \rightskip=\z@
  \parindent=\z@
  \vskip\skip\@nameuse{footins#1}%
  \footnoterule}}

%    \end{macrocode}
% \end{macro}
%
% \subsection{Nasty insert bits}
% \changes{v1.61803}{2008/01/30}{Put \cs{@makecol} and associated code
%           into new section `Nasty insert bits' (mempatch various)}
%
% \cs{sidebar} is implemented as a new kind of \cs{insert} and the 
% extended footnotes are also implemented via new kinds of \cs{insert}s.
% New \cs{insert}s mean that the kernel's \cs{@makecol} must be revised
% to cater for them. As this is part of the output process it is nasty to
% do.
%
% Before v1.61803 \cs{@makecol} got (re)defined at several points in the 
% code. Here is what I hope is the final version od \cs{@makecol} and
% associated code after having resolved and combined all the changes.
%
%
% \begin{macro}{\if@mem@nofoot}
% \begin{macro}{\@mem@testifnofoot}
% \begin{macro}{\@mem@extranofoot}
% These are from [RS] as \cs{@doclearpage} should check for more than
% just \cs{footins} being void. Note that this covers all current
% class defined inserts, including sidebars.
% \changes{v1.61}{2004/03/14}{Added \cs{if@mem@nofoot}, 
%                              \cs{@mem@testifnofoot}, and
%                              \cs{@mem@extranofoot}}
%    \begin{macrocode}
\newif\if@mem@nofoot
\newcommand*{\@mem@testifnofoot}{%
  \@mem@nofoottrue
  \ifvoid\footins\else\@mem@nofootfalse\fi
  \ifvoid\footinsv@r\else\@mem@nofootfalse\fi
  \ifvoid\sideins\else\@mem@nofootfalse\fi
  \@mem@extranofeet}
\newcommand*{\@mem@extranofeet}{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\memold@doclearpage}
% \begin{macro}{\mem@doclearpage}
% \begin{macro}{\@doclearpage}
% I thought that I could get away with using the kernel's 
% \cs{@doclearpage} but [RS] discovered that I couldn't.
% \changes{v1.62}{2004/03/14}{Redid \cs{@doclearpage} using [RS] code}
% \changes{v3.7d}{2015/04/23}{Opdated \cs{mem@doclearpage} to match
% \Lpack{fixltx2e} v1.1s (which will be the base of the ltx kernel for
% TL15)}
%    \begin{macrocode}
\let\memold@doclearpage\@doclearpage
\newcommand{\mem@doclearpage}{%
  \@mem@testifnofoot
  \if@mem@nofoot
    \setbox\@tempboxa\vsplit\@cclv to\z@ \unvbox\@tempboxa
    \setbox\@tempboxa\box\@cclv
    \xdef\@deferlist{\@toplist\@botlist\@deferlist}%
    \global \let \@toplist \@empty
    \global \let \@botlist \@empty
    \global \@colroom \@colht
    \ifx \@currlist\@empty
    \else
       \@latexerr{Float(s) lost}\@ehb
       \global \let \@currlist \@empty
    \fi
    \@makefcolumn\@deferlist
    \@whilesw\if@fcolmade \fi{\@opcol\@makefcolumn\@deferlist}%
    \if@twocolumn
      \if@firstcolumn
        \xdef\@deferlist{\@dbltoplist\@deferlist}%
        \global \let \@dbltoplist \@empty
        \global \@colht \textheight
        \begingroup
           \@dblfloatplacement
           \@makefcolumn\@deferlist
           \@whilesw\if@fcolmade \fi{\@outputpage
                                     \@makefcolumn\@deferlist}%
         \endgroup
       \else
        \vbox{}\clearpage
      \fi
    \fi
    \ifx\@deferlist\@empty \else\clearpage \fi
  \else
    \setbox\@cclv\vbox{\box\@cclv\vfil}%
    \@makecol\@opcol
    \clearpage
  \fi
  % older version
  %   \setbox\@tempboxa\vsplit\@cclv to\z@ \unvbox\@tempboxa
  %   \setbox\@tempboxa\box\@cclv
  %   \xdef\@deferlist{\@toplist\@botlist\@deferlist}%
  %   \global\let\@toplist\@empty
  %   \global\let\@botlist\@empty
  %   \global\@colroom\@colht
  %   \ifx \@currlist\@empty
  %   \else
  %     \@latexerr{Float(s) lost}\@ehb
  %     \global\let\@currlist\@empty
  %   \fi
  %   \@makefcolumn\@deferlist
  %   \@whilesw\if@fcolmade \fi{\@opcol\@makefcolumn\@deferlist}%
  %   \if@twocolumn
  %     \if@firstcolumn
  %       \xdef\@dbldeferlist{\@dbltoplist\@dbldeferlist}%
  %       \global\let\@dbltoplist\@empty
  %       \global\@colht\textheight
  %       \begingroup
  %         \@dblfloatplacement
  %         \@makefcolumn\@dbldeferlist
  %         \@whilesw\if@fcolmade \fi{\@outputpage
  %                                   \@makefcolumn\@dbldeferlist}%
  %       \endgroup
  %     \else
  %       \vbox{}\clearpage
  %     \fi
  %   \fi
  % \else
  %   \setbox\@cclv\vbox{\box\@cclv\vfil}%
  %   \@makecol\@opcol
  %   \clearpage
  % \fi
}
%    \end{macrocode}
% Replace the kernel's \cs{@doclearpage}.
%    \begin{macrocode}
\gdef\@doclearpage{\mem@doclearpage}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\m@m@makecolfloats}
% \begin{macro}{\m@m@makecoltext}
% These two macros contain code common to versions of \cs{@makecol}
% \changes{v3.7q}{2022/02/20}{Added the \cs{@elt} line from the kernel}
%    \begin{macrocode}
\newcommand*{\m@m@makecolfloats}{%
  \let\@elt\relax%
  \xdef\@freelist{\@freelist\@midlist}%
  \global\let\@midlist\@empty
  \@combinefloats}
%    \end{macrocode}
%   \changes{v3.8c}{2025/07/14}{Fixed typo in first branch. BTW: is this even different from the kernel version?}
%    \begin{macrocode}
\newcommand*{\m@m@makecoltext}{%
  \ifvbox\@kludgeins
    \@make@specialcolbox
  \else
    \setbox\@outputbox \vbox to\@colht{%
      \@texttop
      \dimen@ \dp\@outputbox
      \unvbox \@outputbox
      \vskip -\dimen@
      \@textbottom}%
  \fi}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\m@m@makecolintro}
% A hook into the revised \cs{@makecol}
%    \begin{macrocode}
\newcommand*{\m@m@makecolintro}{}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@mopfootnote}
% (footnote) code for possible use in \cs{@makecol}.
% \changes{v3.7d}{2015/04/21}{Added feature to force footnotes to the
% bottom of the page in a ragged context}
%    \begin{macrocode}
\newcommand*{\m@mopfootnote}{\setbox\@outputbox \vbox{%
  \boxmaxdepth\@maxdepth
  \@tempdima\dp\@cclv
  \unvbox\@cclv
  \vskip-\@tempdima
%    \end{macrocode}
% We then add a macro call that is only activated if we are not using
% \cs{flushbottom}. If \cs{feetatbottom} is active, then a
% \cs{vfill} is added. Solution inspired by \Lpack{footmisc}.
%    \begin{macrocode}
  \mem@if@flushbottomF\m@mopfn@bottom
  \vskip \skip\footins
  \color@begingroup
    \normalcolor
    \footnoterule
    \unvbox \footins
  \color@endgroup}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@mopfootnotebf}
%   (footnote) code in support of footnotes below floats.  Problem
%   with original code noted by J{\o}rgen Larsen on
%   2008/05/24. Updated 2015.
% \changes{v1.618033}{2008/06/02}{Added \cs{m@mopfootnotebf}}
% \changes{v3.7d}{2015/04/21}{Added feature to force footnotes to the
% bottom of the page in a ragged context}
%    \begin{macrocode}
\newcommand*{\m@mopfootnotebf}{%
  \setbox\@outputbox \vbox{%
  \boxmaxdepth\@maxdepth
  \unvbox\@outputbox
%    \end{macrocode}
% We then add a macro call as above.
%    \begin{macrocode}
  \mem@if@flushbottomF\m@mopfn@bottom
  \vskip\skip\footins
  \color@begingroup
    \normalcolor
    \footnoterule
    \unvbox \footins
  \color@endgroup}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@mopsidebar}
% (sidebar) code for possible use in \cs{@makecol}.
% From DA's latest sidebar fixes.
%    \begin{macrocode}
\newcommand*{\m@mopsidebar}{%
  \ifvoid\sideins\else
    \setbox\@outputbox \vbox{%
      \sidecontents
      \unvbox\@outputbox}
  \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\mem@makecol}
% DA's latest version of \cs{@makecol} (giving the standard 
% footnote order (bottom floats after footnotes)) putting the sidebar
% insert after the others (from mempatch v4.9). The code is renewed on
% page~\pageref{makecol} onwards.
%    \begin{macrocode}
 % \gdef\mem@makecol{%
 %   \m@m@makecolintro
 %   \ifvoid\footins
 %     \setbox\@outputbox \box\@cclv
 %   \else
 %     \m@mopfootnote
 %   \fi
 %   \m@mdoextrafeet
 %   \m@m@makecolfloats
 %   \m@mopsidebar
 %   \m@m@makecoltext
 %   \global \maxdepth \@maxdepth}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\mem@makecolbf}
% A version of \cs{@makecol} which puts footnotes at the bottom of the page
% (after any bottom floats). The code is renewed on
% page~\pageref{makecol} onwards.
% \changes{v1.618033}{2008/06/02}{Used \cs{m@mopfootnotebf} instead of
%                     \cs{m@mopfootnote} in \cs{mem@makecolbf}}
%    \begin{macrocode}
 % \gdef\mem@makecolbf{%
 %   \m@m@makecolintro
 %   \setbox\@outputbox \box\@cclv
 %   \m@m@makecolfloats
 %   \ifvoid\footins\else
 %     \m@mopfootnotebf
 %   \fi
 %   \m@mdoextrafeet
 %   \m@mopsidebar
 %   \m@m@makecoltext
 %   \global\maxdepth \@maxdepth}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\mem@makecoldblf}
% A version of \cs{@makecol} which is a placeholder to fix the doublefloat
% problem. 
% TODO: remove this code it is not used
%    \begin{macrocode}
\gdef\mem@makecoldblf{%
  \m@m@makecolintro
  \setbox\@outputbox \box\@cclv
  \m@m@makecolfloats
  \m@mopsidebar%    <- added
  \ifvoid\footins
  \else
    \m@mopfootnote
  \fi
  \m@mdoextrafeet
  \m@m@makecoltext
  \global \maxdepth \@maxdepth}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\feetabovefloat}
% \begin{macro}{\feetbelowfloat}
% \begin{macro}{\@makecol}
% declarations to put footnotes above bottom floats (standard \LaTeX)
% or at the bottom of the page
%    \begin{macrocode}
\newcommand{\feetabovefloat}{\gdef\@makecol{\mem@makecol}}
\newcommand{\feetbelowfloat}{\gdef\@makecol{\mem@makecolbf}}
\feetabovefloat

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\feetatbottom}
% \begin{macro}{\feetbelowragged}
% \begin{macro}{\m@mopfn@bottom}
% \begin{macro}{\mem@if@flushbottomF}
%   If a page is typeset with a ragged bottom then any footnotes are
%   added directly under the text. It may look better if the footnotes
%   are added to the text block from the bottom up.
%    \begin{macrocode}
\newcommand\feetatbottom{\def\m@mopfn@bottom{\vfill\relax}}
\newcommand\feetbelowragged{\let\m@mopfn@bottom\relax}
\feetbelowragged
%    \end{macrocode}
% Next we add a test to see if \cs{flushbottom} is active. This macro
% is used within \cs{m@mopfootnote} and \cs{m@mopfootnotebf} to
% force the footnotes to the bottom \emph{only} when \cs{flushbottom}
% is \emph{not} active, hince the \texttt{F} in the name.
%    \begin{macrocode}
\newcommand\mem@if@flushbottomF[1]{%
  \if\mem@flshbot\else#1\fi%
}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@reinserts}
% DA's final version from last patch.
% \changes{v3.6d}{2010/06/30}{THere is a newer version further down
% the code}
%    \begin{macrocode}
 % \gdef\@reinserts{%
 % \ifvoid\footins\else\insert\footins{\unvbox\footins}\fi
 % \m@mdodoreinextrafeet
 % \ifvbox\@kludgeins\insert\@kludgeins{\unvbox\@kludgeins}\fi
 %  \ifvoid\sideins\else\insert\sideins{\unvbox\sideins}\fi}

%    \end{macrocode}
% \end{macro}
%
% \changes{v1.61803398d}{2010/01/25}{Added section about side footnotes}
% \subsection{Side footnotes} \label{sec:sidefootnotes}
%
%
% \subsubsection{Extension to the regular footnote}
%
%  The code here enables the regular \cs{footnote} to be set in the
% margin. It is based on Robin Fairbairns' \Lpack{footmisc} package.
%
% \begin{macro}{\ifm@mfnmargin}
% \begin{macro}{\footnotesatfoot}
% \begin{macro}{\footnotesinmargin}
% Declarations for regular footnotes to be set as normal at the foot
% of the page, or in the margin.
%    \begin{macrocode}
\newif\ifm@mfnmargin
\newcommand*{\footnotesatfoot}{\m@mfnmarginfalse}
\newcommand*{\footnotesinmargin}{\m@mfnmargintrue}
\footnotesatfoot

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \changes{v1.61803398d}{2010/01/25}{Remember that we actually have
% several \cs{@footnotetext} in memoir, might be an idea to clean this
% up at some point/daleif}
% \begin{macro}{\@footnotetext}
% \begin{macro}{\m@mold@footnotetext}
% Change \cs{@footnotetext} to enable footnotes to be put into the margin
% by using \cs{marginpar}.
%    \begin{macrocode}
\renewcommand{\@footnotetext}[1]{%
  \ifm@mfnmargin%   use marginpar
%    \end{macrocode}
% Use \cs{marginpar} for placing the footnote.
% \changes{v3.6g}{2010/09/19}{made 'single spacing' configurable}
% \changes{v3.8}{2023/07/26}{added the missing \cs{@currentcounter}}
%    \begin{macrocode}
    \marginpar{%
    \def\baselinestretch{\m@m@footnote@spacing}%
    \reset@font
    \foottextfont
    \def\@currentcounter{footnote}%
    \protected@edef\@currentlabel{%
      \csname p@footnote\endcsname\@thefnmark}%
    \color@begingroup
      \@makefntext{\ignorespaces#1}%
    \color@endgroup}%
  \else% regular feet
%    \end{macrocode}
% This is the original code for \cs{@footnotetext}.
% \changes{v1.618033988c}{2010/02/20}{sporadic spaces removed, error
% reported on texlive mailinglist}
% \changes{v3.6g}{2010/09/19}{made 'single spacing' configurable}
% \changes{v3.8}{2023/07/26}{added the missing \cs{@currentcounter}}
% \changes{v3.8}{2023/07/27}{removed group around \cs{footnotetext}}
%    \begin{macrocode}
    \insert\footins{%
    \def\baselinestretch{\m@m@footnote@spacing}%
    \reset@font
    \foottextfont
    \@preamfntext
    \hsize\columnwidth
    \def\@currentcounter{footnote}%
    \protected@edef\@currentlabel{%
      \csname p@footnote\endcsname\@thefnmark}%
    \color@begingroup
      \@makefntext{%
        \rule\z@\footnotesep\ignorespaces\foottextfont #1%
        \@finalstrut\strutbox}%
    \color@endgroup}%
  \fi%
  \m@mmf@prepare}
%    \end{macrocode}
% Need to save this version of \cs{@footnotetext}, it is
% used within \cs{plainfootnotes}.
% \changes{v3.6h}{2010/10/22}{Moved \cs{m@mold@footnotetext} to this
% location, and renamed it to \cs{@plainfootnotetext}}
%    \begin{macrocode}
\let\@plainfootnotetext\@footnotetext

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \subsection{Bottom aligned side footnotes}
%
% The code for the bottom aligned marginal footnotes is based partly on
% the \cs{sidebar} code and code from David Salomon, 'Output Routines:
% Examples and Techniques. Part III: Insertions', \textit{TUGboat}, 
% 11, 4, pp 588--605, Nov 1990.
%
% \begin{macro}{\sidefootmargin}
% \begin{macro}{\m@msidefoot@margin}
% \cs{sidefootmargin} is the user command for setting the side for
% side footnotes (stored as \cs{m@msidefoot@margin}). The default
% is \texttt{outer}.
%    \begin{macrocode}
\newcommand*{\sidefootmargin}[1]{%
  \m@msetm@argin{#1}%
  \ifnum\m@mm@argin<\z@
    \@memwarn{Bad \string\sidefootmargin\space argument `#1'\MessageBreak
              set to `outer'}%
    \gdef\m@msidefoot@margin{2}%   set as outer
  \else
    \global\let\m@msidefoot@margin\m@mm@argin
  \fi}
\sidefootmargin{outer}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\sidefootins}
% As for any non-main text matter we need an insert.
%    \begin{macrocode}
\newinsert\sidefootins
  \skip\sidefootins=0pt
  \count\sidefootins=0\relax

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sidefootadjust}
% \begin{macro}{\sidefootheight}
% \begin{macro}{\setsidefootheight}
% The length \cs{sidefootadjust} can be used for fine control over the
% vertivcal position of the base of the column of side footnotes. 
% The length \cs{sidefootheight}
% is the height of the column and is best set by the \cs{setsidefootheight}
% macro, which takes the desired height as its argument and sets the height
% of the \cs{sidefootins} \cs{insert}. The height is
% initially set to the \cs{textheight}.
%    \begin{macrocode}
\newlength{\sidefootadjust}
  \setlength{\sidefootadjust}{0pt}
\newlength{\sidefootheight}
\newcommand*{\setsidefootheight}[1]{%
  \setlength{\dimen\sidefootins}{#1}%
  \advance\dimen\sidefootins -\topskip
  \advance\dimen\sidefootins \ht\strutbox
  \setlength{\sidefootheight}{\dimen\sidefootins}}
\setsidefootheight{\textheight}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\sidefoothsep}
% \begin{macro}{\sidefootwidth}
% \begin{macro}{\sidefootvsep}
% The horizontal space between the text block and side footnotes 
% (\cs{sidefoothsep}), 
% the width of the column of notes (\cs{sidefootwidth}),
% and the vertical space between consecutive side footnotes
% (\cs{sidefootvsep}). 
% \changes{v1.61803398d}{2010/02/05}{removed \cs{sidefootfont}}
%    \begin{macrocode}
\newlength{\sidefoothsep}
\newlength{\sidefootvsep}
\newlength{\sidefootwidth}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\setsidefeet}
% The macro \cs{setsidefeet}\marg{hsep}\marg{width}\marg{vsep}\marg{adj}\marg{font}\marg{height}
% sets the specifications for the side footnotes. An `*' means `use
% the current 
% value'.
% \changes{v1.61803398d}{2010/02/05}{changed \cs{sidefootfont} to 
% \cs{sidefoottextfont}}
%
%    \begin{macrocode}
\newcommand*{\setsidefeet}[6]{%
  \nametest{#1}{*}\ifsamename\else
    \setlength{\sidefoothsep}{#1}\@memznegtest{\sidefoothsep}%
  \fi
  \nametest{#2}{*}\ifsamename\else
    \setlength{\sidefootwidth}{#2}\@memznegtest{\sidefootwidth}%
  \fi
  \nametest{#3}{*}\ifsamename\else
    \setlength{\sidefootvsep}{#3}\@memznegtest{\sidefootvsep}%
  \fi
  \nametest{#4}{*}\ifsamename\else
    \setlength{\sidefootadjust}{#4}%
  \fi
  \nametest{#5}{*}\ifsamename\else
    \def\sidefoottextfont{#5}%
  \fi
  \nametest{#6}{*}\ifsamename\else
    \setsidefootheight{#6}%
    \ifdim\dimen\sidefootins>\z@\else
      \@memerror{\protect\sidefootheight\space is zero or negative}{\@ehd}%
    \fi
  \fi}
\setsidefeet{\marginparsep}{\marginparwidth}%
            {\onelineskip}{0pt}%
            {\normalfont\footnotesize}{\textheight}%

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\sidefootform}
% Set the sidefootnotes raggedy right
%    \begin{macrocode}
\newcommand*{\sidefootform}{\rightskip=\z@ \@plus 2em}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\m@sideft@left}
% \begin{macro}{\m@sideft@right}
% Macros placing the sidefootnotes at the left and the right respectively.
%    \begin{macrocode}
\newcommand*{\m@sideft@left}{%
  \@tempdimc \sidefootwidth
  \advance\@tempdimc\sidefoothsep
  \kern-\@tempdimc}
\newcommand*{\m@sideft@right}{%
  \@tempdimc \columnwidth% or \hsize
  \advance\@tempdimc\sidefoothsep
  \kern\@tempdimc}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\m@mdownsf}
% A length used in the vertical positioning of sidefootnotes.
% (Perhaps one of the \cs{@tempdim} lengths could be used instead?)
%    \begin{macrocode}
\newlength{\m@mdownsf}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sidefootcontents}
% The essence of the sidefootnote task. This first positions the column 
% to the left or the right and then tries to make the bottom of the 
% column align with the bottom of the textblock.
%    \begin{macrocode}
\newcommand*{\sidefootcontents}{\hbox to \z@{%
  \m@mwhich@margin{\m@msidefoot@margin}%
  \ifmemtortm
    \m@sideft@right
  \else
    \m@sideft@left
  \fi
%    \end{macrocode}
% Now the fun part. The general idea is to measure the height of the insert's 
% contents, subtract this from the specified height of the insert, 
% and move the contents down by that amount.
% The code below seems to work except when sidefootnotes
% spill over to the following page; also, like \cs{sidebar}, 
% they are out of vertical alignment when on a \cs{chapter} page. 
% I haven't found a way to automatically
% adjust for these, which is why the \cs{sidefootadjust} length is
% there to enable manual adjustment.
% \changes{v1.61803398d}{2010/02/05}{changed \cs{sidefootfont} 
% to \cs{sidefoottextfont}}
%    \begin{macrocode}
  \vtop to 0pt{%    original
    \normalsize\normalfont\sidefoottextfont
    \vskip\topskip \vskip-\ht\strutbox
    \vskip\sidefootadjust%    use this for minor vertical adjustment
    \m@mdownsf=\dimen\sidefootins
    \advance\m@mdownsf-\ht\sidefootins
    \advance\m@mdownsf-\dp\sidefootins
%    \end{macrocode}
% Here's where the fiddling occurs, arrived at by a mixture of theory and 
% experiment.
%    \begin{macrocode}
    \ifdim\m@mdownsf>\sidefootvsep
      \advance\m@mdownsf\sidefootvsep
      \advance\m@mdownsf 0.5\ht\strutbox
    \fi
    \vskip\m@mdownsf%     --- basically works
    \unvbox\sidefootins%
    \vss}%
  \hss}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@mopsidefoot}
% If there are any sidefeet then add them to the output.
%    \begin{macrocode}
\newcommand*{\m@mopsidefoot}{%
  \ifvoid\sidefootins\else
    \setbox\@outputbox \vbox{%
      \sidefootcontents
      \unvbox\@outputbox}
  \fi}  

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\mem@makecol}
% \begin{macro}{\mem@makecolbf}
% \begin{macro}{\@reinserts}
% \begin{macro}{\@mem@extranofeet}
% \begin{macro}{@mem@testifnofoot}
% Revise these to cater for the new sidefoot insert.\label{makecol}
% \changes{v3.7c}{2013/11/28}{Spurious space}
%    \begin{macrocode}
\gdef\mem@makecol{%
  \m@m@makecolintro
  \ifvoid\footins
    \setbox\@outputbox \box\@cclv
  \else
    \m@mopfootnote
  \fi
  \m@mdoextrafeet
  \m@m@makecolfloats
  \m@mopsidebar
  \m@mopsidefoot
  \m@m@makecoltext
  \global \maxdepth \@maxdepth}

%    \end{macrocode}
%
% If the \Lpack{footmisc} package is loaded all of our additions of
% extra footnotes, side footnotes, sidebar are lost. So we add them to
% their collection macro. This is especially important when
% \Lpack{footmisc} \emph{and} \Lpack{reledmac} are loaded with
% memoir. To play nice, we use the command hooks introduced in june 2021.
% \changes{v3.7q}{2022/02/17}{Added this fix for \Lpack{footmisc}}
% \changes{v3.8.4}{2025/09/24}{Removed format check as we use format of at least 2023/06/01}
%    \begin{macrocode}
 % adding to "hook" in footmisc
\AddToHook{cmd/@makecol@appendblocks/after}{\m@mdoextrafeet\m@mopsidefoot\m@mopsidebar}

%    \end{macrocode}
%
% \changes{v1.618033988b}{2010/02/17}{a bf was missing in \cs{m@mopfootnotebf}}
% \changes{v3.7c}{2013/11/28}{Spurious space}
%    \begin{macrocode}
\gdef\mem@makecolbf{%
  \m@m@makecolintro
  \setbox\@outputbox \box\@cclv
  \m@m@makecolfloats
  \ifvoid\footins
  \else
    \m@mopfootnotebf
  \fi
  \m@mdoextrafeet
  \m@mopsidebar
  \m@mopsidefoot
  \m@m@makecoltext
  \global \maxdepth \@maxdepth}

%    \end{macrocode}
% \changes{v3.6d}{2010/06/30}{There should not be an \cs{else} on the
% kludge line}
% \changes{v3.6f}{2010/08/22}{There should not be an \cs{else} on the
% kludge line, then remember to remove it}
%    \begin{macrocode}
\gdef\@reinserts{%
  \ifvoid\footins\else\insert\footins{\unvbox\footins}\fi
  \m@mdodoreinextrafeet
  \ifvbox\@kludgeins\insert\@kludgeins{\unvbox\@kludgeins}\fi
  \ifvoid\sideins\else\insert\sideins{\unvbox\sideins}\fi
  \ifvoid\sidefootins\else\insert\sidefootins{\unvbox\sidefootins}\fi}

%    \end{macrocode}
%
% The easy way of extending the \cs{clearpage} code is by:
% \begin{verbatim}
% \renewcommand*{\@mem@extranofeet}{%
%  \ifvoid\sidefootins\else\@mem@nofootfalse\fi}
% \end{verbatim}
% but as so many other changes have to be made it's probably better to
% leave that alone and change \cs{@mem@testifnofoot} directly.
%    \begin{macrocode}
\renewcommand*{\@mem@testifnofoot}{%
  \@mem@nofoottrue
  \ifvoid\footins\else\@mem@nofootfalse\fi
  \ifvoid\footinsv@r\else\@mem@nofootfalse\fi
  \ifvoid\sideins\else\@mem@nofootfalse\fi
  \ifvoid\sidefootins\else\@mem@nofootfalse\fi
  \@mem@extranofeet}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \subsubsection{The sidefootnote macros}
%
% The macros here are essentially a copy of the ones for \cs{footnote}.
% I have not done anything about sidefootnotes in minipages, as I can't
% imagine a use for them while simultaneously making the final appearance
% looking good.
%
% The usual counter.
%    \begin{macrocode}
\newcounter{sidefootnote}
  \renewcommand{\thesidefootnote}{\@arabic\c@sidefootnote}
\@addtoreset{sidefootnote}{chapter}

%    \end{macrocode}
%
% By using: \\
% \verb?\letcountercounter{sidefootnote}{footnote}? \\
% the same counter will be used for both footnotes and sidefootnotes.
% This can be reverted to separate counters by; \\
% \verb?\unletcounter{sidefootnote}?
%
% \begin{macro}{\sidefoottextfont}
% The font for the sidefootnotes.
% \changes{v1.61803398d}{2010/02/06}{\cs{sidefoottextfont} is already
% defined by the initial issuing of \cs{setsidefeet}}
%    \begin{macrocode}
%\newcommand*{\sidefoottextfont}{\normalfont\footnotesize}

%    \end{macrocode}
% \end{macro}
%
% The remainder of the code is a copied from that for \cs{footnote}
% but with the appropriate variables for \cs{sidefootnote}s
%
% \begin{macro}{\@sidempfn}
% \begin{macro}{\thesidempfn}
%    \begin{macrocode}
\newcommand*{\@sidempfn}{sidefootnote}
\newcommand*{\thesidempfn}{\thesidefootnote}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@makesidefnmark}
%    \begin{macrocode}
\newcommand*{\@makesidefnmark}{\hbox{\@textsuperscript{%
  \normalfont\@thesidefnmark}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@preamsidefntext}
%    \begin{macrocode}
\newcommand{\@preamsidefntext}{%
  \interlinepenalty\interfootnotelinepenalty
  \floatingpenalty \@MM
  \splittopskip=\footnotesep
  \splitmaxdepth=\dp\strutbox
  \@parboxrestore}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@sidefootnotetext}
% \changes{v1.61803398d}{2010/02/05}{changed \cs{sidefootfont} 
% to \cs{sidefoottextfont}}
% \changes{v3.6g}{2010/09/19}{made 'single spacing' configurable}
% \changes{v3.8}{2023/07/26}{added the missing \cs{@currentcounter}}
%    \begin{macrocode}
\newcommand{\@sidefootnotetext}[1]{\insert\sidefootins{%
  \hsize\sidefootwidth
  \@parboxrestore
    \def\baselinestretch{\m@m@footnote@spacing}%
  \sidefootform \normalsize\normalfont\sidefoottextfont
  \splittopskip=\ht\strutbox
  \splitmaxdepth=\dp\strutbox
  \allowbreak
  \prevdepth=\dp\strutbox
  \vskip-\parskip
  \def\@currentcounter{sidefootnote}%
  \protected@edef\@currentlabel{%
    \csname p@sidefootnote\endcsname\@thesidefnmark}%
\color@begingroup
\@makesidefntext{{\sidefoottextfont #1}}%
\color@endgroup
  \ifvmode\else
    \unskip\@finalstrut\strutbox
  \fi
  \par
  \ifdim\prevdepth>\dp\strutbox \prevdepth=\dp\strutbox\fi
  \ifdim\prevdepth>99\p@
    \nobreak
    \vskip-\prevdepth
    \allowbreak
    \vskip\dp\strutbox
  \fi
  \vskip\sidefootvsep}%
  \m@mmf@prepare}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@sidefootnotemark}
%    \begin{macrocode}
\newcommand*{\@sidefootnotemark}{%
  \leavevmode
  \ifhmode
    \edef\@x@sf{\the\spacefactor}%
    \m@mmf@check
    \nobreak
  \fi
  \@makesidefnmark
  \m@mmf@prepare
  \ifhmode\spacefactor\@x@sf\fi
  \relax}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sidefootnote}
%    \begin{macrocode}
\newcommand*{\sidefootnote}{\@ifnextchar[ 
  \@xsidefootnote{\stepcounter\@sidempfn
  \protected@xdef\@thesidefnmark{\thesidempfn}%
  \@sidefootnotemark\@sidefootnotetext}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@xsidefootnote}
%    \begin{macrocode}
\def\@xsidefootnote[#1]{%
  \begingroup
    \csname c@\@sidempfn\endcsname #1\relax
    \unrestored@protected@xdef\@thesidefnmark{\thesidempfn}%
  \endgroup
  \@sidefootnotemark\@sidefootnotetext}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sidefootnotemark}
%    \begin{macrocode}
\newcommand{\sidefootnotemark}{%
  \@ifnextchar[
    \@xsidefootnotemark
      {\stepcounter{sidefootnote}%
       \protected@xdef\@thesidefnmark{\thesidefootnote}%
       \@sidefootnotemark}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@xsidefootnotemark}
%    \begin{macrocode}
\def\@xsidefootnotemark[#1]{%
  \begingroup
    \c@sidefootnote #1\relax
    \unrestored@protected@xdef\@thesidefnmark{\thesidefootnote}%
  \endgroup
  \@sidefootnotemark}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sidefootnotetext}
%    \begin{macrocode}
\newcommand*{\sidefootnotetext}{%
  \@ifnextchar[
    \@xsidefootnotetext
      {\protected@xdef\@thesidefnmark{\thesidempfn}%
       \@sidefootnotetext}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@xsidefootnotetext}
%    \begin{macrocode}
\def\@xsidefootnotetext[#1]{%
  \begingroup
    \csname c@\@sidempfn\endcsname #1\relax
    \unrestored@protected@xdef\@thesidefnmark{\thesidempfn}%
  \endgroup
  \@sidefootnotetext}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sidefootmarkstyle}
% \begin{macro}{\sidefootscript}
% \begin{macro}{\makesidefootmarkhook}
% \begin{macro}{\sidefootfootmark}
%    \begin{macrocode}
\newcommand*{\sidefootmarkstyle}[1]{\def\sidefootscript##1{#1}}
\newcommand*{\makesidefootmarkhook}{}
\newcommand*{\sidefootfootmark}{%
  \ifdim\sidefootmarkwidth < \z@
    \llap{\hb@xt@ -\sidefootmarkwidth{%
          \hss\normalfont\sidefootscript{\@thesidefnmark}}%
         \hspace*{-\sidefootmarkwidth}}%
  \else
    \ifdim\sidefootmarkwidth = \z@
      {\normalfont\sidefootscript{\@thesidefnmark}}%
    \else
      \hb@xt@\sidefootmarkwidth{\hss\normalfont\sidefootscript{\@thesidefnmark}}%
    \fi
  \fi}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\makesidefootmark}
% \changes{v1.61803398d}{2010/02/04}{Made \cs{makesidefootmark} long
% as the similar \cs{footnote} command, otherwise one cannot make side
% footnotes containign several paragraphs}
%    \begin{macrocode}
\newcommand{\makesidefootmark}[1]{%
  \leavevmode
  \parindent \sidefootparindent\noindent
  \leftskip\sidefootmarksep\relax
  \advance\leftskip \sidefootmarkwidth \null\nobreak\hskip -\leftskip\relax
  \makesidefootmarkhook\relax
  \sidefootfootmark #1}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@makesidefntext}
%    \begin{macrocode}
\newcommand{\@makesidefntext}[1]{\makesidefootmark #1}

%    \end{macrocode}
% \end{macro}
%
% Final layout.
% \begin{macro}{\sidefootmarkwidth}
% \begin{macro}{\sidefootmarksep}
% \begin{macro}{\sidefootparindent}
% \changes{v1.61803398d}{2010/02/04}{changed the defaults for
% \cs{sidefootmarkwidth} and \cs{sidefootmarksep} to zero, from 1em
% and -1em, looks better with the narrow margins}
%    \begin{macrocode}
\newlength{\sidefootmarkwidth}
  \setlength{\sidefootmarkwidth}{0em}
\newlength{\sidefootmarksep}
  \setlength{\sidefootmarksep}{0em}
\newlength{\sidefootparindent}
  \setlength{\sidefootparindent}{1em}
\sidefootmarkstyle{\textsuperscript{#1}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \subsection{End notes}
%
% \changes{v3.6h}{2011/01/19+}{Reimplemented page notes}
% This used to be a copy of the \Lpack{pagenote} package, with minor
% amendments. But it turned out that the implementation used by
% \Lpack{pagenote} at that time, had a few serious flaws. In this
% implementation we will instead turn to the trick used by the
% \Lpack{endnotes} package to overcome the same problem.
% For the sake of history, let us summarise what the actual problem
% was. Basically the command \cs{pagenote}\marg{text} would write an
% entry to an external file in the following format
% \begin{verbatim}
% \noteentry{nom}{id}{text}{pagenum}
% \end{verbatim}
% and when typesetting the page notes, this file would be read into
% the document and \cs{noteentry} would typeset each page note. The
% main problem here is \verb|{text}| which is written verbatimly to
% the external file, but it is written on a single line!, thus an
% input like this
% \begin{verbatim}
% \pagenote{Test%
% test}
% \end{verbatim}
% would give us the entry
% \begin{verbatim}
% \noteentry{num}{id}{Test%test}{pagenum}
% \end{verbatim}
% oops! This is what we will solve using inspiration from
% \Lpack{endnotes}, kudos to  John Lavagnino.
%
%
% \begin{macro}{\ifm@mpnpageopt}
% \begin{macro}{\ifm@mpncontopt}
% We need two flags for the options.
% \cs{m@mpnpageoptfalse} means that page numbers are not available and
% \cs{m@mpncontopt} means that note numbers are reset at each \cs{chapter}.
%    \begin{macrocode}
\newif\ifm@mpnpageopt
  \m@mpnpageoptfalse
\newif\ifm@mpncontopt
  \m@mpncontoptfalse
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\c@pagenote}
% \begin{macro}{\thepagenote}
% We need a counter for the notes. This is the default definition.
%    \begin{macrocode}
\newcounter{pagenote}[chapter]
\renewcommand{\thepagenote}{\arabic{pagenote}}
\setcounter{pagenote}{0}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\notepageref}
% \begin{macro}{\continuousnotenums}
% \changes{v3.6h}{2011/01/19}{Removed references to pagenote package}
%   Let the user change the default options.  \cs{notepageref} makes
%   page numbers available in the typeset list of page note and
%   \cs{continuousnotenums} means that notes will be numbered
%   continuously throughout the document.
%    \begin{macrocode}
\newcommand*{\notepageref}{\m@mpnpageopttrue}
\@onlypreamble\notepageref
\newcommand*{\continuousnotenums}{%
  \counterwithout{pagenote}{chapter}
  \renewcommand{\thepagenote}{\arabic{pagenote}}}
\@onlypreamble\continuousnotenums

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\ifmempagenotes}
% Need to check if notes are required.
%    \begin{macrocode}
\newif\ifmempagenotes
  \mempagenotesfalse

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\makepagenote}
% This sets up the note file. At the end it emasculates itself so it can only
% be used once.
%    \begin{macrocode}
\newcommand*{\makepagenote}{%
  \newwrite\@notefile
  \immediate\openout\@notefile=\jobname.ent
  \mempagenotestrue
%    \end{macrocode}
% \begin{macro}{\pagenote}
% Make sure that this has a useful definition. 
% \changes{v3.6h}{2011/01/19}{Made \cs{pagenote} robust}
% \changes{v3.6j}{2011/03/01}{Removed \cs{@sanitize}}
% \changes{v3.6k}{2011/03/08}{Actually need \cs{@sanitize} for the
% optional argument. But we need to remove spaces from this}
%    \begin{macrocode}
  \DeclareRobustCommand\pagenote{\@bsphack\begingroup
    \rem@special{\ }% <--- added 
    \@sanitize
    \m@m@wrpnote}%
%    \end{macrocode}
% \end{macro}
% \changes{v3.6h}{2011/01/19}{Added the redefinition of \cs{mem@footto@pagenote}}
% \begin{macro}{\mem@footto@pagenote}
% The same as for \cs{pagenote} but here we use a special version of
% the writing macro that will ignore the optional argument. This will
% internally be used when the user ask for foot notes to be turned
% into page notes.
% \changes{v3.6j}{2011/03/01}{Removed \cs{@sanitize}}
% \changes{v3.6k}{2011/03/08}{Actually need \cs{@sanitize} for the
% optional argument. But we need to remove spaces from this}
%    \begin{macrocode}
  \DeclareRobustCommand\mem@footto@pagenote{\@bsphack\begingroup
    \rem@special{\ }% <--- added 
    \@sanitize
    \def\mem@pn@step{01}%
    \m@m@wrpnote}%
%    \end{macrocode}
% \end{macro}
% At the end we make sure \cs{makepagenote} can only do something once.
% \begin{macrocode}
  \typeout{Writing note file \jobname.ent}%
  \let\makepagenote\@empty}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\immediate@protected@write}
% We might have to do some immediate writes. This is an immediate
% version of the kernel \cs{protected@write}.
% \changes{v3.7i}{2019/11/15}{changed to \cs{providecommand} and
% removed the \cs{if@nobreak} line, also removed the edef part,
% suggested by Davis Carlisle}
%    \begin{macrocode}
\providecommand{\immediate@protected@write}[3]{%
  \begingroup
  #2%
  \let\protect\@unexpandable@protect
  %\edef\reserved@a{\immediate\write#1{#3}}%
  %\reserved@a
  \immediate\write#1{#3}%
  \endgroup
  %\if@nobreak\ifvmode\nobreak\fi\fi%
}

%    \end{macrocode}
%
% \end{macro}
% 
% \begin{macro}{\immediateaddtocontents}
%   This is a rather risky macro, that sometimes is needed in
%   documents with \cs{include} as things can get out of sequence. The
%   macro is \emph{not} documented in the manual, as it can be
%   dangerous. If a \cs{clearpage} is executed right after, then it
%   should be save to use. Instead of just copying code and edit, we
%   use a \cs{NewCommandCopy} and patch it. Note that we define
%   \cs{thepage} to do nothing here.
%    \begin{macrocode}
 % \long\def\immediateaddtocontents#1#2{%
 %  \immediate@protected@write\@auxout% 
 %  {\let\label\@gobble \let\index\@gobble \let\glossary\@gobble \let\thepage\relax}%
 %  {\string\@writefile{#1}{#2}}}
\NewCommandCopy\immediateaddtocontents\addtocontents
\patchcmd{\immediateaddtocontents}
  {\protected@write}%
  {\immediate@protected@write}%
  {}%
  {\typeout{patch 1 for \string\immediateaddtocontents\space failed}}
%    \end{macrocode}
%   In 2025 \cs{addtocontents} was changed a bit and is now using
%   alternative \cs{@gobble} macro. Since we still support older
%   installations we support both variants.
% \changes{v3.8.4}{2025/06/10}{Added support for \cs{@gobble@om}}
%    \begin{macrocode}
\@ifundefined{@gobble@om}{
  \patchcmd{\immediateaddtocontents}%
    {\let\glossary\@gobble}%
    {\let\glossary\@gobble\let\thepage\relax}%
    {}%
    {\typeout{patch 2 for \string\immediateaddtocontents\space failed}}
  }{
    \patchcmd{\immediateaddtocontents}%
      {\let\glossary\@gobble@om}%
      {\let\glossary\@gobble\let\thepage\relax}%
      {}%
      {\typeout{patch 2 for \string\immediateaddtocontents\space failed}}
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@m@pnwrite} 
% \begin{macro}{\m@m@pnwrited} 
% In the old implementation we used \cs{immediate@protected@write}
% unless the user asked for page numbers in the notes, the new
% implementation use the same writing method for all cases, for easy
% of notation we collect it in a macro. Seems UTF8 is an interesting
% beast, \cs{immediate@protected@write} can write it to disk, but
% \cs{m@m@pnwrite} cannot. To get past this we also include a version
% that has an embedded \cs{detokenize} (thanks to Heiko Oberdiek for
% that hint). We also add a \% at the end of the \cs{m@m@pnwrited}
% process (don't think \cs{m@m@pnwrite} needs it). This is handy in
% those cases where the user is using a design which rely on there not
% being any spaces after the note text.
% \changes{v3.6k}{2011/04/06}{Added the version with \cs{detokenize}}
%    \begin{macrocode}
% \changes{v3.7i}{2019/06/07}{Added \cs{@percentchar} to
% \cs{m@m@pnwrited}}
\newcommand{\m@m@pnwrite}[3]{\immediate\write#1{#3}}
\newcommand{\m@m@pnwrited}[3]{\immediate\write#1{\detokenize{#3}\@percentchar}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\pnchap}
% \begin{macro}{\pnschap}
% Redefine these for different subheadings in the notes list.
%    \begin{macrocode}
\newcommand*{\pnchap}{\f@rtoc}
\newcommand*{\pnschap}{\f@rbdy}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \begin{macro}{\c@pagenoteshadow}
% \begin{macro}{\mem@pn@step}
% \begin{macro}{\mem@pn@lastkern}
% Utilities, a counter to provide us with a unique name for each page
% note, a toggle macro and a length to hold a lastkern (because
% someone may hide it from us).
%    \begin{macrocode}
\newcounter{pagenoteshadow}
  \setcounter{pagenoteshadow}{0}
\newcommand\mem@pn@step{00} % i.e. true
\newlength\mem@pn@lastkern
%    \end{macrocode}
%  
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\m@m@wrpnote}
% This writes the note information to the note file. If the optional argument
% is empty it increments the
% note counter and calls \cs{notenumintext} to handle its appearance in 
% the body text. We write an entry of the following design
% \begin{verbatim}
% \startnoteentry{notenumber}{id}{auto label key}{hyperref}
% macro:->text
% \endnoteentry
% \end{verbatim}
% 
% \begin{macro}{\m@m@pnwrite@fourtharg}
% \begin{macro}{\m@m@pnwrite@fourtharg@hyperref}
% In order for us to add \Lpack{hyperref} support we will need to
% record the hyperref anchor label into the page note data. We do this
% though \verb|\m@m@pnwrite@fourtharg|, which by default just adds
% \verb|{}| to the page note data. \Lpack{memhfixc} makes it point
% toward \verb|\m@m@pnwrite@fourtharg@hyperref| instead. We make sure
% to pass it the optional argument from \verb?\pagenote?, if this is
% precent a hyper anchor is not passed on.
% \changes{v3.6k}{2013/05/17}{Macro needs to test an argument}
%    \begin{macrocode}
\newcommand\m@m@pnwrite@fourtharg[1]{\m@m@pnwrited\@notefile{}{{}}}
\newcommand\m@m@pnwrite@fourtharg@hyperref[1]{%
  \@ifmtarg{#1}{%
    \m@m@pnwrite\@notefile{}{{\Hy@pagenote@currentHref}}%
  }{%
    \m@m@pnwrited\@notefile{}{{}}%
  }}

%    \end{macrocode}
% \end{macro}
%   % \end{macro}
% 
% \changes{v1.61803}{2008/05/25}{Made \cs{m@m@wrpnote} match the effect 
%                    described in memman regarding the optional argument.}
% \changes{v3.6h}{2011/01/19}{Changed the internal implementation}
%    \begin{macrocode}
\newcommand{\m@m@wrpnote}[2][]{%
%    \end{macrocode}
% If \Lpack{hyperref} is loaded it issues a whatisit and thus
% hide/reset the last kern, which is needed for the algorithm used for
% the multiple notes in a row feature (adding commas). So we start by
% storing the last kern, and refstep a shadow counter such that we
% can generate more or less unique label keys.
%    \begin{macrocode}
  \mem@pn@lastkern=\lastkern% 
  \refstepcounter{pagenoteshadow}% 
%    \end{macrocode}
% If the user asks for it enable page back refs, we use labels and
% references for this (bonus: automatic support for hyperlinks if
% \Lpack{hyperref} is available).
% \changes{v3.8.4}{2025/09/16}{There is no need for a \cs{phantomsection} herem as there is a \cs{refstepcounter} just above}
%    \begin{macrocode}
  \ifm@mpnpageopt%
    %\phantomsection%
    \label{pagenote\thepagenoteshadow-\thesheetsequence}%
  \fi%
%    \end{macrocode}
% Next we want to be able to reuse this macro just for writing the
% entry to disk, no writing a marker in the text (think replacement
% for \cs{footnotetext}), we use the toggle for this and also remember
% to re-insert the code needed for comma separated multiple markers
%    \begin{macrocode}
  \if\mem@pn@step%
    \@ifmtarg{#1}{%
      \refstepcounter{pagenote}%
      % this enables the ^{1,2} feature
      \ifdim\mem@pn@lastkern=\multiplefootnotemarker%
        \m@mmf@prepare% rerun
      \fi%
      \mem@pn@multiple@marker{\notenumintext{\thepagenote}}% 
%    \end{macrocode}
% \changes{3.7i}{2019/05/28}{Added the special kern also if the
% optional arg is empty. Otherwise the multiple marker might not work
% under hyperref. Reported in private email}
%    \begin{macrocode}
    }{\m@mmf@prepare}%
  \fi%
%    \end{macrocode}
% Check if this is the first note in a division, and if so indicate this 
% in the file.
% \changes{v3.6h}{2011/01/25}{Added \cs{pagenotesubheadstarred}}
%    \begin{macrocode}
  \ifm@mpn@new@chap%
    \global\m@mpn@new@chapfalse%
    \addtonotes{\string\pagenotesubhead{\@chapapp}{\thechapter}{\pnchap}}%
  \fi%
  \ifm@mpn@new@schap%
    \global\m@mpn@new@schapfalse%
    \addtonotes{\string\pagenotesubheadstarred{\@chapapp}{}{\pnschap}}%
  \fi%
%    \end{macrocode}
% Next we write to the notes file. Instead of writing everything as a
% macro with arguments, we will use three writes. One to start a new
% entry with a few (non-text) arguments, then the text itself, and
% finally an end of entry marker macro. There is a slight complication
% here. The \verb|#1| may be UTF8 so it has to be written unexpanded
% to disk, but macros like \verb|\thepagenote| need to be
% expanded. Luckily \TeX\ eats up spaces when reading arguments, so we
% simply writte several lines using two different writing methods.
% \changes{v3.6k}{2011/04/06}{Rewritten to use a different writing method}
%    \begin{macrocode}
  \m@m@pnwrite\@notefile{}%
    {\string\startnoteentry{\thepagenote}}%
  \m@m@pnwrited\@notefile{}{{#1}}%
  \m@m@pnwrite\@notefile{}%
    {{pagenote\thepagenoteshadow-\thesheetsequence}}%
%    \end{macrocode}
% Add the fourth argument.
% \changes{v3.6k}{2013/05/16}{Added fourth argument for the note data}
% \changes{v3.6k}{2013/05/17}{Fourth arg, should depend on \#1}
%    \begin{macrocode}
  \m@m@pnwrite@fourtharg{#1}%
%    \end{macrocode}
% Getting the newline stuff to work require
% \verb|\immediate\write| which we defined earlier. We then write the
% text `verbatimly' using the detokenized macro.
% \changes{v3.6k}{2011/04/06}{No longer any need for the \cs{meaning} construction.}
%    \begin{macrocode}
  \begingroup%
    \newlinechar='40%
    \m@m@pnwrited\@notefile{}{#2}%
  \endgroup%
%    \end{macrocode}
% Remember to also write a marker that ends the entry.
%    \begin{macrocode}
  \m@m@pnwrite\@notefile{}%
  {\string\endnoteentry}%
  \endgroup%
  \@esphack}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\pagenote}
% \begin{macro}{\mem@footto@pagenote}
% The user command to generate a note. It is given substance 
% by \cs{makepagenote}. Supplied with a special version used if the
% user asks for all footnotes to be turned into page notes.
% \changes{v3.6h}{2011/01/19}{Added \cs{mem@footto@pagenote}}
%    \begin{macrocode}
\def\pagenote{\@bsphack\begingroup \@sanitize\m@m@pagenote}
\let\mem@footto@pagenote\pagenote
%    \end{macrocode}
% \end{macro}
% \end{macro}
% 
% \begin{macro}{\m@m@pagenote}
%    \begin{macrocode}
\newcommand{\m@m@pagenote}[2][]{\endgroup\@esphack}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\pagetofootnote}
% \begin{macro}{\foottopagenote}
% \begin{macro}{\memsavefootnote}
% \begin{macro}{\memsavepagenote}
%  Let the user change pagenotes to footnotes, or vice-versa. In either
% case the optional argument is ignored.
% \changes{v3.6h}{2010/12/07}{\cs{footnote} should be long}
% \changes{v3.6h}{2010/12/09}{because of the way
% \cs{pagenote} is defined, we cannot redefine \cs{footnote} to have
% any arguments, we need to go another route}
% \changes{v3.6h}{2010/12/09}{Added a check for the race condition}
% We have a race condition, if both \cs{pagetofootnote} and
% \cs{makepagenote} is issued in the same  document,
% \cs{pagetofootnote} need to come last. 
%    \begin{macrocode}
\newcommand*{\pagetofootnote}{%
  \let\memsavepagenote\pagenote
  \renewcommand{\pagenote}[2][]{\footnote{##2}}
%    \end{macrocode}
% Basic idea is, if pagenotes mode is on when \cs{pagetofootnote} is
% issued, everything is fine. Else we test at end document (because
% \cs{makepagenote} can go anywhere).
%    \begin{macrocode}
  \ifmempagenotes\else% 
    \AtEndDocument{%
      \ifmempagenotes% 
      \@memerror{The use of \string\pagetofootnote\space before
        \string\makepagenote\space^^Jdoes not make
        sense. \string\makepagenote\space make some redefinitions that
        are not picked up if \string\pagetofootnote\space is issued
        before \string\makepagenote
      }{}
    \fi
   }
   \fi
}
%    \end{macrocode}
% Next the more challenging one. We make the footnote counter act as
% the page note counter, this ensure that \cs{footnotemark} still work
% when the user ask to have footnotes converted into page
% notes. \cs{footnotetext} is the same as the page note writer macro,
% but without writing the marker, here we use the special page note macro.
%    \begin{macrocode}
\newcommand*{\foottopagenote}{%
  \let\memsavefootnote\footnote
%    \end{macrocode}
% \changes{v3.6k}{2013/05/02}{Remember to remove footnote counter from
% chapter reset}
% Since we alias the footnote counter to the pagenote counter, we need
% to rewmove the footnote counter from the chapter reset, otherwise
% \cs{continuousnotenums} will be wrong.
%    \begin{macrocode}
  \counterwithout{footnote}{chapter}
  \letcountercounter{footnote}{pagenote}
  \renewcommand\footnotetext[2][]{\mem@footto@pagenote{##2}}
  \renewcommand{\footnote}[2][]{\pagenote{##2}}
}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\addtonotes}
% \cs{addtonotes}\marg{text} puts \meta{text} into the notes file.
% \changes{v3.6i}{2011/02/18}{\cs{addtonotes} need \cs{immediate@protected@write}}
%    \begin{macrocode}
\newcommand{\addtonotes}[1]{\ifmempagenotes
 \IfFileExists{\jobname.ent}{\immediate@protected@write\@notefile{}{#1}}{\mempnofilewarn}%
\fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\notenumintext}
% \begin{macro}{\notenuminnotes}
% \cs{notenumintext}\marg{notenum} typesets \meta{notenum} (in the
% body text). 
%    \begin{macrocode}
\newcommand{\notenumintext}[1]{%
  \textsuperscript{#1}}
%    \end{macrocode}
% \cs{notenuminnotes}\marg{notenum} typesets \meta{notenum} (i.e. the
% very first item when typesetting a note). 
%    \begin{macrocode}
\newcommand{\notenuminnotes}[1]{%
  {\normalfont #1.}\space}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\noteentry}
% \changes{v3.6}{2010/12/14}{explanation was wrong}
% \changes{v3.6h}{2011/01/19}{removed}
% \cs{noteentry}\marg{notenum}\marg{id}\marg{text}\marg{pagenum}
% typesets a note. This macro is not used anymore.
%    \begin{macrocode}
 %\newcommand{\noteentry}[4]{} % not used any more!

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\idtextinnotes}
% \cs{idtextinnotes}\marg{id text} typesets the note's \meta{id text}.
%    \begin{macrocode}
\newcommand{\idtextinnotes}[1]{%
  [#1]\space}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\noteidinnotes}
% \cs{noteidinnotes}\marg{notenum}\marg{id} is used to typeset the note 
% identification (in the note listing). It is set so that it typesets the 
% \meta{id} if it is not empty, otherwise it sets the \meta{notenum}.
%    \begin{macrocode}
\newcommand{\noteidinnotes}[2]{%
  \@ifmtarg{#2}{%
    \notenuminnotes{#1}}{\idtextinnotes{#2}}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\pageinnotes}
% \begin{macro}{\printpageinnotes}
% \begin{macro}{\printpageinnoteshyperref}
% \changes{v3.6h}{2011/01/19}{Changed to match new implementation}
% \cs{pageinnotes}\marg{key} calls 
% \cs{printpageinnotes}\marg{key} to typeset the originating 
% page number (in the note), but only if the \cs{notepageref} declaration
% has been used. Remember we provide an automatically generated label
% key, thus we use \cs{pageref} to get the page number. We provide a
% \Lpack{hyperref} version which is automatically used whenever
% \Lpack{hyperref} is loaded.
%    \begin{macrocode}
\newcommand{\pageinnotes}[1]{%
  \ifm@mpnpageopt \printpageinnotes{#1}\fi}
\newcommand*{\printpageinnotes}[1]{%
  (\pagerefname\ \pageref{#1})\space}
\newcommand\printpageinnoteshyperref[1]{%
(\hyperref[#1]{\pagerefname\ \pageref*{#1}})\space}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\noteinnotes}
% \cs{noteinnotes}\marg{text} is used to typeset the note's text 
% (in the note list). This macro is not used any more, but doesn't do
% any harm to leave it here.
%    \begin{macrocode}
\newcommand{\noteinnotes}[1]{#1} % not used anymore!

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\prenoteinnotes}
% \begin{macro}{\postnoteinnotes}
% These are called immediately before and after the note information is 
% typeset.
%    \begin{macrocode}
\newcommand{\prenoteinnotes}{\par\noindent}
\newcommand{\postnoteinnotes}{\par}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\prenotetext}
% \begin{macro}{\postnotetext}
% Thise two macros are executed just before and just after the note
% text. Does nothing by default.
%    \begin{macrocode}
\newcommand\prenotetext{}
\newcommand\postnotetext{}

%    \end{macrocode}
% 
% \end{macro}
% \end{macro}
%
% \begin{macro}{\notesname}
% \begin{macro}{\notedivision}
% Heading for note list.
%    \begin{macrocode}
\providecommand*{\notesname}{Notes}
\newcommand*{\notedivision}{\chapter{\notesname}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \changes{v3.6h}{2010/12/14}{typo}
% \changes{v3.6h}{2011/01/19}{There is no reason to use two macros to
% implement a starred and non starred version in this case.}
% \begin{macro}{\printpagenotes}
% \begin{macro}{\printpagenotes*}
% User commands to print the note file.
%    \begin{macrocode}
\newcommand*{\printpagenotes}{\@ifstar{\mem@printpagenotes{00}}{\mem@printpagenotes{01}}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\mempnofilewarn}
% Warning when the notes file does not exist.
%    \begin{macrocode}
\newcommand*{\mempnofilewarn}{%
  \ClassWarning{memoir}{There is no .ent file}}

%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\startnoteentrystart}
% \begin{macro}{\endnoteentryend}
% \begin{macro}{\pagenoteanchor}
% \begin{macro}{\pagenotebyanchor}
%   Utility macros to handle page note formating and hyperlinks.
%   \changes{v3.6k}{2013/05/16}{altered to use four arguments instead of three}
%   \changes{v3.6k}{2013/05/16}{Added page note anchor}
%   \changes{v3.6k}{2013/05/17}{Forgot about labels in the note text.}
%   \changes{v3.7g}{2018/01/03}{Added \cs{phantomsection}, otherwise
%   \cs{label} does not work correctly. Reported in \texttt{https://tex.stackexchange.com/q/408448/3929}}
%  \changes{v3.8}{2023/07/26}{added \cs{@currentcounter} and
%  defined that \cs{@currentlabel} points to}
% \changes{v3.8.4}{2025/09/16}{Replaced \cs{phantomsection} with \cs{MakeLinkTarget}}
%    \begin{macrocode}
\newcommand\startnoteentrystart[4]{% number; manual id; auto label; href anchor
  \prenoteinnotes%
  \noteidinnotes{#1}{#2}%
  % \phantomsection%
  \MakeLinkTarget[pagenote]{}%
  \@ifmtarg{#2}{\def\@currentlabel{#1}}{\def\@currentlabel{#2}}%
  \def\@currentcounter{pagenote}%
  \pagenoteanchor{#4}%
  \pageinnotes{#3}%
  \prenotetext%
}
\def\endnoteentryend{\postnotetext\postnoteinnotes}
\let\pagenoteanchor\@gobble
%    \end{macrocode}
% The page note hyper anchor should of course only be added when there
% is an anchor.
% \changes{v3.6k}{2013/05/17}{Forgot to test the argument}
%    \begin{macrocode}
\newcommand\pagenotehyperanchor[1]{%
  \expandafter\@ifmtarg\expandafter{#1}{}{%
    \Hy@raisedlink{\hyper@@anchor{#1}{\relax}}}}%

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\mem@printpagenotes}
% \begin{macro}{\startnoteentry}
% \begin{macro}{\ednoteentry}
%   The internal macro for printing the list of page notes. The two
%   macros \cs{startnoteentry} and \cs{endnoteentry} are also defined here.
% \changes{v3.6k}{2011/03/09}{Start and end entry better be long}
% \changes{v3.6k}{2011/04/06}{We no longer use \cs{meaning} when
% writing the data to disk, so no need to remove \texttt{>} any
% more. Also removed the safe GT stuff}
%    \begin{macrocode}
% \changes{v3.6k}{2013/05/16}{\cs{startnoteentry} should expect four args}
\newcommand\mem@printpagenotes[1]{%
  \ifmempagenotes
    \notedivision
    \IfFileExists{\jobname.ent}{%
      \begingroup
      \long\def\startnoteentry####1####2####3####4{%
        \begingroup
        \startnoteentrystart{####1}{####2}{####3}{####4}%
      }
      \long\def\endnoteentry{\endnoteentryend\endgroup}
      \immediate\closeout\@notefile
      \input{\jobname.ent}%
      \if#1\immediate\openout\@notefile=\jobname.ent\fi%
      \endgroup
    }{%
      \mempnofilewarn
    }%
  \fi%
}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@sprintpagenotes}
% Macro implementing \cs{printpagenotes*}. Removed
% \changes{v3.6h}{2011/01/20}{Removed}
%    \begin{macrocode}
 % \newcommand*{\@sprintpagenotes}{%
 %   \ifmempagenotes
 %   \notedivision
 % \IfFileExists{\jobname.ent}{%
 %   \immediate\closeout\@notefile
 %   \input{\jobname.ent}%
 %   \immediate\openout\@notefile=\jobname.ent%
 %   }{%
 %   \mempnofilewarn
 % }%
 % \fi}
  
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@printpagenotes}
% Macro implementing \cs{printpagenotes}. Removed
% \changes{v3.6h}{2011/01/20}{Removed}
%    \begin{macrocode}
 % \newcommand*{\@printpagenotes}{%
 %   \ifmempagenotes
 %     \notedivision
 %     \IfFileExists{\jobname.ent}{%
 %       \immediate\closeout\@notefile
 %       \input{\jobname.ent}%
 %      }{%
 %        \mempnofilewarn
 %      }
 %   \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\pagenotesubhead}
% \begin{macro}{\pagenotesubheadstarred}
% \changes{v3.6h}{2011/01/25}{Added \cs{pagenotesubheadstarred}}
% The section heading before each set of notes. \\
% \cs{pagenotesubhead}\marg{chaptername}\marg{number}\marg{title}
% The \cs{pagenotesubheadstarred} macro is used for unnumbered
% devisions. By default it is the same as \cs{pagenotesubhead}, but
% the user can change this. For example it may look odd with an title
% like this: >>Chapter Title<< when there is no number.
%    \begin{macrocode}
\newcommand*{\pagenotesubhead}[3]{%
  \section*{#1 #2 #3}}
\newcommand\pagenotesubheadstarred{\pagenotesubhead}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \section{Change marks} \label{sec:vct}
%
%    When preparing a manuscript it normally goes through
%    several iterations. The commands provided may be used to identify
%    changes made to a document during its life cycle.
%
% The code for this part of the class is based on the version
% controls in the \Lpack{iso} class~\cite{ISOCLASS}.
%
% \subsection{Print control}
%
%    Members of the development group often need to see the changes
%    between document versions, while the general public does not.
% \begin{macro}{\ifchangemarks}
%    This controls the appearence of the version controls defined
%    below.
%    \begin{macrocode}
\newif\ifchangemarks\changemarksfalse
%    \end{macrocode}
%   The marks only work properly when the \Lopt{draft} option
%   is in effect. Also, the command \cs{changemarkstrue} must be
%   put in the document preamble.
% \end{macro}
%
% \begin{macro}{\changemarks}
% \begin{macro}{\nochangemarks}
% More user friendly version of \cs{changemarks(true/false)}.
% \changes{v1.61803}{2008/01/30}{Added \cs{changemarks} and \cs{nochangemarks}}
%    \begin{macrocode}
\newcommand*{\changemarks}{\changemarkstrue}
\newcommand*{\nochangemarks}{\changemarksfalse}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\v@rid}
%    This acts as an alias for \cs{marginpar} when both \cs{ifchangemarks} is
%    true and the \Lopt{draft} option is in effect, otherwise it throws
%    away its two arguments.
% \changes{v1.2}{2002/07/27}{Added \cs{@bsphack} and \cs{@esphack} to \cs{v@rid}}
%    \begin{macrocode}
\newcommand{\v@rid}[2]{%
  \@bsphack
  \ifchangemarks
     \ifdraftdoc
       \marginpar[#1]{#2}%
  \fi\fi
  \@esphack}

%    \end{macrocode}
% \end{macro}
%
% \subsection{Change marking}
%
%    The following commands flag changes in the typeset document. Each of
%    the commands takes one parameter which is intended to be a 
%    `change number' or comment for tracking purposes. A symbol and
% the \meta{change-id} is put into the margin near where the command 
% is given. The marking commands should be attached to some word or 
% punctuation mark in the text otherwise extraneous spaces may creep
% into the final document.
% \changes{v1.2}{2002/07/27}{Added \cs{@bsphack} and \cs{@esphack} to changemarks}
% \begin{macro}{\added}
%    \cs{added}\marg{change-id}
%    Flags, with the symbol $\oplus$, that something has been added 
% to the manuscript.
%    \begin{macrocode}
\newcommand{\added}[1]{%
  \@bsphack
  \ifchangemarks
    \v@rid{\small$\oplus$ #1}{\small$\oplus$ #1}%
  \fi
  \@esphack}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\deleted}
%    \cs{deleted}\marg{change-id}
%    Flags, with the symbol $\neq$, that something has been deleted 
% from the manuscript.
%    \begin{macrocode}
\newcommand{\deleted}[1]{%
  \@bsphack
  \ifchangemarks
    \v@rid{\small$\neq$ #1}{\small$\neq$ #1}%
  \fi
  \@esphack}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\changed}
%    \cs{changed}\marg{change-id}
%    Flags, with the symbol $\Leftrightarrow$,  that something
% has been changed in the text.
%    \begin{macrocode}
\newcommand{\changed}[1]{%
  \@bsphack
  \ifchangemarks
    \v@rid{\small$\Leftrightarrow$ #1}{\small$\Leftrightarrow$ #1}%
  \fi
  \@esphack}

%    \end{macrocode}
% \end{macro}
%
% \section{Trimming marks}
%
% The \Lopt{showtrims} options prints trimming marks at the corners
% of the logical page. The code for this comes from ideas gleaned
% from Martin Schr\"{o}der's \Lpack{everyshi} package~\cite{EVERYSHI}
% and Melchior Franz's \Lpack{crop} package~\cite{CROP}. 
% The implementation and any errors are mine.
%
%    The implementation up to October 2002 was limited to putting a cross
% at the page corners. The manual directed users to the \Lpack{crop}
% packge if they wanted anything more. In October 2002 the implementation
% was substantially extended. The background to this is below.
%
%    Before the release of version 1.7 of \Lpack{crop} in May 2002 its
% author asked me to make some changes to \Lpack{memoir} that would be
% helpful to him, and I did so. Later he told me that the changes were
% unnecessary and I reverted to the original \Lpack{memoir} code.
%
% On 2002/10/06 Peter Heslin started a thread on \url{comp.text.tex}
% titled `Incompatibility of memoir.cls and crop.sty' in which he said
% that \Lpack{memoir} and \Lpack{crop} did not seem to work
% together. The following are some snippets from that thread,
% identified by the various proponents.
% \begin{description}
% \item[crop] Ah, yes. It cannot work with all those \cs{settrims} etc.
%             crop.sty does only respect \verb?\stock{width,height}?,
%             but none of the other memoir specific trim marks stuff \ldots
%
% \item[crop] \ldots I'm not a memoir expert. crop.sty respects all the
%  usual LaTeX paper dimensions and simply puts the marks around the
% page. It works with all standard classes and the KOMA classes. memoir
% seems to do things completely differently \ldots
%
%    Sorry, but I'm afraid I have to pass the problem to the memoir
% author. \ldots
%
% \item[memoir] I will try and take a look at the problem but I'm
%  not a crop expert --- I've never used it. However it seems odd to
% me that crop doesn't work with memoir. Memoir provides a different
% interface for specifying the page layout but then translates everything
% to the standard length variables. \ldots
%
% \item[crop] You've just taken code from it \verb?...:->?
%
%    crop doesn't have its own idea at all. It just uses that of DEK
% and LaTeX, which says, that the reference point of the output box
% in the output routine is assumed 1 inch to the left [later corrected 
% to right] and 1 inch down
% from the upper left (virtual) paper corner.
%
% \item[crop] With other words: crop changes \cs{hoffset} and \cs{voffset},
% in order to center the logical (virtual) page on the physical sheet
% of paper, in the middle of the crop marks. The length macros 
% \cs{evensidemargin} and \cs{oddsidemargin} are unchanged and refer still 
% to the logical page (modulo 1 inch).
%
%    The memoir class, in contrast (mis)uses the LaTeX margins
% \cs{even(odd)sidemargin} for that purpose.
%
%    Thus, the meaning of \cs{even(odd)sidemargin} is different
% in both packages.
% \end{description}
%
%     Given all the above I concluded that \Lpack{crop} would remain
% as it was, and that in order to satisfy Peter Heslin I would have
% to extend the trimming marks. The following was originally limited to 
% extensions
% asked for by Peter Heslin.
%
% \begin{macro}{\showtrimsoff}
% \begin{macro}{\showtrimson}
% Switch trimming marksoff and on. Requested by James Hunt on CTT
% \textit{Are crop marks needed on every page?}, February 2006.
% \changes{v1.61803}{2008/01/30}{Added \cs{showtrimsoff} and \cs{showtrimson} 
%                (mempatch v4.5)}
%    \begin{macrocode}
\newcommand*{\showtrimsoff}{\showtrimsfalse}
\newcommand*{\showtrimson}{\showtrimstrue}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% 
% \begin{macro}{\trimmark}
%   This is a cross in a zero sized picture for marking the corner of
%   a logical page. Up to version 1.0 the macro used \cs{setlength}
%   for adjusting the \cs{unitlength} but Henrik Holm (Message to
%   \ctt{} on 2002/01/04) discovered that if the \Lpack{calc} package
%   is used then LaTeX complains about a missing number.
% \changes{v1.0a}{2002/01/04}{Removed \cs{setlength} from \cs{trimmark}. Stops
%                 problem with the calc package.}
%    \begin{macrocode}
\newcommand*{\trimmark}{%
  \begin{picture}(0,0)
    \unitlength 1cm
    \thinlines
    \put(-2,0){\line(1,0){4}}
    \put(0,-2){\line(0,1){4}}
  \end{picture}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\Ltrimpictl}
% \begin{macro}{\Ltrimpictr}
% \begin{macro}{\Ltrimpicbl}
% \begin{macro}{\Ltrimpicbr}
%  `L' shaped trim marks for four corners.
% \changes{v1.3}{2002/10/10}{Added \cs{Ltrimpictl}, \cs{Ltrimpictr}, \cs{Ltrimpicbl}
%                            and \cs{Ltrimpicbr}}
%    \begin{macrocode}
\newcommand*{\Ltrimpictl}{%
  \begin{picture}(0,0)
    \unitlength 1mm
    \thinlines
    \put(-2,0){\line(-1,0){18}}
    \put(0,2){\line(0,1){18}}
  \end{picture}}
\newcommand*{\Ltrimpictr}{%
  \begin{picture}(0,0)
    \unitlength 1mm
    \thinlines
    \put(2,0){\line(1,0){18}}
    \put(0,2){\line(0,1){18}}
  \end{picture}}
\newcommand*{\Ltrimpicbl}{%
  \begin{picture}(0,0)
    \unitlength 1mm
    \thinlines
    \put(-2,0){\line(-1,0){18}}
    \put(0,-2){\line(0,-1){18}}
  \end{picture}}
\newcommand*{\Ltrimpicbr}{%
  \begin{picture}(0,0)
    \unitlength 1mm
    \thinlines
    \put(2,0){\line(1,0){18}}
    \put(0,-2){\line(0,-1){18}}
  \end{picture}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\Ftrimpicbl}
%    Frame the page.
% \changes{v1.3}{2002/10/10}{Added \cs{Ftrimpictl}}
%    \begin{macrocode}
\newcommand*{\Ftrimpicbl}{%
  \begin{picture}(0,0)
    \unitlength 1pt
    \thinlines
    \put(0,0){\framebox(\strip@pt\paperwidth,\strip@pt\paperheight){}}
  \end{picture}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\tmarktl}
% \begin{macro}{\tmarktr}
% \begin{macro}{\tmarkbl}
% \begin{macro}{\tmarkbr}
% The trimming marks used for corner display.
% \changes{v1.3}{2002/10/10}{Added \cs{tmarktl}, \cs{tmarktr}, \cs{tmarkbl}
%                            and \cs{tmarkbr}}
%    \begin{macrocode}
\newcommand*{\tmarktl}{\trimmark} 
\newcommand*{\tmarktr}{\trimmark} 
\newcommand*{\tmarkbl}{\trimmark} 
\newcommand*{\tmarkbr}{\trimmark} 

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\tmarktm}
% \begin{macro}{\tmarkml}
% \begin{macro}{\tmarkmr}
% \begin{macro}{\tmarkbm}
% The trimming marks used for mid-side display.
% \changes{v1.3}{2002/10/10}{Added \cs{tmarktm}, \cs{tmarkml}, \cs{tmarkmr}
%                            and \cs{tmarkbm}}
% \changes{v1.6180339c}{2009/11/13}{Fill in these four macros. Easier
% for users to define them to do nothing, than coming up with the code}
%    \begin{macrocode}
\newcommand*{\tmarktm}{%
  \begin{picture}(0,0)%
    \unitlength 1mm
    \thinlines
    \put(0,2){\line(0,1){10}}
  \end{picture}}
\newcommand*{\tmarkml}{%
  \begin{picture}(0,0)%
    \unitlength 1mm
    \thinlines
    \put(-2,0){\line(-1,0){10}}
  \end{picture}}
\newcommand*{\tmarkmr}{%
  \begin{picture}(0,0)%
    \unitlength 1mm
    \thinlines
    \put(2,0){\line(1,0){10}}
  \end{picture}}
\newcommand*{\tmarkbm}{%
  \begin{picture}(0,0)%
    \unitlength 1mm
    \thinlines
    \put(0,-12){\line(0,1){10}}
  \end{picture}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\trimXmarks}
% \begin{macro}{\trimLmarks}
% \begin{macro}{\trimFrame}
% \begin{macro}{\trimNone}
% These are declarations for the different kinds of trimming marks.
% \changes{v1.3}{2002/10/10}{Added \cs{trimXmarks}, \cs{trimLmarks}, 
%                            \cs{trimFrame} and \cs{trimNone}} 
%    \begin{macrocode}
\newcommand*{\trimXmarks}{%
  \let\tmarktl\trimmark
  \let\tmarktr\trimmark
  \let\tmarkbl\trimmark
  \let\tmarkbr\trimmark}
\newcommand*{\trimLmarks}{%
  \let\tmarktl\Ltrimpictl
  \let\tmarktr\Ltrimpictr
  \let\tmarkbl\Ltrimpicbl
  \let\tmarkbr\Ltrimpicbr}
\newcommand*{\trimFrame}{%
  \let\tmarktl\null
  \let\tmarktr\null
  \let\tmarkbl\Ftrimpicbl
  \let\tmarkbr\null}
\newcommand*{\trimNone}{%
  \let\tmarktl\relax
  \let\tmarktr\relax
  \let\tmarkbl\relax
  \let\tmarkbr\relax
  \let\tmarktm\relax
  \let\tmarkml\relax
  \let\tmarkmr\relax
  \let\tmarkbm\relax}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\trimmarks}
% \begin{macro}{\trimmarkscolor}
%    This positions four marks (\cs{trimmark}) at the corners of a
% logical page. It is basically a \cs{vbox} with zero height and width.
%
% Bastiaan Niels Veelo reported (2003/07/11) odd things (e.g., some
% macros ignored) when changing trim marks. Turns out to be related
% to the use of \cs{protect}. The macro \cs{trimmarkscolor} can be
% used to change the color of the trimmarks. Despite its name, it is
% not a color but just an empty macro.
% \changes{v1.1}{2002/03/10}{Changed \cs{trimmarks} to work properly with the oneside option}
% \changes{v1.3}{2002/10/10}{Changed \cs{trimmarks} to use \cs{tmarktl}, etc.,
%                            instead of four \cs{trimmark}s}
% \changes{v1.4}{2003/11/22}{Fiddled \cs{protect} in \cs{trimmaks}
%                            (from patch v1.7)}              
% \changes{v3.6h}{2010/12/05}{Added \cs{trimmarkscolor}}
% \changes{v3.7m}{2020/08/05}{From the 2020/10/01 format, we don't
% need the \cs{vskip}\texttt{-1in} and \cs{hskip}\texttt{-1in} as the
% trimmarks are added in a different manner}
%    \begin{macrocode}
\newcommand*\trimmarkscolor{}
%    \end{macrocode}
% \changes{v3.7m}{2020/08/05}{Factored out two skips}
% Factoring out two skips to make it easy to remove them in the
% 2020/10/01 onwards.
%    \begin{macrocode}
\newcommand\mem@trimmarks@initial@vskip{\vskip-1in}
\newcommand\mem@trimmarks@initial@hskip{\hskip-1in}
\newcommand*{\trimmarks}{%   
  \vbox to \z@{%
    \mem@trimmarks@initial@vskip%
    \vskip\trimtop % top of logical page
    \hb@xt@\z@{%
      \mem@trimmarks@initial@hskip%
      \ifodd\c@page 
        \hskip\stockwidth
        \hskip-\trimedge
        \hskip-\paperwidth
      \else 
        \if@twoside
          \hskip\trimedge  % left of logical page
        \else
          \hskip\stockwidth
          \hskip-\trimedge
          \hskip-\paperwidth
        \fi
      \fi
      \vbox to \paperheight{%
        \let\protect\relax        % <- v1.4 addition
        \hb@xt@\paperwidth{\trimmarkscolor\tmarktl\hfil\tmarktm\hfil\tmarktr}%
        \vfil
        \hb@xt@\paperwidth{\trimmarkscolor\tmarkml\hfil\tmarkmr}%
        \vfil
        \hb@xt@\paperwidth{\trimmarkscolor\tmarkbl\hfil\tmarkbm\hfil\tmarkbr}}%
      \hss}%
    \vss}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \subsection{Quark marks}
%
% William Adams (2006/08/28) supplied the following code to use trim marks 
% along the style of Quark Xpress. 
%
% \begin{macro}{\registrationColour}
% \begin{macro}{\quarkmarks}
% Trim marks on the style of Quark Express.
% \changes{v1.61803}{2008/01/30}{Added \cs{quarkmarks} (mempatch v4.6)}
% \changes{v3.6h}{2010/12/05}{Added \cs{normalfont} such that font
% changes going over a page break does not effect the quarks
% text. Reported by Rasmus Villemoes.}
% \changes{v3.6j}{2011/02/28}{Typo hsip -> hskip, reported by Alex Ball}
%    \begin{macrocode}
\newcommand*{\registrationColour}[1]{#1}
\newcommand*{\quarkmarks}{%
\renewcommand*{\tmarktl}{\registrationColour{%
  \begin{picture}(0,0)
    \setlength{\unitlength}{1bp}\thicklines
    \put(-36,0){\line(1,0){24}}
    \put(0,12){\line(0,1){24}}
    \put(3,27){\normalfont\ttfamily\fontsize{8bp}{10bp}\selectfont\jobname\ \
      \today\ \ \printtime\ \ Page \thepage}
  \end{picture}}}
\renewcommand*{\tmarktm}{\registrationColour{%
  \begin{picture}(0,0)
    \setlength{\unitlength}{1bp}\thicklines
    \put(-24,24){\line(1,0){48}}
    \put(0,12){\line(0,1){24}}
    \put(0,24){\oval(12,12)}
  \end{picture}}}
\renewcommand*{\tmarktr}{\registrationColour{%
  \begin{picture}(0,0)
    \setlength{\unitlength}{1bp}\thicklines
    \put(12,0){\line(1,0){24}}
    \put(0,12){\line(0,1){24}}
  \end{picture}}}
\renewcommand*{\tmarkmr}{\registrationColour{%
  \begin{picture}(0,0)
    \setlength{\unitlength}{1bp}\thicklines
    \put(12,0){\line(1,0){24}}
    \put(24,-24){\line(0,1){48}}
    \put(24,0){\oval(12,12)}
  \end{picture}}}
\renewcommand*{\tmarkbr}{\registrationColour{%
  \begin{picture}(0,0)
    \setlength{\unitlength}{1bp}\thicklines
    \put(12,0){\line(1,0){24}}
    \put(0,-36){\line(0,1){24}}
  \end{picture}}}
\renewcommand*{\tmarkbm}{\registrationColour{%
  \begin{picture}(0,0)
    \setlength{\unitlength}{1bp}\thicklines
    \put(-24,-24){\line(1,0){48}}
    \put(0,-36){\line(0,1){24}}
    \put(0,-24){\oval(12,12)}
  \end{picture}}}
\renewcommand*{\tmarkbl}{\registrationColour{%
  \begin{picture}(0,0)
    \setlength{\unitlength}{1bp}\thicklines
    \put(-36,0){\line(1,0){24}}
    \put(0,-36){\line(0,1){24}}
  \end{picture}}}
\renewcommand*{\tmarkml}{\registrationColour{%
  \begin{picture}(0,0)
    \setlength{\unitlength}{1bp}\thicklines
    \put(-36,0){\line(1,0){24}}
    \put(-24,-24){\line(0,1){48}}
    \put(-24,0){\oval(12,12)}
  \end{picture}}}
%    \end{macrocode}
% 
% \changes{v3.7m}{2020/08/05}{Removed redefinition of \cs{trimmarks}
% inside \cs{quarkmarks}, it only adds an extra group compared to the
% normal \cs{trimmarks}}
% Removed redefintion of \cmd{\trimmarks}, seemingly no need for it.
%    \begin{macrocode}
%% \renewcommand*{\trimmarks}{%
%% %%  \special{papersize=\the\stockwidth,\the\stockheight}
%%   {%
%%   \vbox to \z@{\vskip-1in \vskip\trimtop % top of logical page
%%     \hb@xt@\z@{\hskip-1in
%%       \ifodd\c@page
%%         \hskip\stockwidth \hskip-\trimedge \hskip-\paperwidth
%%       \else
%%         \if@twoside
%%           \hskip\trimedge % left of logical page
%%         \else
%%           \hskip\stockwidth \hskip-\trimedge \hskip-\paperwidth
%%         \fi
%%       \fi
%%       \vbox to \paperheight{%
%%         \let\protect\relax %      <- v1.4 addition
%    \end{macrocode}
% We remember to add \cs{trimmarkscolor}
% \changes{v3.6h}{2010/12.05}{added \cs{trimmarkscolor}}
%    \begin{macrocode}
%%         \hb@xt@\paperwidth{\trimmarkscolor\tmarktl\hfil\tmarktm\hfil\tmarktr}%
%%         \vfil
%%         \hb@xt@\paperwidth{\trimmarkscolor\tmarkml\hfil\tmarkmr}%
%%         \vfil
%%         \hb@xt@\paperwidth{\trimmarkscolor\tmarkbl\hfil\tmarkbm\hfil\tmarkbr}}%
%%       \hss}%
%%     \vss}}%
%%   }
}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% As of the format update 2020/10/01 a hooking mechanism was added
% to the kernel. One of these provides a hook into the background of
% the shipped out pages, ideal for adding trimmarks. This hooking
% system saves us from messing with \cmd{\shipout} direction (in
% potentially incompatible ways).
% 
% \changes{v3.7m}{2020/08/05}{Applying a format check and adding
% trimmarks via hook if available}
%
% Note that the hook will be named \texttt{memoir/trimmarks} of easy
% reference if one ever need to do some order readjustments. See
% \cite{LTHOOKS,LTSHIPOUT} for more details on the hooking system. The
% extra \cmd{\ifshowtrims} inside the hook is to accommodate for the
%   \cmd{\showtrimson}/\cmd{\showtrimsoff} commands which can be
%   adjusted after the hook was added.
% \changes{v3.8.4}{2025/09/24}{Removed format check}
%    \begin{macrocode}
\renewcommand\mem@trimmarks@initial@vskip{}
\renewcommand\mem@trimmarks@initial@hskip{}
\ifshowtrims
  \AddToHook{shipout/background}[./trimmarks]{%
    \ifshowtrims\put(0,0){\trimmarks}\fi
  }
\fi

%    \end{macrocode}
% ^^A % Here follows then the old code where Any marks are put onto the pages by adding to the \cs{shipout}
% ^^A % routine.
% ^^A %
% ^^A % \begin{macro}{\mem@oldshipout}
% ^^A % Keep a copy of the current version of \cs{shipout} in \cs{mem@oldshipout}.
% ^^A %    \begin{macrocode}
% ^^A   \let\mem@oldshipout\shipout
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A %
% ^^A % \begin{macro}{\mem@shipi}
% ^^A % \begin{macro}{\mem@shipii}
% ^^A % Effectively these will add the \cs{trimmarks} to the box holding
% ^^A % the contents of the page. Note that any \cs{makeindex} must come 
% ^^A % \emph{before} \Lpack{pagesel} (and \Lpack{selectp}) package.
% ^^A % \changes{v1.618}{2005/09/03}{Changed \cs{mem@shipii} for the pagesel package,
% ^^A %              courtesy James Szinger (mempatch v311)}
% ^^A % \changes{v1.61803}{2008/01/30}{Added \cs{ifshowtrims} to \cs{mem@shipii}
% ^^A %                    (mempatch v4.5)}
% ^^A % \changes{v1.6180339f}{2009/06/24}{Added Dan Luecking's fix to 
% ^^A % \cs{mem@shippii} to cater for another merry hyperref change!}
% ^^A % \changes{v1.6180339c}{2009/11/13}{Replaced Dans fix with a fix from
% ^^A % Heiko Oberdiek}
% ^^A %    \begin{macrocode}
% ^^A   \newcommand*{\mem@shipi}{%
% ^^A     \ifvoid\@cclv\expandafter\aftergroup\fi\mem@shipii}
% ^^A   \newcommand*\mem@shipii{%
% ^^A     \ifvoid\@cclv
% ^^A       \mem@oldshipout\box\@cclv
% ^^A     \else
% ^^A       \ifshowtrims
% ^^A %    \end{macrocode}
% ^^A % Heiko Oberdiek responded to a problem reported by Rolf
% ^^A % Niepraschk. The earlier implementation might cause the output box to
% ^^A % be shifted. Heikos explanation (in response to the line 
% ^^A %  \verb?\mem@oldshipout\vbox{\trimmarks\ifvbox\@cclv\unvbox\else\box\fi\@cclv}?) :
% ^^A % \begin{verbatim}
% ^^A %   In vertical mode (\mem@oldshipout\vbox{...}) TeX puts
% ^^A %   interline skip between two boxes (\trimmarks and \@cclv),
% ^^A %   here \linekskip (1pt) is put inbetween causing the
% ^^A %   shift downwards.
% ^^A % \end{verbatim}
% ^^A % Heiko also provided the fix used below. Actually Heikos fix also
% ^^A % fixes a problem that might cause glue settings to disappear.
% ^^A %    \begin{macrocode}
% ^^A       \mem@oldshipout\vbox{%
% ^^A           \trimmarks
% ^^A           \nointerlineskip
% ^^A           \box\@cclv
% ^^A        }%
% ^^A       \else
% ^^A         \mem@oldshipout\box\@cclv
% ^^A       \fi
% ^^A     \fi}
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A % \end{macro}
% ^^A %
% ^^A % \begin{macro}{\shipout}
% ^^A % Our new version of \cs{shipout}, which is only needed for the 
% ^^A % \Lopt{showtrims} option. This adds \cs{mem@shipi} to the page box
% ^^A % which then calls the original version of \cs{shipout}.
% ^^A %    \begin{macrocode}
% ^^A   \ifshowtrims
% ^^A     \renewcommand*{\shipout}{\afterassignment\mem@shipi\setbox\@cclv=}
% ^^A   \fi
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A %    \begin{macrocode}
% ^^A } % end format check, else part
% ^^A 
% ^^A %    \end{macrocode}
% ^^A %
%
% \section{Verbatims, boxes, and files}
%
%
% Until January 2024 the class contained an embedded and modified
% version of the \Lpack{verbatim} package where PW had added some
% extra features to the verbatim system. As time have progressed the
% LaTeX team has taken all the required tool packages under their wing
% and continuously update them. Thus is it unfeasible to embed a
% package like \Lpack{verbatim} anymore. The embeded copy have
% therefore been replaced by simply loading the \Lpack{verbatim}
% package.
%
% Eventhough we could patch in the changed PW made to \Lpack{verbatim}
% we've decided against it. The two features he added was marking tabs
% using a number of spaces (turned off by default) and enabling line
% breaks at white space (turned off by default). It simply gets to
% messy trying to patch in both features, given that the number of
% users using it is probably very low.
%
% Note that our modified copy of \Lpack{verbatim} had all references
% to \cs{leftskip} and \cs{rightskip} replaced by \cs{memRTLleftskip}
% and \cs{memRTLrightskip}. For now we have no intention of patching
% these into the \Lpack{verbatim} code, but it should be straight
% forward if needed.
%
% \subsection{Additions to the verbatim package}
% 
% \changes{v3.8.2}{2024/01/24}{Replaced embedded altered copy of
% \Lpack{verbatim} with loading the package}
% Load the package instead of embedding it.
%    \begin{macrocode}
\RequirePackage{verbatim}      
%    \end{macrocode}
%
% A future update (\verb|github #1245|) to \Lpack{verbatim} will enable
% \cs{verbatiminput*} to mark tabs as if it was spaces. If that
% version has not been released yet, we add the patch
%    \begin{macrocode}
\@ifpackagelater{verbatim}{2024/01/21}{}{
  \def\verbatiminput{\begingroup
    \@ifstar{\verbatim@input{\@setupverbvisiblespace\@vobeyspaces}}%
            {\verbatim@input{\frenchspacing\@vobeyspaces}}}
}

%    \end{macrocode}
% it of course requires an updated kernel.
%
% \begin{macro}{\setverbatimfont}
% \begin{macro}{\m@mverbfont}
% We do provide an interface to set the font used in
% verbatims. Internally in \Lpack{verbatim} this is done via \cs{verbatim@font}.
%    \begin{macrocode}
\newcommand{\setverbatimfont}[1]{\def\m@mverbfont{#1}}
\setverbatimfont{\normalfont\ttfamily}
\patchcmd\verbatim@font{\normalfont\ttfamily}%
  {\m@mverbfont}%
  {}%
  {\typeout{Paching \string\verbatim@font\space failed}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% % \subsubsection{The \texttt{comment} environment}
% 
% The \Lpack{verbatim} package provides the \Lenv{comment} environment
% that ignores its contents. This is a very useful feature, and we
% would like users to be able todefine their own \Lenv{comment} like
% envs. The following code is PWs original code, only difference is
% that we do not define \Lenv{comment} using the code. We leave the
% \Lpack{verbatim} alone.
% % \begin{macro}{\setupcomment}
% \cs{setupcomment} does all the \cs{let}s in the original \cs{comment} code. For reference see the \cite{VERBATIM} sources.
%    \begin{macrocode}
\newcommand{\setupcomment}{%
  \let\do\@makeother\dospecials\catcode`\^^M\active
  \let\verbatim@startline\relax
  \let\verbatim@addtoline\@gobble
  \let\verbatim@processline\relax
  \let\verbatim@finish\relax}
%    \end{macrocode}
% \end{macro}
%
% The macros below do no checking to see if something has (not) been defined
% previously. It's `user beware' time.
%
% \begin{macro}{\newcomment}
% \cs{newcomment}\marg{name} creates a new comment environment called 
% \meta{name}. This is a generalisation of the original comment code.
%    \begin{macrocode}
\newcommand{\newcomment}[1]{%
  \expandafter\def\csname #1\endcsname{\@bsphack\setupcomment\verbatim@}%
  \expandafter\let\csname end#1\endcsname=\@esphack}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\commentsoff}
% \cs{commentsoff}\marg{name} switches off the \meta{name} comment 
% environment by defining the relevent macros to do nothing.
%    \begin{macrocode}
\newcommand{\commentsoff}[1]{%
  \expandafter\def\csname #1\endcsname{}%
  \expandafter\def\csname end#1\endcsname{}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\commentson}
% \cs{commentson}\marg{name} switches on the \meta{name} comment 
% environment. It has to do the same things as \cs{newcomment} does,
% so let \cs{newcomment} do the work.
%    \begin{macrocode}
\newcommand{\commentson}[1]{\newcomment{#1}}

%    \end{macrocode}
% \end{macro}
%
% 
% 
% \subsubsection{Disabled interface macros}
%
% These are macros that via the un-embedding are no longer
% used. Relevant macros are defined to to issue a warning, others just
% does not do anything.
% 
% \changes{v3.8.2}{2024/01/24}{Added defaults for disabled macros}
% Macros for enabling marking tabs in verbatim, have been
% discontinued.
%    \begin{macrocode}
\newcommand*\tabsoff{} % defined to do nothing
\newcommand*\tabson{
  \@memwarn{As of January 2024, \string\tabson\space has been discontinued.}
}

%    \end{macrocode}
%
% Code for automatic line breaking in verbatim has been discontinued.
%    \begin{macrocode}
\newlength\verbatimindent
\newcommand*\verbatimbreakchar{} % silently does nothing as it
                                 % needs \wrappingon to be enabled
\newcommand*\setverbatimbreak{} % never used
\newcommand*\wrappingon{
  \@memwarn{As of January 2024, \string\wrappingon\space has been discontinued.}
}
\newcommand*\wrappingoff{} % defined to do nothing
\def\wrapright{} % internal macro no longer used
%    \end{macrocode}
%
%   
% \subsubsection{About the \texttt{verbatim} adjustments that have been removed}
%
% The adjustments PW made that we removed (in January 2024) can
% actually be patched back in using the following code and
% patches. Left here for reference. Will probably be removed at some
% point.
%
% First the code needed by the patches
% \begin{verbatim}
% % extra hook to be added at the end of verbatims
% \newtoks\afterevery@verbatim
% \afterevery@verbatim={}
% % code for marking tabs using a number of spaces
% \newcount\tab@position
% \def\mem@xobeytab{%
%   \typeout{\the\tab@position}
%   \loop
%    \toks@\expandafter{\the\toks@\@xobeysp}%
%    \advance\tab@position-1
%   \ifnum\tab@position>-1 \repeat% was 0, but that never gave 4 spaces
% }
% \def\verbatim@tabexpand#1{%
%   \ifx#1\@nil
%     \the\toks@
%     \expandafter\par
%   \else
%     \ifx#1\@xobeytab
%       \@xobeytab
%     \else
%       \toks@\expandafter{\the\toks@#1}%
%       \advance\tab@position\m@ne
%     \fi
%     \ifnum\tab@position=0 \tab@position\tab@size \fi
%     \expandafter\verbatim@tabexpand
%   \fi
% }
% \newif\ift@bs
% \def\@maybeobeytabs{}%
% % The code to enable marking tabs
% \newcommand{\tabson}[1][4]{%
%   % firstly, has to be at least 1, so if less than one, we disable visible tabs
%   \ifnum\@ne > #1\relax
%     \typeout{#1 gives tabs off}
%     \tabsoff
%   \else
%     \t@bstrue
%     \let\@xobeytab\mem@xobeytab
%     \def\tab@size{#1\relax}%
%     \def\@maybeobeytabs{\@vobeytabs}%
%   \fi
% }
% \newcommand{\tabsoff}{%
%   \t@bsfalse
%   \def\tab@size{\z@}%
%   \def\@maybeobeytabs{}%
% }
% % default is off
% \tabsoff
% % \verbatim@processline is redefined to this in certain places if tabs are on
% \def\tabverbatim@processline{\tab@position\tab@size%
%   \toks@{}%
%   \expandafter\verbatim@tabexpand\the\verbatim@line\@nil}
% %   Code for the wrapping system, \cs{raggedwrap} was moved
% %   elsewhere in the code so is still there.
% \newcommand*{\wrappingon}{%
%   \def\@xobeysp{~\discretionary{\verbatimbreakchar}%
%     {\kern\verbatimindent}{}}%
%   \def\wrapright{\raggedwrap}}
% \newcommand*{\wrappingoff}{%
%   \def\@xobeysp{\leavevmode\penalty\@M\ }%
%   \def\wrapright{}}
% \wrappingoff
% \end{verbatim}
%
% Next the actual patching
% \begin{verbatim}
% % % patch \@verbatim, two changes
% % firstly change leftskip into the memoir aliases
% \patchcmd\@verbatim{%
%   \leftskip\@totalleftmargin\rightskip\z@%
% }{%
%   \memRTLleftskip\@totalleftmargin\memRTLrightskip\z@%
% }{}{\typeout{first patch for \string\@verbatim\space failed}}
% % secondly add the wrapping code at the very end, we could probably
% % use the macro hook here
% \patchcmd\@verbatim{%
%   \everypar \expandafter{\the\everypar \unpenalty}%
% }{%
%   \everypar \expandafter{\the\everypar \unpenalty}%
%   \wrapright\the\afterevery@verbatim%
% }{}{\typeout{second patch for \string\@verbatim\space failed}}
%   
% % add tabs support for \verbatim
% \patchcmd\verbatim{\begingroup\@verbatim}{%
%   \begingroup%
%     \ift@bs%
%       \def\verbatim@processline{\tabverbatim@processline}%
%     \fi%
%     \@verbatim%
% }{}{\typeout{Patch 1 for \string\verbatim\space failed}}
% % add tab support  
% \patchcmd\verbatim{\@vobeyspaces}{%
%   \@vobeyspaces\@maybeobeytabs%
% }{}{\typeout{Patch 2 for \string\verbatim\space failed}}
% 
% \expandafter\patchcmd\expandafter{\csname verbatim*\endcsname}%
% {\begingroup\@verbatim}{%
%     \begingroup%
%     \ift@bs%
%       \def\verbatim@processline{\tabverbatim@processline}%
%       \def\@setupverbvisibletab{}% remove redef of \@xobeytab
%     \fi%
%     \@verbatim%
% }{}{\typeout{Patch 1 for \string\verbatim*\space failed}}
% \expandafter\patchcmd\expandafter{\csname verbatim*\endcsname}%
% {\@vobeyspaces}{%
%   \@vobeyspaces\@maybeobeytabs%
% }{}{\typeout{Patch 2 for \string\verbatim*\space failed}}              
%
% patches for \verbatiminput, there are 3
% \patchcmd\verbatiminput{\begingroup\@ifstar}{%
%   \begingroup%
%     \ift@bs%
%       \def\verbatim@processline{\tabverbatim@processline}%
%     \fi%
%     \@ifstar%
% }{}{\typeout{Patch 1 for \string\verbatiminput\space failed}}
% 
% \patchcmd\verbatiminput{\@ifstar{\verbatim@input\relax}}{%
%   \@ifstar{\verbatim@input{\@maybeobeytabs}}%
% }{}{\typeout{Patch 2 for \string\verbatiminput\space failed}}
% 
% \patchcmd\verbatiminput{\frenchspacing\@vobeyspaces}{%
%   \frenchspacing\@vobeyspaces\@maybeobeytabs%
% }{}{\typeout{Patch 3 for \string\verbatiminput\space failed}}
% 
% \end{verbatim}
% 
%
%
%
% ^^A % All the code in this section was added for version 1.2 of the class.
% ^^A % \changes{v1.2}{2002/07/27}{Section `Verbatims, boxes and files' added}
% ^^A %
% ^^A % \subsection{Modified version of the verbatim package}
% ^^A %
% ^^A % \noindent{\color{red}\rule\textwidth{5mm}}
% ^^A % 
% ^^A % Much of this is from the \Lpack{verbatim} package code~\cite{VERBATIM}.
% ^^A % Unless indicated otherwise, the code and commentary is from that
% ^^A % package.
% ^^A %
% ^^A %
% ^^A % \subsubsection{Preliminaries}
% ^^A %
% ^^A % \begin{macro}{\every@verbatim}
% ^^A % \begin{macro}{\afterevery@verbatim}
% ^^A %    The hook (i.e., token register) \cs{every@verbatim}
% ^^A %    is initialized to \meta{empty}.
% ^^A %
% ^^A % PW added the \cs{afterevery@verbatim} hook.
% ^^A %    \begin{macrocode}
% ^^A \newtoks\every@verbatim
% ^^A   \every@verbatim={}
% ^^A \newtoks\afterevery@verbatim
% ^^A   \afterevery@verbatim={}
% ^^A 
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A % \end{macro}
% ^^A %
% ^^A %
% ^^A % \begin{macro}{\@makeother}
% ^^A %    \cs{@makeother} takes as argument a character and changes
% ^^A %    its category code to $12$ (other).
% ^^A %    \begin{macrocode}
% ^^A \def\@makeother#1{\catcode`#112\relax}
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A %
% ^^A %
% ^^A % \begin{macro}{\@vobeyspaces}
% ^^A %    The macro \cs{@vobeyspaces} causes spaces in the input
% ^^A %    to be printed as spaces in the output.
% ^^A %    
% ^^A %    In the Nov-2023 kernel update, some changes were made to how
% ^^A %    \verb|\verb| handles tabs. We need to adjust accordingly. Note
% ^^A %    that it will be better to just load the \Lpack{verbatim} package
% ^^A %    and make adjustments to it. The fix comes from \url{https://github.com/latex3/latex2e/issues/1160#issuecomment-1793564381}.
% ^^A % \changes{v3.8.2}{2023/11/07}{Added fix for kernel update}
% ^^A %    \begin{macrocode}
% ^^A \begingroup
% ^^A   \catcode`\ =\active%
% ^^A   \IfFormatAtLeastTF{2023-11-01}% 
% ^^A % active spaces at line beginning are absorbed as macro arguments
% ^^A {\def\x{\def\@vobeyspaces{\catcode`\ \active\let \@xobeysp\@vobeytabs}}}%
% ^^A {\def\x{\def\@vobeyspaces{\catcode`\ \active\let \@xobeysp}}}%
% ^^A   % was: \def\x{\def\@vobeyspaces{\catcode`\ \active\let \@xobeysp}}
% ^^A   \expandafter\endgroup\x
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A %
% ^^A %
% ^^A % \begin{macro}{\@xobeysp}
% ^^A %    The macro \cs{@xobeysp} produces exactly one space in
% ^^A %    the output, protected against breaking just before it.
% ^^A %    (\cs{@M} is an abbreviation for the number $10000$.)
% ^^A %    \begin{macrocode}
% ^^A \def\@xobeysp{\leavevmode\penalty\@M\ }
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A %
% ^^A %
% ^^A % \begin{macro}{\verbatim@line}
% ^^A %    We use a newly defined token register called \cs{verbatim@line}
% ^^A %    that will be used as the character buffer.
% ^^A %    \begin{macrocode}
% ^^A \newtoks\verbatim@line
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A %
% ^^A % PW. I have extended the original \Lpack{verbatim} package code to handle
% ^^A % TABs within verbatims. Normally TeX replaces a TAB by either a single space or
% ^^A % ignores it altogether. For this purpose I have bits of code from the \Lpack{moreverb}
% ^^A % package~\cite{MOREVERB} for handling TABs.
% ^^A %
% ^^A % \textit{Code and commentary from moreverb.}
% ^^A %
% ^^A % We define a few auxiliary macros and counters for expanding tabs.
% ^^A %    \begin{macrocode}
% ^^A \newcount\tab@position 
% ^^A %    \end{macrocode}
% ^^A %
% ^^A % \begin{macro}{\@xobeytab}
% ^^A % \cs{@xobeytab} puts enough spaces in to get to the next nominal
% ^^A % tab stop
% ^^A %    \begin{macrocode}
% ^^A \def\@xobeytab{%
% ^^A   \loop
% ^^A     \toks@\expandafter{\the\toks@\@xobeysp}%
% ^^A     \advance\tab@position-1
% ^^A   \ifnum\tab@position>0 \repeat
% ^^A }
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A %
% ^^A % \begin{macro}{\@vobeytabs}
% ^^A % \cs{@vobeytabs} initialises use of \cs{@xobeytab}.  Needs to be
% ^^A % executed within a group, as mustn't be allowed to leak out into the
% ^^A % wide world.
% ^^A %
% ^^A %    \begin{macrocode}
% ^^A \begingroup
% ^^A   \catcode`\^^I=\active
% ^^A   \gdef\@vobeytabs{\catcode`\^^I\active\let^^I\@xobeytab}%
% ^^A \endgroup
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A %
% ^^A % \begin{macro}{\verbatim@tabexpand}
% ^^A % \cs{verbatim@tabexpand}\marg{body of line}\cs{@nil} processes every
% ^^A % character of a line by tail recursion, counting the characters and
% ^^A % juggling things when a tab is encountered.
% ^^A %    \begin{macrocode}
% ^^A \def\verbatim@tabexpand#1{%
% ^^A   \ifx#1\@nil
% ^^A     \the\toks@
% ^^A     \expandafter\par
% ^^A   \else
% ^^A     \ifx#1\@xobeytab
% ^^A       \@xobeytab
% ^^A     \else
% ^^A %    \end{macrocode}
% ^^A %
% ^^A % We can safely put \cs{@xobeysp} into the token register, since it
% ^^A % does precisely what we need
% ^^A %    \begin{macrocode}
% ^^A       \toks@\expandafter{\the\toks@#1}%
% ^^A       \advance\tab@position\m@ne
% ^^A     \fi
% ^^A     \ifnum\tab@position=0 \tab@position\tab@size \fi
% ^^A     \expandafter\verbatim@tabexpand
% ^^A   \fi
% ^^A }
% ^^A 
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A %
% ^^A % \textit{End of code and commentary from moreverb.}
% ^^A %
% ^^A % PW. Some macros for turning tabbing on and off.
% ^^A %
% ^^A % \begin{macro}{\tabson}
% ^^A % \begin{macro}{\tabsoff}
% ^^A % \begin{macro}{\@maybeobeytabs}
% ^^A % \cs{tabson} turns tabbing on, and \cs{tabsoff} turns it off. Default
% ^^A % is no tabbing.
% ^^A %    \begin{macrocode}
% ^^A \newif\ift@bs
% ^^A \newcommand{\tabson}[1][4]{%
% ^^A   \ifnum\@ne > #1\relax
% ^^A     \tabsoff
% ^^A   \else
% ^^A     \t@bstrue
% ^^A     \def\tab@size{#1\relax}%
% ^^A     \def\@maybeobeytabs{\@vobeytabs}%
% ^^A   \fi
% ^^A }
% ^^A \newcommand{\tabsoff}{%
% ^^A   \t@bsfalse
% ^^A   \def\tab@size{\z@}%
% ^^A   \def\@maybeobeytabs{}%
% ^^A }
% ^^A \tabsoff
% ^^A 
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A % \end{macro}
% ^^A % \end{macro}
% ^^A %
% ^^A % \begin{macro}{\tabverbatim@processline}
% ^^A % Process a line with TABs (extracted from \Lpack{moreverb}).
% ^^A %    \begin{macrocode}
% ^^A \def\tabverbatim@processline{\tab@position\tab@size
% ^^A   \toks@{}%
% ^^A   \expandafter\verbatim@tabexpand\the\verbatim@line\@nil}
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A %
% ^^A % \begin{macro}{\notabverbatim@processline}
% ^^A % Processes a line ignoring TABs (this is the original \Lpack{verbatim}
% ^^A % package definition of \cs{verbatim@processline}).
% ^^A %    \begin{macrocode}
% ^^A \def\notabverbatim@processline{\the\verbatim@line\par}
% ^^A 
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A %
% ^^A % \textit{We are now back to the \Lpack{verbatim} code.}
% ^^A %
% ^^A % The following four macros are defined globally in a way suitable for
% ^^A % the \texttt{verbatim} and \texttt{verbatim*} environments.
% ^^A % \begin{macro}{\verbatim@startline}
% ^^A % \begin{macro}{\verbatim@addtoline}
% ^^A % \begin{macro}{\verbatim@processline}
% ^^A %    \cs{verbatim@startline} initializes processing of a line
% ^^A %    by emptying the character buffer (\cs{verbatim@line}).
% ^^A %    \begin{macrocode}
% ^^A \def\verbatim@startline{\verbatim@line{}}
% ^^A %    \end{macrocode}
% ^^A %    \cs{verbatim@addtoline} adds the tokens in its argument
% ^^A %    to our buffer register \cs{verbatim@line} without expanding
% ^^A %    them.
% ^^A %    \begin{macrocode}
% ^^A \def\verbatim@addtoline#1{%
% ^^A   \verbatim@line\expandafter{\the\verbatim@line#1}}
% ^^A %    \end{macrocode}
% ^^A %    Processing a line inside a \texttt{verbatim} or \texttt{verbatim*}
% ^^A %    environment means printing it.
% ^^A %    Ending the line means that we have to begin a new paragraph.
% ^^A %    We use \cs{par} for this purpose.  Note that \cs{par}
% ^^A %    is redefined in \cs{@verbatim} to force \TeX{} into horizontal
% ^^A %    mode and to insert an empty box so that empty lines in the input
% ^^A %    do appear in the output.
% ^^A % (PW changed next line from \\
% ^^A % \verb?\def\verbatim@processline{\the\verbatim@line\par}?
% ^^A %    \begin{macrocode}
% ^^A \def\verbatim@processline{\notabverbatim@processline}
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A % \end{macro}
% ^^A % \end{macro}
% ^^A %
% ^^A % \begin{macro}{\verbatim@finish}
% ^^A %    As a default, \cs{verbatim@finish} processes the remaining
% ^^A %    characters.
% ^^A %    When this macro is called we are facing the following problem:
% ^^A %    when the \verb?\end{verbatim}?
% ^^A %    command is encountered \cs{verbatim@processline} is called
% ^^A %    to process the characters preceding the command on the same
% ^^A %    line.  If there are none, an empty line would be output if we
% ^^A %    did not check for this case.
% ^^A %
% ^^A %    If the line is empty \verb?\the\verbatim@line? expands to
% ^^A %    nothing.  To test this we use a trick similar to that on p.\ 376
% ^^A %    of the \TeX{}book, but with \verb?$?\ldots\verb?|$? instead of
% ^^A %    the \verb?!? tokens.  These \verb?$? tokens can never have the same
% ^^A %    category code as a \verb?$? token that might possibly appear in the
% ^^A %    token register \cs{verbatim@line}, as such a token will always have
% ^^A %    been read with category code $12$ (other).
% ^^A %    Note that \cs{ifcat} expands the following tokens so that
% ^^A %    \verb?\the\verbatim@line? is replaced by the accumulated
% ^^A %    characters
% ^^A %    \begin{macrocode}
% ^^A \def\verbatim@finish{\ifcat$\the\verbatim@line$\else
% ^^A   \verbatim@processline\fi}
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A %
% ^^A %
% ^^A % \subsubsection{The \texttt{verbatim} and \texttt{verbatim*} environments}
% ^^A %
% ^^A % \begin{macro}{\verbatim@font}
% ^^A %    We start by defining the macro \cs{verbatim@font} that is
% ^^A %    to select the font and to set font-dependent parameters.
% ^^A %    Then we go through \cs{verbatim@nolig@list} to avoid
% ^^A %    certain ligatures.
% ^^A %    \cs{verbatim@nolig@list} is a macro defined in the \LaTeXe{} kernel
% ^^A %    to expand to
% ^^A % \begin{verbatim}
% ^^A %    \do\`\do\<\do\>\do\,\do\'\do\-
% ^^A % \end{verbatim}
% ^^A %    All the characters in this list can be part of a ligature in some
% ^^A %    font or other.
% ^^A % 
% ^^A % PW. This is the original version which I'm going to replace.
% ^^A % \begin{verbatim}
% ^^A % \def\verbatim@font{\normalfont\ttfamily
% ^^A %                    \hyphenchar\font\m@ne
% ^^A %                    \let\do\do@noligs
% ^^A %                    \verbatim@nolig@list}
% ^^A % \end{verbatim}
% ^^A % Actually the kernel defines the macro \verb+\@noligs+ which just
% ^^A % runs the last two lines of the \verb+\verbatim@font+ above. As other
% ^^A % package may add stuff to \verb+\@noligs+, we will use that instead.
% ^^A % \end{macro}
% ^^A %
% ^^A % \begin{macro}{\setverbatimfont}
% ^^A % \begin{macro}{\m@mverbfont}
% ^^A % \begin{macro}{\verbatim@font}
% ^^A % User level handle for changing the font used for verbatim text.
% ^^A % \changes{v1.61803398}{2009/09/10}{Changed the last two lines of
% ^^A % \cs{verbatim@font} into using \cs{@noligs} instead. This fixes
% ^^A % problem with upquote.}
% ^^A %    \begin{macrocode}
% ^^A \newcommand{\setverbatimfont}[1]{\def\m@mverbfont{#1}}
% ^^A \setverbatimfont{\normalfont\ttfamily}
% ^^A 
% ^^A \def\verbatim@font{\m@mverbfont
% ^^A                    \hyphenchar\font\m@ne
% ^^A                    \@noligs}
% ^^A 
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A % \end{macro}
% ^^A % \end{macro}
% ^^A %
% ^^A %
% ^^A % \begin{macro}{\@verbatim}
% ^^A %    The macro \cs{@verbatim} sets up things properly.
% ^^A %    First of all, the tokens of the \cs{every@verbatim} hook
% ^^A %    are inserted.
% ^^A %    Then a \texttt{trivlist} environment is started and its first
% ^^A %    \cs{item} command inserted.
% ^^A %    Each line of the \texttt{verbatim} or \texttt{verbatim*}
% ^^A %    environment will be treated as a separate paragraph.
% ^^A % \changes{v1.61803398}{2009/07/18}{Added bidi support to \cs{@verbatim}}
% ^^A %    \begin{macrocode}
% ^^A \def\@verbatim{\the\every@verbatim
% ^^A   \trivlist \item \relax
% ^^A %    \end{macrocode}
% ^^A %    The following extra vertical space is for compatibility with the
% ^^A %    \LaTeX kernel: otherwise, using the \Lpack{verbatim} package changes
% ^^A %    the vertical spacing of a \texttt{verbatim} environment nested within a
% ^^A %    \texttt{quote} environment.
% ^^A %    \begin{macrocode}
% ^^A   \if@minipage\else\vskip\parskip\fi
% ^^A %    \end{macrocode}
% ^^A %    The paragraph parameters are set appropriately:
% ^^A %    the penalty at the beginning of the environment,
% ^^A %    left and right margins, paragraph indentation, the glue to
% ^^A %    fill the last line, and the vertical space between paragraphs.
% ^^A %    The latter space has to be zero since we do not want to add
% ^^A %    extra space between lines.
% ^^A %    \begin{macrocode}
% ^^A   \@beginparpenalty \predisplaypenalty 
% ^^A %%%  \leftskip\@totalleftmargin\rightskip\z@
% ^^A   \memRTLleftskip\@totalleftmargin\memRTLrightskip\z@
% ^^A   \parindent\z@\parfillskip\@flushglue\parskip\z@
% ^^A %    \end{macrocode}
% ^^A %    There's one point to make here:
% ^^A %    the \texttt{list} environment uses \TeX's \cs{parshape}
% ^^A %    primitive to get a special indentation for the first line
% ^^A %    of the  list.
% ^^A %    If the list begins with a \texttt{verbatim} environment
% ^^A %    this \cs{parshape} is still in effect.
% ^^A %    Therefore we have to reset this internal parameter explicitly.
% ^^A %    We could do this by assigning $0$ to \cs{parshape}.
% ^^A %    However, there is a simpler way to achieve this:
% ^^A %    we simply tell \TeX{} to start a new paragraph.
% ^^A %    As is explained on p.~103 of the \TeX{}book, this resets
% ^^A %    \cs{parshape} to zero.
% ^^A %    \begin{macrocode}
% ^^A   \@@par
% ^^A %    \end{macrocode}
% ^^A %    We now ensure that \cs{par} has the correct definition,
% ^^A %    namely to force \TeX{} into horizontal mode
% ^^A %    and to include an empty box.
% ^^A %    This is to ensure that empty lines do appear in the output.
% ^^A %    Afterwards, we insert the \cs{interlinepenalty} since \TeX{}
% ^^A %    does not add a penalty between paragraphs (here: lines)
% ^^A %    by its own initiative. Otherwise a \texttt{verbatim} environment
% ^^A %    could be broken across pages even if a \cs{samepage}
% ^^A %    declaration were present.
% ^^A %
% ^^A %    However, in a top-aligned minipage, this will result in an extra
% ^^A %    empty line added at the top. Therefore, a slightly more
% ^^A %    complicated construct is necessary.
% ^^A %    One of the important things here is the inclusion of
% ^^A %    \cs{leavevmode} as the first macro in the first line, for example,
% ^^A %    a blank verbatim line is the first thing in a list item.
% ^^A %    \begin{macrocode}
% ^^A   \def\par{%
% ^^A     \if@tempswa
% ^^A       \leavevmode\null\@@par\penalty\interlinepenalty
% ^^A     \else
% ^^A       \@tempswatrue
% ^^A       \ifhmode\@@par\penalty\interlinepenalty\fi
% ^^A     \fi}%
% ^^A %    \end{macrocode}
% ^^A %    But to avoid an error message when the environment
% ^^A %    doesn't contain any text, we redefine \cs{@noitemerr}
% ^^A %    which will in this case be called by \cs{endtrivlist}.
% ^^A %    \begin{macrocode}
% ^^A   \def\@noitemerr{\@warning{No verbatim text}}%
% ^^A %    \end{macrocode}
% ^^A %    Now we call \cs{obeylines} to make the end of line character
% ^^A %    active,
% ^^A %    \begin{macrocode}
% ^^A   \obeylines
% ^^A %    \end{macrocode}
% ^^A %    change the category code of all special characters,
% ^^A %    to $12$ (other).
% ^^A %    \begin{macrocode}
% ^^A   \let\do\@makeother \dospecials
% ^^A %    \end{macrocode}
% ^^A %    and switch to the font to be used.
% ^^A %    \begin{macrocode}
% ^^A   \verbatim@font
% ^^A %    \end{macrocode}
% ^^A %    To avoid a breakpoint after the labels box, we remove the penalty
% ^^A %    put there by the list macros: another use of \cs{unpenalty}!
% ^^A %    \begin{macrocode}
% ^^A   \everypar \expandafter{\the\everypar \unpenalty}%
% ^^A %    \end{macrocode}
% ^^A % PW added next code at end of \cs{@verbatim}.
% ^^A %    \begin{macrocode}
% ^^A   \wrapright\the\afterevery@verbatim}
% ^^A %    \end{macrocode}   
% ^^A % \end{macro}
% ^^A %
% ^^A %
% ^^A % \begin{macro}{\verbatim}
% ^^A % \begin{macro}{\verbatim*}
% ^^A %    Now we define the toplevel macros.
% ^^A %    \cs{verbatim} is slightly changed:
% ^^A %    after setting up things properly it calls
% ^^A %    \cs{verbatim@start}.
% ^^A %    This is done inside a group, so that \cs{verbatim} can be used
% ^^A %    directly, without \cs{begin}.
% ^^A %
% ^^A % PW. The following is the original code, but I want a version of
% ^^A % \texttt{verbatim} that recognises TABs.
% ^^A % \begin{verbatim}
% ^^A %    \begin{macrocode}
% ^^A % \def\verbatim{%
% ^^A %    \begingroup\@verbatim \frenchspacing\@vobeyspaces 
% ^^A %    \verbatim@start}
% ^^A %    \end{macrocode}
% ^^A %    \cs{verbatim*} is defined accordingly.
% ^^A %    \begin{macrocode}
% ^^A % \@namedef{verbatim*}{\begingroup\@verbatim\verbatim@start}
% ^^A % \def\endverbatim{\endtrivlist\endgroup}
% ^^A % \expandafter\let\csname endverbatim*\endcsname=\endverbatim
% ^^A %    \end{macrocode}
% ^^A % \end{verbatim}
% ^^A %
% ^^A % PW. My code for these is a modified version of the original \Lpack{verbatim}
% ^^A % code.
% ^^A %    \begin{macrocode}
% ^^A \def\verbatim{\begingroup
% ^^A   \ift@bs
% ^^A     \def\verbatim@processline{\tabverbatim@processline}%
% ^^A   \fi
% ^^A   \@verbatim \frenchspacing\@vobeyspaces\@maybeobeytabs\verbatim@start}
% ^^A \@namedef{verbatim*}{\begingroup
% ^^A   \ift@bs
% ^^A     \def\verbatim@processline{\tabverbatim@processline}%
% ^^A   \fi
% ^^A   \@verbatim\@maybeobeytabs\verbatim@start}
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A % \end{macro}
% ^^A %
% ^^A %
% ^^A % \begin{macro}{\endverbatim}
% ^^A % \begin{macro}{\endverbatim*}
% ^^A %    To end the \texttt{verbatim} and \texttt{verbatim*}
% ^^A %    environments it is only necessary to finish the
% ^^A %    \texttt{trivlist} environment started in \cs{@verbatim} and
% ^^A %    close the corresponding group, and handle\footnote{Noted by
% ^^A % Zarko Cucej.} following (non-) paragraph,
% ^^A % by using \cs{@doendpe}.
% ^^A % \changes{v1.4}{2003/11/22}{Added \cs{@doendpe} to \cs{endverbatim} 
% ^^A %                            (from patch v1.8)}
% ^^A % \changes{v2.0a}{2004/03/01}{Refixed \cs{endverbatim}}
% ^^A %    \begin{macrocode}
% ^^A \def\endverbatim{\endtrivlist\endgroup\@doendpe}
% ^^A \@namelet{endverbatim*}\endverbatim
% ^^A 
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A % \end{macro}
% ^^A %
% ^^A % For abnormal \cs{parskip}s the NTG class included the following, but I'm
% ^^A % not sure if it is relevant here, but if it is just how it should be included.
% ^^A % \begin{verbatim}
% ^^A % From NTG, where it is a \cs{def}
% ^^A % \providecommand*{\verbatim}{%
% ^^A %   \topsep=-0.5\parskip
% ^^A %   \@verbatim
% ^^A %   \frenchspacing\@vobeyspaces \@xverbatim}
% ^^A % \end{verbatim}
% ^^A %
% ^^A %
% ^^A % \subsubsection{The \texttt{comment} environment}
% ^^A %
% ^^A %    The \cs{comment} macro is similar to \cs{verbatim*}.
% ^^A %    However, we do not need to switch fonts or set special
% ^^A %    formatting parameters such as \cs{parindent} or \cs{parskip}.
% ^^A %    We need only set the category code of all special characters
% ^^A %    to $12$ (other) and that of \verb?^^M? (the end of line character)
% ^^A %    to $13$ (active).
% ^^A %    The latter is needed for macro parameter delimiter matching in
% ^^A %    the internal macros defined below.
% ^^A %    In contrast to the default definitions used by the
% ^^A %    \cs{verbatim} and \cs{verbatim*} macros,
% ^^A %    we define \cs{verbatim@addtoline} to throw away its argument
% ^^A %    and \cs{verbatim@processline}, \cs{verbatim@startline},
% ^^A %    and \cs{verbatim@finish} to act as no-ops.
% ^^A %    Then we call \cs{verbatim@}.
% ^^A %    But the first thing we do is to call \cs{@bsphack} so that
% ^^A %    this environment has no influence whatsoever upon the spacing.
% ^^A %
% ^^A % PW: This is the original code for the \texttt{comment} environment, 
% ^^A % which I'm going to change.
% ^^A % \begin{verbatim}
% ^^A % \def\comment{\@bsphack
% ^^A %              \let\do\@makeother\dospecials\catcode`\^^M\active
% ^^A %              \let\verbatim@startline\relax
% ^^A %              \let\verbatim@addtoline\@gobble
% ^^A %              \let\verbatim@processline\relax
% ^^A %              \let\verbatim@finish\relax
% ^^A %              \verbatim@}
% ^^A % \end{verbatim}
% ^^A %    \cs{endcomment} is very simple: it only calls
% ^^A %    \cs{@esphack} to take care of the spacing.
% ^^A %    The \cs{end} macro closes the group and therefore takes care
% ^^A %    of restoring everything we changed.
% ^^A % \begin{verbatim}
% ^^A % \let\endcomment=\@esphack
% ^^A % \end{verbatim}
% ^^A %
% ^^A % PW: The remainder of this section is my code.
% ^^A %
% ^^A % \begin{macro}{\setupcomment}
% ^^A % \cs{setupcomment} does all the \cs{let}s in the original \cs{comment} code.
% ^^A %    \begin{macrocode}
% ^^A \newcommand{\setupcomment}{%
% ^^A   \let\do\@makeother\dospecials\catcode`\^^M\active
% ^^A   \let\verbatim@startline\relax
% ^^A   \let\verbatim@addtoline\@gobble
% ^^A   \let\verbatim@processline\relax
% ^^A   \let\verbatim@finish\relax}
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A %
% ^^A % The macros below do no checking to see if something has (not) been defined
% ^^A % previously. It's `user beware' time.
% ^^A %
% ^^A % \begin{macro}{\newcomment}
% ^^A % \cs{newcomment}\marg{name} creates a new comment environment called 
% ^^A % \meta{name}. This is a generalisation of the original comment code.
% ^^A %    \begin{macrocode}
% ^^A \newcommand{\newcomment}[1]{%
% ^^A   \expandafter\def\csname #1\endcsname{\@bsphack\setupcomment\verbatim@}%
% ^^A   \expandafter\let\csname end#1\endcsname=\@esphack}
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A %
% ^^A % \begin{macro}{\commentsoff}
% ^^A % \cs{commentsoff}\marg{name} switches off the \meta{name} comment 
% ^^A % environment by defining the relevent macros to do nothing.
% ^^A %    \begin{macrocode}
% ^^A \newcommand{\commentsoff}[1]{%
% ^^A   \expandafter\def\csname #1\endcsname{}%
% ^^A   \expandafter\def\csname end#1\endcsname{}}
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A %
% ^^A % \begin{macro}{\commentson}
% ^^A % \cs{commentson}\marg{name} switches on the \meta{name} comment 
% ^^A % environment. It has to do the same things as \cs{newcomment} does,
% ^^A % so let \cs{newcomment} do the work.
% ^^A %    \begin{macrocode}
% ^^A \newcommand{\commentson}[1]{\newcomment{#1}}
% ^^A 
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A %
% ^^A % We had better supply the \texttt{comment} environment, as promised.
% ^^A %    \begin{macrocode}
% ^^A \newcomment{comment}
% ^^A 
% ^^A %    \end{macrocode}
% ^^A %
% ^^A % PW: That is the end of my changes and extensions to the original 
% ^^A % \texttt{comment} environment code.
% ^^A %
% ^^A %
% ^^A % \subsubsection{The main loop}
% ^^A %
% ^^A % Here comes the tricky part:
% ^^A % During the definition of the macros we need to use the special
% ^^A % characters \verb?\?, \verb?{?, and \verb?}? not only with their
% ^^A % normal category codes,
% ^^A % but also with category code $12$ (other).
% ^^A % We achieve this by the following trick:
% ^^A % first we tell \TeX{} that \verb?\?, \verb?{?, and \verb?}?
% ^^A % are the lowercase versions of \verb?!?, \verb?[?, and \verb?]?.
% ^^A % Then we replace every occurrence of \verb?\?, \verb?{?, and \verb?}?
% ^^A % that should be read with category code $12$ by \verb?!?, \verb?[?,
% ^^A % and \verb?]?, respectively,
% ^^A % and give the whole list of tokens to \cs{lowercase},
% ^^A % knowing that category codes are not altered by this primitive!
% ^^A %
% ^^A % But first we have ensure that
% ^^A % \verb?!?, \verb?[?, and \verb?]? themselves have
% ^^A % the correct category code!
% ^^A % To allow special settings of these codes we hide their setting in
% ^^A % the macro \cs{vrb@catcodes}.  If it is already defined our new
% ^^A % definition is skipped.
% ^^A %    \begin{macrocode}
% ^^A \@ifundefined{vrb@catcodes}%
% ^^A   {\def\vrb@catcodes{%
% ^^A      \catcode`\!12\catcode`\[12\catcode`\]12}}{}
% ^^A %    \end{macrocode}
% ^^A % This trick allows us to use this code for applications where other
% ^^A % category codes are in effect.
% ^^A %
% ^^A % We start a group to keep the category code changes local.
% ^^A %    \begin{macrocode}
% ^^A \begingroup
% ^^A  \vrb@catcodes
% ^^A  \lccode`\!=`\\ \lccode`\[=`\{ \lccode`\]=`\}
% ^^A %    \end{macrocode}
% ^^A %    We also need the end-of-line character \verb?^^M?,
% ^^A %    as an active character.
% ^^A %    If we were to simply write \verb?\catcode`\^^M=\active?
% ^^A %    then we would get an unwanted active end of line character
% ^^A %    at the end of every line of the following macro definitions.
% ^^A %    Therefore we use the same trick as above:
% ^^A %    we write a tilde \verb?~? instead of \verb?^^M? and
% ^^A %    pretend that the
% ^^A %    latter is the lowercase variant of the former.
% ^^A %    Thus we have to ensure now that the tilde character has
% ^^A %    category code $13$ (active).
% ^^A %    \begin{macrocode}
% ^^A  \catcode`\~=\active \lccode`\~=`\^^M
% ^^A %    \end{macrocode}
% ^^A %    The use of the \cs{lowercase} primitive leads to one problem:
% ^^A %    the uppercase character `\texttt{C}' needs to be used in the
% ^^A %    code below and its case must be preserved.
% ^^A %    So we add the command:
% ^^A %    \begin{macrocode}
% ^^A  \lccode`\C=`\C
% ^^A %    \end{macrocode}
% ^^A %    Now we start the token list passed to \cs{lowercase}.
% ^^A %    We use the following little trick (proposed by Bernd Raichle):
% ^^A %    The very first token in the token list we give to \cs{lowercase} is
% ^^A %    the \cs{endgroup} primitive. This means that it is processed by
% ^^A %    \TeX{} immediately after \cs{lowercase} has finished its operation,
% ^^A %    thus ending the group started by \cs{begingroup} above. This avoids
% ^^A %    the global definition of all macros.
% ^^A %    \begin{macrocode}
% ^^A  \lowercase{\endgroup
% ^^A %    \end{macrocode}
% ^^A % \begin{macro}{\verbatim@start}
% ^^A %    The purpose of \cs{verbatim@start} is to check whether there
% ^^A %    are any characters on the same line as the \verb?\begin{verbatim}?
% ^^A %    and to pretend that they were on a line by themselves.
% ^^A %    On the other hand, if there are no characters remaining
% ^^A %    on the current line we shall just find an end of line character.
% ^^A %    \cs{verbatim@start} performs its task by first grabbing the
% ^^A %    following character (its argument).
% ^^A %    This argument is then compared to an active \verb?^^M?,
% ^^A %    the end of line character.
% ^^A %    \begin{macrocode}
% ^^A     \def\verbatim@start#1{%
% ^^A       \verbatim@startline
% ^^A       \if\noexpand#1\noexpand~%
% ^^A %    \end{macrocode}
% ^^A %    If this is true we transfer control to \cs{verbatim@}
% ^^A %    to process the next line.  We use
% ^^A %    \cs{next} as the macro which will continue the work.
% ^^A %    \begin{macrocode}
% ^^A         \let\next\verbatim@
% ^^A %    \end{macrocode}
% ^^A %    Otherwise, we define \cs{next} to expand to a call
% ^^A %    to \cs{verbatim@} followed by the character just
% ^^A %    read so that it is reinserted into the text.
% ^^A %    This means that those characters remaining on this line
% ^^A %    are handled as if they formed a line by themselves.
% ^^A %    \begin{macrocode}
% ^^A       \else \def\next{\verbatim@#1}\fi
% ^^A %    \end{macrocode}
% ^^A %    Finally we call \cs{next}.
% ^^A %    \begin{macrocode}
% ^^A       \next}%
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A %
% ^^A % \begin{macro}{\verbatim@}
% ^^A %    The three macros \cs{verbatim@}, \cs{verbatim@@},
% ^^A %    and \cs{verbatim@@@} form the ``main loop'' of the
% ^^A %    \texttt{verbatim} environment.
% ^^A %    The purpose of \cs{verbatim@} is to read exactly one line
% ^^A %    of input.
% ^^A %    \cs{verbatim@@} and \cs{verbatim@@@} work together to
% ^^A %    find out whether the four characters
% ^^A %    \cs{end} (all with category code $12$ (other)) occur in that
% ^^A %    line.
% ^^A %    If so, \cs{verbatim@@@} will call
% ^^A %    \cs{verbatim@test} to check whether this \cs{end} is
% ^^A %    part of \verb?\end{verbatim}? and will terminate the environment
% ^^A %    if this is the case.
% ^^A %    Otherwise we continue as if nothing had happened.
% ^^A %    So let's have a look at the definition of \cs{verbatim@}:
% ^^A %    \begin{macrocode}
% ^^A     \def\verbatim@#1~{\verbatim@@#1!end\@nil}%
% ^^A %    \end{macrocode}
% ^^A %    Note that the \verb?!? character will have been replaced by a
% ^^A %    \verb?\? with category code $12$ (other) by the \cs{lowercase}
% ^^A %    primitive governing this code before the definition of this
% ^^A %    macro actually takes place.
% ^^A %    That means that
% ^^A %    it takes the line, puts \cs{end} (four character tokens)
% ^^A %    and \cs{@nil} (one control sequence token) as a
% ^^A %    delimiter behind it, and
% ^^A %    then calls \cs{verbatim@@}.
% ^^A % \end{macro}
% ^^A %
% ^^A % \begin{macro}{\verbatim@@}
% ^^A %    \cs{verbatim@@} takes everything up to the next occurrence of
% ^^A %    the four characters \cs{end} as its argument.
% ^^A %    \begin{macrocode}
% ^^A     \def\verbatim@@#1!end{%
% ^^A %    \end{macrocode}
% ^^A %    That means: if they do not occur in the original line, then
% ^^A %    argument \verb?#1? is the
% ^^A %    whole input line, and \cs{@nil} is the next token
% ^^A %    to be processed.
% ^^A %    However, if the four characters \cs{end} are part of the
% ^^A %    original line, then
% ^^A %    \verb?#1? consists of the characters in front of \cs{end},
% ^^A %    and the next token is the following character (always remember
% ^^A %    that the line was lengthened by five tokens).
% ^^A %    Whatever \verb?#1? may be, it is verbatim text,
% ^^A %    so \verb?#1? is added to the line currently built.
% ^^A %    \begin{macrocode}
% ^^A        \verbatim@addtoline{#1}%
% ^^A %    \end{macrocode}
% ^^A %    The next token in the input stream
% ^^A %    is of special interest to us.
% ^^A %    Therefore \cs{futurelet} defines \cs{next} to be equal
% ^^A %    to it before calling \cs{verbatim@@@}.
% ^^A %    \begin{macrocode}
% ^^A        \futurelet\next\verbatim@@@}%
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A %
% ^^A % \begin{macro}{\verbatim@@@}
% ^^A %    \cs{verbatim@@@} will now read the rest of the tokens on
% ^^A %    the current line,
% ^^A %    up to the final \cs{@nil} token.
% ^^A %    \begin{macrocode}
% ^^A     \def\verbatim@@@#1\@nil{%
% ^^A %    \end{macrocode}
% ^^A %    If the first of the above two cases occurred, i.e.\ no
% ^^A %    \cs{end} characters were on that line, \verb?#1? is empty
% ^^A %    and \cs{next} is equal to \cs{@nil}.
% ^^A %    This is easily checked.
% ^^A %    \begin{macrocode}
% ^^A        \ifx\next\@nil
% ^^A %    \end{macrocode}
% ^^A %    If so, this was a simple line.
% ^^A %    We finish it by processing the line we accumulated so far.
% ^^A %    Then we prepare to read the next line.
% ^^A %    \begin{macrocode}
% ^^A          \verbatim@processline
% ^^A          \verbatim@startline
% ^^A          \let\next\verbatim@
% ^^A %    \end{macrocode}
% ^^A %    Otherwise we have to check what follows these \cs{end}
% ^^A %    tokens.
% ^^A %    \begin{macrocode}
% ^^A        \else
% ^^A %    \end{macrocode}
% ^^A %    Before we continue, it's a good idea to stop for a moment
% ^^A %    and remember where we are:
% ^^A %    We have just read the four character tokens \cs{end}
% ^^A %    and must now check whether the name of the environment (surrounded
% ^^A %    by braces) follows.
% ^^A %    To this end we define a macro called \cs{@tempa}
% ^^A %    that reads exactly one character and decides what to do next.
% ^^A %    This macro should do the following: skip spaces until
% ^^A %    it encounters either a left brace or the end of the line.
% ^^A %    But it is important to remember which characters are skipped.
% ^^A %    The \cs{end}\meta{optional spaces}\verb?{? characters
% ^^A %    may be part of the verbatim text, i.e.\ these characters
% ^^A %    must be printed.
% ^^A %
% ^^A %    Assume for example that the current line contains
% ^^A %    \begin{verbatim*}
% ^^A %      \end {AVeryLongEnvironmentName}
% ^^A %\end{verbatim*}
% ^^A %    As we shall soon see, the scanning mechanism implemented here
% ^^A %    will not find out that this is text to be printed until
% ^^A %    it has read the right brace.
% ^^A %    Therefore we need a way to accumulate the characters read
% ^^A %    so that we can reinsert them if necessary.
% ^^A %    The token register \cs{@temptokena} is used for this purpose.
% ^^A %
% ^^A %    Before we do this we have to get rid of the superfluous
% ^^A %    \cs{end} tokens at the end of the line.
% ^^A %    To this end we define a temporary macro whose argument
% ^^A %    is delimited by \verb?\end\@nil? (four character tokens
% ^^A %    and one control sequence token) to be used below
% ^^A %    on the rest of the line, after appending a \cs{@nil} token to it.
% ^^A %    (Note that this token can never appear in \verb?#1?.)
% ^^A %    We use the following definition of
% ^^A %    \cs{@tempa} to get the rest of the line (after the first
% ^^A %    \cs{end}).
% ^^A %    \begin{macrocode}
% ^^A          \def\@tempa##1!end\@nil{##1}%
% ^^A %    \end{macrocode}
% ^^A %    We mentioned already that we use token register
% ^^A %    \cs{@temptokena}
% ^^A %    to remember the characters we skip, in case we need them again.
% ^^A %    We initialize this with the \cs{end} we have thrown away
% ^^A %    in the call to \cs{@tempa}.
% ^^A %    \begin{macrocode}
% ^^A          \@temptokena{!end}%
% ^^A %    \end{macrocode}
% ^^A %    We shall now call \cs{verbatim@test}
% ^^A %    to process the characters
% ^^A %    remaining on the current line.
% ^^A %    But wait a moment: we cannot simply call this macro
% ^^A %    since we have already read the whole line.
% ^^A %    Therefore we have to first expand the macro \cs{@tempa} to insert
% ^^A %    them again after the \cs{verbatim@test} token.
% ^^A %    A \verb?^^M? character is appended to denote the end of the line.
% ^^A %    (Remember that this character comes disguised as a tilde.)
% ^^A %    \begin{macrocode}
% ^^A          \def\next{\expandafter\verbatim@test\@tempa#1\@nil~}%
% ^^A %    \end{macrocode}
% ^^A %    That's almost all, but we still have to
% ^^A %    now call \cs{next} to do the work.
% ^^A %    \begin{macrocode}
% ^^A        \fi \next}%
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A %
% ^^A %
% ^^A % \begin{macro}{\verbatim@test}
% ^^A %    We define \cs{verbatim@test} to investigate every token
% ^^A %    in turn.
% ^^A %    \begin{macrocode}
% ^^A     \def\verbatim@test#1{%
% ^^A %    \end{macrocode}
% ^^A %    First of all we set \cs{next} equal to \cs{verbatim@test}
% ^^A %    in case this macro must call itself recursively in order to
% ^^A %    skip spaces.
% ^^A %    \begin{macrocode}
% ^^A            \let\next\verbatim@test
% ^^A %    \end{macrocode}
% ^^A %    We have to distinguish four cases:
% ^^A %    \begin{enumerate}
% ^^A %      \item The next token is a \verb?^^M?, i.e.\ we reached
% ^^A %            the end of the line.  That means that nothing
% ^^A %            special was found.
% ^^A %            Note that we use \cs{if} for the following
% ^^A %            comparisons so that the category code of the
% ^^A %            characters is irrelevant.
% ^^A %    \begin{macrocode}
% ^^A            \if\noexpand#1\noexpand~%
% ^^A %    \end{macrocode}
% ^^A %            We add the characters accumulated in token register
% ^^A %            \cs{@temptokena} to the current line.  Since
% ^^A %            \cs{verbatim@addtoline} does not expand its argument,
% ^^A %            we have to do the expansion at this point.  Then we
% ^^A %            \cs{let} \cs{next} equal to \cs{verbatim@}
% ^^A %            to prepare to read the next line.
% ^^A %    \begin{macrocode}
% ^^A              \expandafter\verbatim@addtoline
% ^^A                \expandafter{\the\@temptokena}%
% ^^A              \verbatim@processline
% ^^A              \verbatim@startline
% ^^A              \let\next\verbatim@
% ^^A %    \end{macrocode}
% ^^A %      \item A space character follows.
% ^^A %            This is allowed, so we add it to \cs{@temptokena}
% ^^A %            and continue.
% ^^A %    \begin{macrocode}
% ^^A            \else \if\noexpand#1
% ^^A              \@temptokena\expandafter{\the\@temptokena#1}%
% ^^A %    \end{macrocode}
% ^^A %      \item An open brace follows.
% ^^A %            This is the most interesting case.
% ^^A %            We must now collect characters until we read the closing
% ^^A %            brace and check whether they form the environment name.
% ^^A %            This will be done by \cs{verbatim@testend}, so here
% ^^A %            we let \cs{next} equal this macro.
% ^^A %            Again we will process the rest of the line, character
% ^^A %            by character.
% ^^A %            The characters forming the name of the environment will
% ^^A %            be accumulated in \cs{@tempc}.
% ^^A %            We initialize this macro to expand to nothing.
% ^^A %    \begin{macrocode}
% ^^A            \else \if\noexpand#1\noexpand[%
% ^^A              \let\@tempc\@empty
% ^^A              \let\next\verbatim@testend
% ^^A %    \end{macrocode}
% ^^A %            Note that the \verb?[? character will be a \verb?{? when
% ^^A %            this macro is defined.
% ^^A %      \item Any other character means that the \cs{end} was part
% ^^A %            of the verbatim text.
% ^^A %            Add the characters to the current line and prepare to call
% ^^A %            \cs{verbatim@} to process the rest of the line.
% ^^A %    \begin{macrocode}
% ^^A            \else
% ^^A              \expandafter\verbatim@addtoline
% ^^A                \expandafter{\the\@temptokena}%
% ^^A              \def\next{\verbatim@#1}%
% ^^A            \fi\fi\fi
% ^^A %    \end{macrocode}
% ^^A %    \end{enumerate}
% ^^A %    The last thing this macro does is to call \cs{next}
% ^^A %    to continue processing.
% ^^A %    \begin{macrocode}
% ^^A            \next}%
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A %
% ^^A % \begin{macro}{\verbatim@testend}
% ^^A %    \cs{verbatim@testend} is called when
% ^^A %    \cs{end}\meta{optional spaces}\verb?{? was seen.
% ^^A %    Its task is to scan everything up to the next \verb?}?
% ^^A %    and to call \cs{verbatim@@testend}.
% ^^A %    If no \verb?}? is found it must reinsert the characters it read
% ^^A %    and return to \cs{verbatim@}.
% ^^A %    The following definition is similar to that of
% ^^A %    \cs{verbatim@test}:
% ^^A %    it takes the next character and decides what to do.
% ^^A %    \begin{macrocode}
% ^^A     \def\verbatim@testend#1{%
% ^^A %    \end{macrocode}
% ^^A %    Again, we have four cases:
% ^^A %    \begin{enumerate}
% ^^A %      \item \verb?^^M?: As no \verb?}? is found in the current line,
% ^^A %            add the characters to the buffer.  To avoid a
% ^^A %            complicated construction for expanding
% ^^A %            \cs{@temptokena}
% ^^A %            and \cs{@tempc} we do it in two steps.  Then we
% ^^A %            continue with \cs{verbatim@} to process the
% ^^A %            next line.
% ^^A %    \begin{macrocode}
% ^^A          \if\noexpand#1\noexpand~%
% ^^A            \expandafter\verbatim@addtoline
% ^^A              \expandafter{\the\@temptokena[}%
% ^^A            \expandafter\verbatim@addtoline
% ^^A              \expandafter{\@tempc}%
% ^^A            \verbatim@processline
% ^^A            \verbatim@startline
% ^^A            \let\next\verbatim@
% ^^A %    \end{macrocode}
% ^^A %      \item \verb?}?: Call \cs{verbatim@@testend} to check
% ^^A %            if this is the right environment name.
% ^^A %    \begin{macrocode}
% ^^A          \else\if\noexpand#1\noexpand]%
% ^^A            \let\next\verbatim@@testend
% ^^A %    \end{macrocode}
% ^^A %      \item \verb?\?: This character must not occur in the name of
% ^^A %            an environment.  Thus we stop collecting characters.
% ^^A %            In principle, the same argument would apply to other
% ^^A %            characters as well, e.g., \verb?{?.
% ^^A %            However, \verb?\? is a special case, since it may be
% ^^A %            the first character of \cs{end}.  This means that
% ^^A %            we have to look again for
% ^^A %            \cs{end}\marg{environment name}
% ^^A %            Note that we prefixed the \verb?!? by a \cs{noexpand}
% ^^A %            primitive, to protect ourselves against it being an
% ^^A %            active character.
% ^^A %    \begin{macrocode}
% ^^A          \else\if\noexpand#1\noexpand!%
% ^^A            \expandafter\verbatim@addtoline
% ^^A              \expandafter{\the\@temptokena[}%
% ^^A            \expandafter\verbatim@addtoline
% ^^A              \expandafter{\@tempc}%
% ^^A            \def\next{\verbatim@!}%
% ^^A %    \end{macrocode}
% ^^A %      \item Any other character: collect it and continue.
% ^^A %            We cannot use \cs{edef} to define \cs{@tempc}
% ^^A %            since its replacement text might contain active
% ^^A %            character tokens.
% ^^A %    \begin{macrocode}
% ^^A          \else \expandafter\def\expandafter\@tempc\expandafter
% ^^A            {\@tempc#1}\fi\fi\fi
% ^^A %    \end{macrocode}
% ^^A %    \end{enumerate}
% ^^A %    As before, the macro ends by calling itself, to
% ^^A %    process the next character if appropriate.
% ^^A %    \begin{macrocode}
% ^^A          \next}%
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A %
% ^^A % \begin{macro}{\verbatim@@testend}
% ^^A %    Unlike the previous macros \cs{verbatim@@testend} is simple:
% ^^A %    it has only to check if the \cs{end}\marg{...}
% ^^A %    matches the corresponding \cs{begin}\marg{...}
% ^^A %    \begin{macrocode}
% ^^A     \def\verbatim@@testend{%
% ^^A %    \end{macrocode}
% ^^A %    We use \cs{next} again to define the things that are
% ^^A %    to be done.
% ^^A %    Remember that the name of the current environment is
% ^^A %    held in \cs{@currenvir}, the characters accumulated
% ^^A %    by \cs{verbatim@testend} are in \cs{@tempc}.
% ^^A %    So we simply compare these and prepare to execute
% ^^A %    \cs{end}\marg{current environment}
% ^^A %    macro if they match.
% ^^A %    Before we do this we call \cs{verbatim@finish} to process
% ^^A %    the last line.
% ^^A %    We define \cs{next} via \cs{edef} so that
% ^^A %    \cs{@currenvir} is replaced by its expansion.
% ^^A %    Therefore we need \cs{noexpand} to inhibit the expansion
% ^^A %    of \cs{end} at this point.
% ^^A %    \begin{macrocode}
% ^^A        \ifx\@tempc\@currenvir
% ^^A          \verbatim@finish
% ^^A          \edef\next{\noexpand\end{\@currenvir}%
% ^^A %    \end{macrocode}
% ^^A %    Without this trick the \cs{end} command would not be able
% ^^A %    to correctly check whether its argument matches the name of
% ^^A %    the current environment and you'd get an
% ^^A %    interesting \LaTeX{} error message such as:
% ^^A %    \begin{verbatim}
% ^^A %! \begin{verbatim*} ended by \end{verbatim*}.
% ^^A %\end{verbatim}
% ^^A %    But what do we do with the rest of the characters, those
% ^^A %    that remain on that line?
% ^^A %    We call \cs{verbatim@rescan} to take care of that.
% ^^A %    Its first argument is the name of the environment just
% ^^A %    ended, in case we need it again.
% ^^A %    \cs{verbatim@rescan} takes the list of characters to be
% ^^A %    reprocessed as its second argument.
% ^^A %    (This token list was inserted after the current macro
% ^^A %    by \cs{verbatim@@@}.)
% ^^A %    Since we are still in an \cs{edef} we protect it
% ^^A %    by means of\cs{noexpand}.
% ^^A %    \begin{macrocode}
% ^^A                     \noexpand\verbatim@rescan{\@currenvir}}%
% ^^A %    \end{macrocode}
% ^^A %    If the names do not match, we reinsert everything read up
% ^^A %    to now and prepare to call \cs{verbatim@} to process
% ^^A %    the rest of the line.
% ^^A %    \begin{macrocode}
% ^^A        \else
% ^^A          \expandafter\verbatim@addtoline
% ^^A            \expandafter{\the\@temptokena[}%
% ^^A            \expandafter\verbatim@addtoline
% ^^A              \expandafter{\@tempc]}%
% ^^A          \let\next\verbatim@
% ^^A        \fi
% ^^A %    \end{macrocode}
% ^^A %    Finally we call \cs{next}.
% ^^A %    \begin{macrocode}
% ^^A        \next}%
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A %
% ^^A % \begin{macro}{\verbatim@rescan}
% ^^A %    In principle \cs{verbatim@rescan} could be used to
% ^^A %    analyse the characters remaining after the \verb?\end{...}?
% ^^A %    command and pretend that these were read
% ^^A %    ``properly'', assuming ``standard'' category codes are in
% ^^A %    force.\footnote{Remember that they were all read with
% ^^A %          category codes $11$ (letter) and $12$ (other) so
% ^^A %          that control sequences are not recognized as such.}
% ^^A %    But this is not always possible (when there are unmatched
% ^^A %    curly braces in the rest of the line).
% ^^A %    Besides, we think that this is not worth the effort:
% ^^A %    After a \texttt{verbatim} or \texttt{verbatim*} environment
% ^^A %    a new line in the output is begun anyway,
% ^^A %    and an \verb?\end{comment}? can easily be put on a line by itself.
% ^^A %    So there is no reason why there should be any text here.
% ^^A %    For the benefit of the user who did put something there
% ^^A %    (a comment, perhaps)
% ^^A %    we simply issue a warning and drop them.
% ^^A %    The method of testing is explained in Appendix~D, p.\ 376 of
% ^^A %    the \TeX{}book. We use \verb?^^M? instead of the \verb?!?
% ^^A %    character used there
% ^^A %    since this is a character that cannot appear in \verb?#1?.
% ^^A %    The two \cs{noexpand} primitives are necessary to avoid
% ^^A %    expansion of active characters and macros.
% ^^A %
% ^^A %    One extra subtlety should be noted here: remember that
% ^^A %    the token list we are currently building will first be
% ^^A %    processed by the \cs{lowercase} primitive before \TeX{}
% ^^A %    carries out the definitions.
% ^^A %    This means that the `\texttt{C}' character in the
% ^^A %    argument to the \cs{@warning} macro must be protected against
% ^^A %    being changed to `\texttt{c}'.  That's the reason why we added the
% ^^A %    \verb?\lccode`\C=`\C? assignment above.
% ^^A %    We can now finish the argument to \cs{lowercase} as well as the
% ^^A %    group in which the category codes were changed.
% ^^A %    \begin{macrocode}
% ^^A     \def\verbatim@rescan#1#2~{\if\noexpand~\noexpand#2~\else
% ^^A         \@warning{Characters dropped after `\string\end{#1}'}\fi}}
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A %
% ^^A % \subsubsection{The \cs{verbatiminput} command}
% ^^A %
% ^^A % \begin{macro}{\verbatim@in@stream}
% ^^A %    We begin by allocating an input stream (out of the 16 available
% ^^A %    input streams).
% ^^A %    \begin{macrocode}
% ^^A \newread\verbatim@in@stream
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A %
% ^^A % \begin{macro}{\verbatim@readfile}
% ^^A %    The macro \cs{verbatim@readfile} encloses the main loop by calls to
% ^^A %    the macros \cs{verbatim@startline} and \cs{verbatim@finish},
% ^^A %    respectively.  This makes sure
% ^^A %    that the user can initialize and finish the command when the file
% ^^A %    is empty or doesn't exist.  The \texttt{verbatim} environment has a
% ^^A %    similar behaviour when called with an empty text.
% ^^A %    \begin{macrocode}
% ^^A \def\verbatim@readfile#1{%
% ^^A   \verbatim@startline
% ^^A %    \end{macrocode}
% ^^A %    When the file is not found we issue a warning.
% ^^A %    \begin{macrocode}
% ^^A   \openin\verbatim@in@stream #1\relax
% ^^A   \ifeof\verbatim@in@stream
% ^^A     \typeout{No file #1.}%
% ^^A   \else
% ^^A %    \end{macrocode}
% ^^A %    At this point we pass the name of the file to \cs{@addtofilelist}
% ^^A %    so that its appears appears in the output of a \cs{listfiles}
% ^^A %    command.
% ^^A %    In addition, we use \cs{ProvidesFile} to make a log entry in the
% ^^A %    transcript file and to distinguish files read in via
% ^^A %    \cs{verbatiminput} from others.
% ^^A %    \begin{macrocode}
% ^^A     \@addtofilelist{#1}%
% ^^A     \ProvidesFile{#1}[(verbatim)]%
% ^^A %    \end{macrocode}
% ^^A %    While reading from the file it is useful to switch off the
% ^^A %    recognition of the end-of-line character.  This saves us stripping
% ^^A %    off spaces from the contents of the line.
% ^^A %    \begin{macrocode}
% ^^A     \expandafter\endlinechar\expandafter\m@ne
% ^^A     \expandafter\verbatim@read@file
% ^^A     \expandafter\endlinechar\the\endlinechar\relax
% ^^A     \closein\verbatim@in@stream
% ^^A   \fi
% ^^A   \verbatim@finish
% ^^A }
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A %
% ^^A % \begin{macro}{\verbatim@read@file}
% ^^A %    All the work is done in \cs{verbatim@read@file}.  It reads the input
% ^^A %    file line by line and recursively calls itself until the end of
% ^^A %    the file.
% ^^A %    \begin{macrocode}
% ^^A \def\verbatim@read@file{%
% ^^A   \read\verbatim@in@stream to\next
% ^^A   \ifeof\verbatim@in@stream
% ^^A   \else
% ^^A %    \end{macrocode}
% ^^A %    For each line we call \cs{verbatim@addtoline} with the contents of
% ^^A %    the line. \hskip0pt plus 3cm\penalty0\hskip0pt plus -3cm
% ^^A %    \cs{verbatim@processline} is called next.
% ^^A %    \begin{macrocode}
% ^^A     \expandafter\verbatim@addtoline\expandafter{\next}%
% ^^A     \verbatim@processline
% ^^A %    \end{macrocode}
% ^^A %    After processing the line we call \cs{verbatim@startline} to
% ^^A %    initialize all before we read the next line.
% ^^A %    \begin{macrocode}
% ^^A     \verbatim@startline
% ^^A %    \end{macrocode}
% ^^A %    Without \cs{expandafter} each call of \cs{verbatim@read@file} uses
% ^^A %    space in \TeX's input stack.\footnote{A standard \TeX\ would
% ^^A %    report an overflow error if you try to read a file with more than
% ^^A %    ca.\ 200~lines.  The same error occurs if the first line of code
% ^^A %    in \S 390 of \textsl{``TeX: The Program''\/} is missing.}
% ^^A %    \begin{macrocode}
% ^^A     \expandafter\verbatim@read@file
% ^^A   \fi
% ^^A }
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A %
% ^^A %
% ^^A % \begin{macro}{\verbatiminput}
% ^^A %    \cs{verbatiminput} first starts a group to keep font and category
% ^^A %    changes local.
% ^^A %    Then it calls the macro \cs{verbatim@input} with additional
% ^^A %    arguments, depending on whether an asterisk follows.
% ^^A %
% ^^A % PW. I added the TAB checking code.
% ^^A %    \begin{macrocode}
% ^^A \def\verbatiminput{\begingroup
% ^^A   \ift@bs
% ^^A     \def\verbatim@processline{\tabverbatim@processline}%
% ^^A   \fi
% ^^A   \@ifstar{\verbatim@input{\@maybeobeytabs}}%
% ^^A           {\verbatim@input{\frenchspacing\@vobeyspaces\@maybeobeytabs}}}
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A %
% ^^A % \begin{macro}{\verbatim@input}
% ^^A %    \cs{verbatim@input} first checks whether the file exists, using
% ^^A %    the standard macro cs{IfFileExists} which leaves the name of the
% ^^A %    file found in \cs{@filef@und}.
% ^^A %    Then everything is set up as in the \cs{verbatim} macro.
% ^^A %    \begin{macrocode}
% ^^A \def\verbatim@input#1#2{%
% ^^A    \IfFileExists {#2}{\@verbatim #1\relax
% ^^A %    \end{macrocode}
% ^^A %    Then it reads in the file, finishes off the \texttt{trivlist}
% ^^A %    environment started by \cs{@verbatim} and closes the group.
% ^^A %    This restores everything to its normal settings.
% ^^A %    \begin{macrocode}
% ^^A     \verbatim@readfile{\@filef@und}\endtrivlist\endgroup\@doendpe}%
% ^^A %    \end{macrocode}
% ^^A %   If the file is not found a more or less helpful message is
% ^^A %    printed. The final \cs{endgroup} is  needed to close the group
% ^^A %    started in \cs{verbatiminput} above.
% ^^A %    \begin{macrocode}
% ^^A    {\typeout {No file #2.}\endgroup}}
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A %
% ^^A % \textit{That completes my borrowings from \Lpack{verbatim}.}
% ^^A %
% ^^A 
% ^^A  % ^^A end embedded verbatim
% ^^A 
% ^^A % The next bunch of code implements wrapping verbatim lines so they, hopefully,
% ^^A % stay within the typeblock.
% ^^A %
% ^^A % \begin{macro}{\verbatimindent}
% ^^A % \begin{macro}{\verbatimbreakchar}
% ^^A % \begin{macro}{\setverbatimbreak}
% ^^A % The length \cs{verbatimindent} is the distance continuation lines are indented
% ^^A % from the left margin. \cs{verbatimbreakchar} is the character to indicate
% ^^A % a wrapped line.
% ^^A %    \begin{macrocode}
% ^^A \newlength{\verbatimindent}
% ^^A   \setlength{\verbatimindent}{3em}
% ^^A \newcommand*{\verbatimbreakchar}{\char`\%}
% ^^A \newcommand*{\setverbatimbreak}{%
% ^^A   \vspace*{-\baselineskip}%
% ^^A   \def\@xobeysp{~\discretionary{\verbatimbreakchar}%
% ^^A     {\kern\verbatimindent}{}}%
% ^^A }
% ^^A 
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A % \end{macro}
% ^^A % \end{macro}
% ^^A %
% ^^A % ^^A \begin{macro}{\wrappingon}
% ^^A % \begin{macro}{\wrapright}
% ^^A % \begin{macro}{\wrappingoff}
% ^^A % \cs{wrappingon} and \cs{wrappingoff} enable/prohibit wrapping. The
% ^^A % default is \cs{wrappingoff}.
% ^^A %
% ^^A % The macro
% ^^A % \cs{wrapright}  is used to set paragraph skips; without raggedright the 
% ^^A % lines
% ^^A % may break at the first space \emph{outside} the text area. However,
% ^^A % Paul found that wrapped verbatims
% ^^A % in a list (e.g., \texttt{itemize}) were not indented although regular
% ^^A % verbatims were indented. \cs{raggedwrap} is a variation on \cs{raggedright}
% ^^A % (\cs{leftskip} is set to \cs{@totalleftmargin} instead of 0pt), and seems
% ^^A % to have fixed the problem with the original code which used 
% ^^A % \cs{raggedright}. 
% ^^A % \changes{v1.61803}{2008/01/30}{Added \cs{raggedwrap} (mempatch v4.4)}
% ^^A % \changes{v1.61803398}{2009/07/18}{Added bidi support to \cs{raggedwrap}}
% ^^A %    \begin{macrocode}
% ^^A  % \newcommand*{\raggedwrap}{%
% ^^A  %  \@rightskip\@flushglue
% ^^A  %  %%%  \rightskip\@rightskip
% ^^A  %  \memRTLrightskip\@rightskip
% ^^A  % %%%  \leftskip\@totalleftmargin
% ^^A  %  \memRTLleftskip\@totalleftmargin
% ^^A  %  \parindent\ragrparindent}
% ^^A \newcommand*{\wrappingon}{%
% ^^A   \def\@xobeysp{~\discretionary{\verbatimbreakchar}%
% ^^A     {\kern\verbatimindent}{}}%
% ^^A   \def\wrapright{\raggedwrap}}
% ^^A \newcommand*{\wrappingoff}{%
% ^^A   \def\@xobeysp{\leavevmode\penalty\@M\ }%
% ^^A   \def\wrapright{}}
% ^^A \wrappingoff
% ^^A 
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A % \end{macro}
% ^^A % \end{macro}
% ^^A % ^^A \end{macro}
% ^^A %
% ^^A % \noindent{\color{red}\rule\textwidth{5mm}}
% 
% \subsection{Writing and boxing verbatim}
%
%    This bunch of code is from the \Lpack{moreverb} package.
%
% \begin{environment}{verbatimoutput}
% \verb?\begin{verbatimoutput}?\marg{filename} writes all text in its body to a
% file, the name of which it is given as an argument. (The code was
% written by Rainer Sch\"opf but the environment was called 
% \verb?verbatimwrite?). In the code below, uncommenting \\
% \verb?\catcode`\^^I=12? \\
% will result in TABs being written as \verb?^^I?.
% \changes{v1.3}{2002/09/27}{Changed name verbatimwrite to 
%               verbatimoutput (but neither were mentioned in the manual)}
%    \begin{macrocode}
\newwrite \verbatim@out
\def\verbatimoutput#1{%
  \@bsphack
  \immediate\openout \verbatim@out #1
  \let\do\@makeother\dospecials
  \catcode`\^^M\active %% \catcode`\^^I=12  
  \def\verbatim@processline{%
    \immediate\write\verbatim@out
      {\the\verbatim@line}}%
  \verbatim@start}
%    \end{macrocode}
%    \begin{macrocode}
\def\endverbatimoutput{%
  \immediate\closeout\verbatim@out
  \@esphack}
%    \end{macrocode}
% \end{environment}
%
%
%
% \begin{environment}{fboxverbatim}
% \texttt{fboxverbatim} puts the contents of a verbatim environment
% in a framing box. (PW: This was originally called \texttt{boxedverbatim}).
%
% (Written by Victor Eijkhout.)
%
% Bug fix (supplied by David Carlisle) 1995/12/28, marked
% \verb+%%%DPC%%%+
%
% First, redefine `processline' to produce only a line as wide
% as the natural width of the line
%
%    \begin{macrocode}
\def\fboxverbatim{\begingroup%
  \tabsoff %% PW otherwise box fills the width
  \def\verbatim@processline{%
    {\setbox0=\hbox{\the\verbatim@line}%
    \hsize=\wd0 \the\verbatim@line\par}}%
%    \end{macrocode}
%
% Now save the verbatim code in a box
%
%    \begin{macrocode}
  \@minipagetrue%%%DPC%%%
  \@tempswatrue%%%DPC%%%
  \setbox0=\vbox\bgroup \verbatim
}
%    \end{macrocode}
%
% At the end of the environment, we (umm) simply have to stick the
% results into a frame.
%
%    \begin{macrocode}
\def\endfboxverbatim{%
  \endverbatim
  \unskip\setbox0=\lastbox %%%DPC%%%
%    \end{macrocode}
%
% Now everything's in the box, so we can close it\dots
%
%    \begin{macrocode}
  \egroup
%    \end{macrocode}
%
% To change the code for centering, the next line needs a spot of
% hacking.
%
%    \begin{macrocode}
  \fbox{\box0}% <<<=== change here for centering,...
\endgroup}
%    \end{macrocode}

% \end{environment}
%
%
%
% \subsection{The shortvrb package}
%
% 
% \changes{v3.8.2}{2024/01/10}{Replaced embedded copy if
% \Lpack{shortvrb} with loading the package. The embedded code is just
% outcommented for now.}
%
% In earlier versions of the class we had an embedded copy of the code
% from the \Lpack{shortvrb} package, as the functionality is very
% useful.
%
% As of 2024 we load the package instead. This also gives us access to
% the starred version of \verb!\MakeShortVerb!. For details see
% \cite{SHORTVRB}.
%
% It adds the following macros
% \begin{verbatim}
% \MakeShortVerb
% \MakeShortVerb*
% \DeleteShortVerb
% \end{verbatim}
%    \begin{macrocode}
 % load shortvrb instead of embedding it
\RequirePackage{shortvrb}

%    \end{macrocode}
% 
% ^^A % The following is the \Lpack{shortvrb} package code (from \texttt{doc.dtx}
% ^^A % by Frank Mittelbach). It has been so useful to me that I wanted
% ^^A % to include it in the class.
% ^^A %
% ^^A % CODE AND COMMENTARY IS BY FRANK MITTELBACH
% ^^A  % start shortvrb code
% ^^A %
% ^^A % \begin{macro}{\MakeShortVerb}
% ^^A %    \begin{macrocode}
% ^^A \def\MakeShortVerb#1{%
% ^^A   \expandafter\ifx\csname cc\string#1\endcsname\relax
% ^^A %    \end{macrocode}
% ^^A %    \begin{macrocode}
% ^^A     \@shortvrbinfo{Made }{#1}%
% ^^A     \add@special{#1}%
% ^^A %    \end{macrocode}
% ^^A % Then the character's current catcode is stored in \verb?\cc\?\meta{c}.
% ^^A %    \begin{macrocode}
% ^^A     \expandafter
% ^^A     \xdef\csname cc\string#1\endcsname{\the\catcode`#1}%
% ^^A %    \end{macrocode}
% ^^A % The character is spliced into the definition using the same trick as
% ^^A % used in \cs{verb} (for instance), having activated \verb?~? in a group.
% ^^A %    \begin{macrocode}
% ^^A     \begingroup
% ^^A       \catcode`\~\active  \lccode`\~`#1%
% ^^A       \lowercase{%
% ^^A %    \end{macrocode}
% ^^A % The character's old meaning is recorded in \verb?\ac\?\meta{c} prior to
% ^^A % assigning it a new one.
% ^^A %    \begin{macrocode}
% ^^A       \global\expandafter\let
% ^^A          \csname ac\string#1\endcsname~%
% ^^A       \gdef~{\verb~}}%
% ^^A     \endgroup
% ^^A %    \end{macrocode}
% ^^A % Finally the character is made active.
% ^^A %    \begin{macrocode}
% ^^A     \global\catcode`#1\active
% ^^A %    \end{macrocode}
% ^^A % If we suspect that \meta{c} is already a short reference, we tell
% ^^A % the user. Now he or she is responsible if anything goes wrong\,\dots
% ^^A %    \begin{macrocode}
% ^^A   \else
% ^^A %    \end{macrocode}
% ^^A %    \begin{macrocode}
% ^^A     \@shortvrbinfo\@empty{#1 already}%
% ^^A   \fi}
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A % \begin{macro}{\DeleteShortVerb}
% ^^A % Here's the means of undoing a \cs{MakeShortVerb}, for instance in a
% ^^A % region where you need to use the character outside a verbatim
% ^^A % environment.  It arranges for \cs{dospecials} and \cs{@sanitize} to be
% ^^A % altered appropriately, restores the saved catcode and, if necessary,
% ^^A % the character's meaning (as stored by 
% ^^A % \cs{MakeShortVerb}).  If the catcode wasn't stored in
% ^^A % \verb?\cc\?\meta{c} (by \cs{MakeShortVerb}) the command is silently
% ^^A % ignored. 
% ^^A %    \begin{macrocode}
% ^^A \def\DeleteShortVerb#1{%
% ^^A   \expandafter\ifx\csname cc\string#1\endcsname\relax
% ^^A   \else
% ^^A %    \end{macrocode}
% ^^A %    \begin{macrocode}
% ^^A     \@shortvrbinfo{Deleted }{#1 as}%
% ^^A     \rem@special{#1}%
% ^^A     \global\catcode`#1\csname cc\string#1\endcsname
% ^^A %    \end{macrocode}
% ^^A % We must not forget to reset \verb?\cc\?\meta{c}, otherwise the check in
% ^^A % \cs{MakeShortVerb} for a repeated definition will not work.
% ^^A %    \begin{macrocode}
% ^^A     \global \expandafter\let \csname cc\string#1\endcsname \relax
% ^^A     \ifnum\catcode`#1=\active
% ^^A       \begingroup
% ^^A         \catcode`\~\active   \lccode`\~`#1%
% ^^A         \lowercase{%
% ^^A           \global\expandafter\let\expandafter~%
% ^^A           \csname ac\string#1\endcsname}%
% ^^A       \endgroup \fi \fi}
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A %
% ^^A %  \begin{macro}{\@shortvrbinfo}
% ^^A % Helper function for info messages.
% ^^A %    \begin{macrocode}
% ^^A \def\@shortvrbinfo#1#2{%
% ^^A   \ClassInfo{memoir}{%
% ^^A      #1\expandafter\@gobble\string#2 a short reference
% ^^A                                           for \string\verb}}
% ^^A %    \end{macrocode}
% ^^A %  \end{macro}
% ^^A %
% ^^A % \begin{macro}{\add@special}
% ^^A % This helper macro adds its argument to the
% ^^A % \cs{dospecials} macro which is conventionally used by verbatim macros
% ^^A % to alter the catcodes of the currently active characters.  We need
% ^^A % to add \verb?\do\?\meta{c} to the expansion of \cs{dospecials} after
% ^^A % removing the character if it was already there to avoid multiple
% ^^A % copies building up should \cs{MakeShortVerb} not be balanced by
% ^^A % \cs{DeleteShortVerb} (in case anything that uses \cs{dospecials} cares
% ^^A % about repetitions).
% ^^A %    \begin{macrocode}
% ^^A \def\add@special#1{%
% ^^A   \rem@special{#1}%
% ^^A   \expandafter\gdef\expandafter\dospecials\expandafter
% ^^A     {\dospecials \do #1}%
% ^^A %    \end{macrocode}
% ^^A % Similarly we have to add \verb?\@makeother\?\meta{c} to \cs{@sanitize}
% ^^A % (which is used in things like \cs{index} to re-catcode all special
% ^^A % characters except braces).
% ^^A %    \begin{macrocode}
% ^^A   \expandafter\gdef\expandafter\@sanitize\expandafter
% ^^A     {\@sanitize \@makeother #1}}
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A % \begin{macro}{\rem@special}
% ^^A % The inverse of cs{add@special} is slightly trickier.  \cs{do} is
% ^^A % re-defined to expand to nothing if its argument is the character of
% ^^A % interest, otherwise to expand simply to the argument.  We can then
% ^^A % re-define \cs{dospecials} to be the expansion of itself.  The space
% ^^A % after \verb?=`##1? prevents an expansion to \cs{relax}!
% ^^A %    \begin{macrocode}
% ^^A \def\rem@special#1{%
% ^^A   \def\do##1{%
% ^^A     \ifnum`#1=`##1 \else \noexpand\do\noexpand##1\fi}%
% ^^A   \xdef\dospecials{\dospecials}%
% ^^A %    \end{macrocode}
% ^^A % Fixing \cs{@sanitize} is the same except that we need to re-define
% ^^A % \cs{@makeother} which obviously needs to be done in a group. 
% ^^A %    \begin{macrocode}
% ^^A   \begingroup
% ^^A     \def\@makeother##1{%
% ^^A       \ifnum`#1=`##1 \else \noexpand\@makeother\noexpand##1\fi}%
% ^^A     \xdef\@sanitize{\@sanitize}%
% ^^A   \endgroup}
% ^^A %    \end{macrocode}
% ^^A % \end{macro}
% ^^A %
% ^^A  % end shortvrb code
% ^^A % END OF MITTELBACH CODE AND COMMENTARY.
% 
% \subsection{General verbatim boxing and line numbering}
%
%    A while ago I wrote a package that I never released. Here it is
% now, updated and improved. The package was based on code originally
% posted to \ctt{}  by Donald Arseneau on 13 July 2000.
%
% This is DA's posted code.
% \begin{verbatim}
% \RequirePackage{verbatim}
% \def\boxverbflag{14 }
%
% \def\boxedverbatim{%
%    \fboxsep=1em
%    \def\verbatim@processline{\leavevmode
%      \vrule\vbox{\advance\hsize-.8p@ \@@line
%        {\strut\kern\fboxsep\the\verbatim@line\hss}%
%         \kern\fbozsep}\vrule\par}%
%    \@verbatim % but make some replacement settings
% %   \ifdim\@totalleftmargin>\fboxsep \fboxsep\@totalleftmargin \fi
%    \leftskip\x@skip \rightskip\z@skip
%    \interlinepenalty\boxverbflag
%    \parfillskip\z@ plus\p@ minus\p@
%    \lineskip-\fboxsep \baselineskip\z@skip
%    \frenchspacing\@vobeyspaces
%    \boxverb@toprule
%    \verbatim@start}
%
% \def\endboxedverbatim{\hrule\endtrivlist}
%
% \@namefdef{boxedverbatim*}{\let\frenchspacing\@gobble \boxedverbatim}
% \@namefdef{endboxedverbatim*}{\hrule\endtrivlist}
%
% \output=\expandafter{\expandafter\boxverb@split \the\output}
%
% \def\boxverb@toprule{\hrule \nobreak \vskip-.1\p@
%    \@@line{\vrule height2\fboxsep \hss \vrule}}
%
% \def\boxverb@split{\ifnum\outputpenalty=\boxverbflag
%    \ifdim\dp\@cclv=\z@
%    \setbox\@cclv\vbox{\unvbox\@cclv\hrule\kern-.4pt}%
%    \null \kern-.7\topskip \boxverb@toprule
%    \fi\fi}
% \end{verbatim}
% That's the end of DA's posted code
%
% I have extended this to provide:
% \begin{itemize}
%  \item A (multipage) boxed verbatim
%  \item A (multipage) boxed verbatim input
%  \item Normally each `page' is boxed, but start/end rules can be switched off
%    at page boundaries
%  \item A heading can be put at the start of `continuation' pages
%  \item Lines of verbatim text can be numbered
%  \item Can be `downgraded' to normal verbatim environment
%  \end{itemize}
%
%    OK, on to the main code.
%
% \begin{macro}{\boxverbflag}
% \begin{macro}{\bvboxsep}
%    \begin{macrocode}
\def\boxverbflag{14 }
\newlength{\bvboxsep}      % user can change this
\setlength{\bvboxsep}{1em}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%    \begin{macrocode}
\newif\ifbvperpage % start/end lines on every page of multipage verbatim
\bvperpagetrue

%    \end{macrocode}
%
% \begin{macro}{\bvtopofpage}
% \begin{macro}{\b@vtop}
% Can use \cs{bvtopofpage} to put a heading above continued verbatims.
% For example \\
% \verb?\bvtopofpage{\begin{center}\normalfont (Continued)\end{center}}? \\
% It only works for \cs{bvperpagetrue}.
%    \begin{macrocode}
\newcommand{\bvtopofpage}[1]{%
  \long\def\b@vtop{#1}}
\def\b@vtop{}  % used in \boxverb@split for heading 

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\c@memfbvline}
% \begin{macro}{\c@bvlinectr}
% Counter for adjusting the starting line number for boxed verbatims
% and for the line number itself..
%    \begin{macrocode}
\newcounter{memfbvline}
  \c@memfbvline=\z@
\newcounter{bvlinectr}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\setbvlinenums}
% \cs{setbvlinenums}\marg{firstline}\marg{startnumsat} sets the first line
% number to \meta{firstline} and the first line number to be printed is
% \meta{startnumsat}. 
% \changes{v1.61803}{2008/01/30}{Added \cs{setbvlinenums} (mempatch v4.9)}
%    \begin{macrocode}
\newcommand*{\setbvlinenums}[2]{%
  \c@bvlinectr #1\relax \advance\c@bvlinectr \m@ne
  \ifnum\z@<\linemodnum%   we are printing line numbers
    \@tempcnta #2\relax
    \divide\@tempcnta\linemodnum
    \multiply\@tempcnta\linemodnum
    \c@memfbvline #2\relax
    \advance\c@memfbvline-\@tempcnta
  \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\theb@vlinenumber}
% \begin{macro}{\resetbvlinenumber}
% \cs{resetbvlinenumber} reinitializes the line numbering.
% \changes{v1.61803}{2008/01/30}{Changed \cs{theb@vlinenumber} (mempatch v4.9)}
%    \begin{macrocode}
\def\theb@vlinenumber{\getthelinenumber{bvlinectr}{memfbvline}}
\newcommand*{\resetbvlinenumber}{\setcounter{bvlinectr}{0}}
 
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\b@vdocount}
% \begin{macro}{\bvnumlength}
% Increment line number if counting. A line number is printed in
% a space width \cs{bvnumlength}, which is given a temporary value here.
%    \begin{macrocode}
\def\b@vdocount{\ifbvcountlines\stepcounter{bvlinectr}\fi}
\newlength{\bvnumlength}       
%% \settowidth{\bvnumlength}{\vlvnumfont 9999}
\settowidth{\bvnumlength}{\normalfont 999}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\ifbvcountinside}
% \begin{macro}{\bvnumbersinside}
% \begin{macro}{\bvnumbersoutside}
% Flag and commands for positioning the numbers. Default is to print
% them inside the box.
%    \begin{macrocode}
\newif\ifbvcountinside  % TRUE if line numbers inside box
  \bvcountinsidetrue
\newcommand*{\bvnumbersinside}{\bvcountinsidetrue}
\newcommand*{\bvnumbersoutside}{\bvcountinsidefalse}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\b@vdoinside}
% \begin{macro}{\b@vdooutside}
% Print numbers inside (outside) the box.
%    \begin{macrocode}
\def\b@vdoinside{%
  \ifbvcountlines\ifbvcountinside%
    \makebox[\bvnumlength][r]{%
      \vlvnumfont \theb@vlinenumber\space}%
  \fi\fi}

\def\b@vdooutside{%
  \ifbvcountlines\ifbvcountinside\else%
    \llap{\makebox[\bvnumlength][r]{%
      \vlvnumfont \theb@vlinenumber\space}}%
  \fi\fi}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@@m@mline}
% \cs{@@line} is defined as \verb?\def\@@line{\hb@xt@\hsize}? and I need
% an equivalent for \cs{linewidth} instead of \cs{hsize} for use in
% \cs{setupboxverb@line}.
% \changes{v1.61803}{2008/01/30}{Added \cs{@@m@mline} (mempatch v4.9)}
%    \begin{macrocode}
\newcommand*{\@@m@mline}{\hb@xt@\linewidth}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\setupboxverb@line}
% Use a macro for the first main part of DA's code for \cs{boxedverbatim}, 
% adding lots of hooks.
%
% Per Starb\"{a}ck had problems with the combination of \texttt{adjustwidth} 
% with \texttt{boxedverbatim} (see CTT \textit{Re: [memoir] adjustwidth + 
% boxedverbatim}, 2007/02/10) and Lars Madsen came up with a suggestion to
% use \cs{linewidth} instead of \cs{hsize}.
% \changes{v1.61803}{2008/01/30}{Changed \cs{hsize} to \cs{linewidth} in
%         \cs{setupboxverb@line} (mempatch v4.9)}
%    \begin{macrocode}
\newcommand{\setupboxverb@line}{%
  \par
  \ifbvperpage
    \output=\expandafter{\expandafter\boxverb@split \the\output}
  \fi
%    \end{macrocode}
% \begin{macro}{\verbatim@processline}
% \changes{v3.8.2}{2024/01/25}{Removed tab support}
%    \begin{macrocode}
  \def\verbatim@processline{\leavevmode
    \b@vdocount%
    \bvleftsidehook\vbox{\advance% \hsize-.8\p@ \@@line % changed to \linewidth
                                 \linewidth-.8\p@ \@@line
      {\b@vdooutside\strut\kern\bvboxsep%
       \b@vdoinside%
       %\ift@bs
       %  \tabverbatim@processline
       %\else
         \the\verbatim@line
       %\fi
       \hss}%
     \kern\bvboxsep}\bvrightsidehook\par}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\setupbox@verb}
% Use a macro for the second main part of DA's code, and integrate it
% with the other verbatim codes.
% 
% \changes{v3.8.2}{2024/01/25}{Removed \cs{@maybeobeytags}}
%    \begin{macrocode}
\newcommand{\setupbox@verb}{%
  \leftskip\z@skip \rightskip\z@skip
  \interlinepenalty\boxverbflag
  \parfillskip\z@ plus\p@ minus\p@
  \lineskip-\bvboxsep \baselineskip\z@skip
  \frenchspacing\@vobeyspaces%\@maybeobeytabs
  \boxverb@toprule}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\boxedverbatim}
% \begin{macro}{\endboxedverbatim}
% \begin{macro}{\boxedverbatim*}
% \begin{macro}{\endboxedverbatim*}
% Given the two macros above, we can write a briefer version of DA's 
% \cs{boxedverbatim(*)}. 
% As noted by Zarko Cucej, have to handle
% a following (no-) paragraph.
% \changes{v1.4}{2003/11/22}{Added \cs{@doendpe} to \cs{endboxedverbatim}
%                            (from patch v1.8)}
%    \begin{macrocode}
\def\boxedverbatim{\begingroup
  \let\@@line\@@m@mline%    new from mempatch v4.9
  \setupboxverb@line
  \@verbatim
  \setupbox@verb
  \verbatim@start}
\def\endboxedverbatim{\bvendrulehook\endtrivlist\endgroup\@doendpe}
\@namedef{boxedverbatim*}{\let\frenchspacing\@gobble \boxedverbatim}
\@namelet{endboxedverbatim*}\endboxverbatim

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%    \begin{macrocode}
\def\boxverb@toprule{\bvtoprulehook
  \@@line{\bvleftsidehook \bvtopmidhook \bvrightsidehook}}

%    \end{macrocode}
%
% \begin{macro}{\bvendofpage}
% \cs{bvendofpage}\marg{spec} sets the boxed verbatim `end of page' to \meta{spec}.
% \changes{v1.618}{2005/09/02}{Added \cs{bvendofpage} (mempatch v2.3d)}
% \changes{v1.61803}{2008/01/30}{Changed \cs{bvendofpage} to include width}
%    \begin{macrocode}
\newcommand*{\bvendofpage}[1]{%
  \def\boxverb@botpage{#1}}
%%%%\bvendofpage{\hrule\kern-.4pt}
\bvendofpage{\hrule width\linewidth\kern-.4pt}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\boxverb@split}
%    \begin{macrocode}
\def\boxverb@split{\ifnum\outputpenalty=\boxverbflag
  \ifdim\dp\@cclv=\z@
%%%%    \setbox\@cclv\vbox{\unvbox\@cclv\hrule\kern-.4pt}%
    \setbox\@cclv\vbox{\unvbox\@cclv\boxverb@botpage}%
    \null \kern-.7\topskip \b@vtop \boxverb@toprule
  \fi
\fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\bvtoprulehook}
% \begin{macro}{\bvendrulehook}
% \begin{macro}{\bvleftsidehook}
% \begin{macro}{\bvrightsidehook}
% \begin{macro}{\bvtopmidhook}
% The new hooks, for the top, bottom, left and right of the box.
% \changes{v1.61803}{2008/01/30}{Added \cs{linewidth} to \cs{bvtoprulehook} and
%                 \cs{bvendrulehook} (mempatch v4.9)}
%    \begin{macrocode}
\def\bvtoprulehook{\hrule width\linewidth \nobreak\vskip-.1\p@}
\def\bvendrulehook{\hrule width\linewidth}
\def\bvleftsidehook{\vrule}
\def\bvrightsidehook{\vrule}
\def\bvtopmidhook{\rule{0\p@}{2\bvboxsep} \hss}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\boxedverbatiminput}
% \begin{macro}{\boxedverbatim@input}
% \cs{boxedverbatiminput}\marg{filename} read in filename contents as verbatim
%    \begin{macrocode}
\newcommand{\boxedverbatiminput}{\begingroup
  \@ifstar{\let\frenchspacing\@gobble 
           \boxedverbatim@input\relax}%
          {\boxedverbatim@input{\frenchspacing\@vobeyspaces}}}

%    \end{macrocode}
%
%    \begin{macrocode}
\def\boxedverbatim@input#1#2{%
  \setupboxverb@line
  \IfFileExists{#2}{\@verbatim #1\relax
  \setupbox@verb
    \verbatim@readfile{\@filef@und}%
      \bvendrulehook\endtrivlist\endgroup\@doendpe}%
  {\typeout {No file #2.}\endgroup}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% Some prepackaged boxing styles.
%
% \begin{macro}{\bvbox}
% Original (default) boxing.
%    \begin{macrocode}
\newcommand{\bvbox}{%
  \bvperpagetrue%
  \renewcommand{\bvtoprulehook}{\hrule \nobreak \vskip-.1\p@}%
  \renewcommand{\bvleftsidehook}{\vrule}%
  \renewcommand{\bvrightsidehook}{\vrule}%
  \renewcommand{\bvendrulehook}{\hrule}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\nobvbox}
% No boxing
%    \begin{macrocode}
\newcommand{\nobvbox}{%
  \bvperpagefalse%
  \renewcommand{\bvtoprulehook}{}%
  \renewcommand{\bvleftsidehook}{}%
  \renewcommand{\bvrightsidehook}{}%
  \renewcommand{\bvendrulehook}{}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\bvtopandtail}
% Head and foot horizontal lines only
%    \begin{macrocode}
\newcommand{\bvtopandtail}{%
  \bvperpagefalse%
  \renewcommand{\bvtoprulehook}{\hrule \nobreak \vskip-.1\p@}%
  \renewcommand{\bvleftsidehook}{}%
  \renewcommand{\bvrightsidehook}{}%
  \renewcommand{\bvendrulehook}{\hrule}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\bvsides}
% Side vertical lines only
%    \begin{macrocode}
\newcommand{\bvsides}{%
  \bvperpagefalse%
  \renewcommand{\bvtoprulehook}{\vskip 3ex}%
  \renewcommand{\bvleftsidehook}{\vrule}%
  \renewcommand{\bvrightsidehook}{\vrule}%
  \renewcommand{\bvendrulehook}{}}

%    \end{macrocode}
% \end{macro}
%
%
%
% \subsection{The framed package}
%
% The following code is the \Lpack{framed} package~\cite{FRAMED}
% by Donald Arseneau.
% \changes{v1.4}{2003/11/22}{Updated framed code to v0.8a of the package}
% \changes{v1.61803}{2008/01/30}{Updated framed code to v0.95 of the package}
%
% \begin{macro}{\framed}
% \begin{macro}{\endframed}
% \begin{macro}{\shaded}
% \begin{macro}{\endshaded}
%    \begin{macrocode}
\let\framed\relax \let\endframed\relax
\let\shaded\relax \let\endshaded\relax

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% Way back when DA sent me a pre-release copy of v0.6 of his \Lpack{framed} 
% package~\cite{FRAMED}.
% We also discussed good ways of embedding it into the class. One result
% being that I defined some some items \cs{AtBeginDocument}, but this is
% no longer required as DA has changed \Lpack{framed} to cooperate
% with memoir. We continue to have sporadic email conversations about the
% interaction of \Lpack{memoir} and \Lpack{framed}.
%
% Here is a modified version of \file{framed.sty}. In particular
% I moved some of DA's description of the code into the general commentary
% instead of comments within the code.
%
% \begin{verbatim}
% framed.sty   v 0.95    2007/10/04
% Copyright (C) 1992-2007 by Donald Arseneau  (asnd@triumf.ca)
% These macros may be freely transmitted, reproduced, or modified
% provided that this notice is left intact.
% 
%====================== Begin Instructions =======================
%
%                       framed.sty
%                       ~~~~~~~~~~
% Create framed, shaded, or differently highlighted regions that can 
% break across pages.  The environments defined are 
%   framed    -- ordinary frame box (\fbox) with edge at margin
%   shaded    -- shaded background (\colorbox) bleeding into margin
%   snugshade -- similar
%   leftbar   -- thick vertical line in left margin
% to be used like
% \begin{framed}
%  copious text
% \end{framed}
%
% But the more general purpose of this package is to facilitate the
% creation of environments that enable page breaking
% within arbitrary decorations using a simple new-environment definition
% incorporating \FrameCommand and
% \begin{MakeFramed}{settings} ... \end{MakeFramed}
%
% The "framed" environment uses "\fbox" as its "\FrameCommand" with 
% the additional settings \fboxrule=\FrameRule and \fboxsep=\FrameSep.
% You can change these lengths (using \setlength) and you can change 
% the definition of \FrameCommand to use much fancier boxes.
%
% In fact, the "shaded" environment just redefines \FrameCommand to be
% \colorbox{shadecolor} (and you have to define the color "shadecolor":
% \definecolor{shadecolor}...).
%
% A page break is allowed, and even encouraged, before the framed
% environment.  If you want to attach some text (a box title) to the
% frame, then the text should be inserted by \FrameCommand.
%
% The contents of the framed regions are restricted: 
% Floats, footnotes, marginpars and head-line entries will be lost.
% (Some of these may be handled in a later version.)
% This package will not work with the page breaking of multicol.sty,
% or other systems that perform column-balancing.
%
% The MakeFramed environment does the work.  Its "settings" argument
% should contain any adjustments to the text width (applied to \hsize,
% and using the "\width" of the frame itself) as well as a "restore" 
% command -- \@parboxrestore or \FrameRestore or something similar;
% as an example, the snugshade environment shows how to suppress excess
% spacing within the box, copying the code from minipage.
%
% Expert commands:
% \MakeFramed, \endMakeFramed: the "MakeFramed" environment
% \FrameCommand: command to draw the frame around its argument
% \FrameRestore: restore some text settings, but fewer than \@parboxrestore
% \FrameRule: length register; \fboxrule for default "framed".
% \FrameSep: length register; \fboxsep for default "framed".
% \FrameHeightAdjust: macro; height of frame above baseline at top of page
% 
% This is still a `pre-production' version because I can think of many
% features/improvements that should be made.  Nevertheless, starting 
% with version 0.5 it should be bug-free.
%
% ToDo: 
% Test more varieties of list 
% Improve and correct documentation
% Propagation of \marks
% Handle footnotes (how??) floats (?) and marginpars.
% Stretchability modification.
%======================== End Instructions ========================
%
% \ProvidesPackage{framed}[2007/10/04 v 0.95: 
%    framed or shaded text with page breaks]
%
% \newenvironment{framed}% using default \FrameCommand
%   {\MakeFramed {\advance\hsize-\width \FrameRestore}}%
%   {\endMakeFramed}
%
% \newenvironment{shaded}{%
%   \def\FrameCommand{\fboxsep=\FrameSep \colorbox{shadecolor}}%
%   \MakeFramed {\FrameRestore}}%
%   {\endMakeFramed}
%
% \newenvironment{leftbar}{%
%   \def\FrameCommand{\vrule width 3pt \hspace{10pt}}%
%   \MakeFramed {\advance\hsize-\width \FrameRestore}}%
%  {\endMakeFramed}
%
% \newenvironment{snugshade}{%
%   \def\FrameCommand{\colorbox{shadecolor}}%
%   \MakeFramed {\FrameRestore\@setminipage}}%
%  {\par\unskip\endMakeFramed}
% 
% \end{verbatim}
%
% Now for the package code.
%
%    \begin{macrocode}
\chardef\FrameRestore=\catcode`\| % for debug
\catcode`\|=\catcode`\% % (debug: insert space after backslash)

%    \end{macrocode}
%
% \begin{macro}{\MakeFramed}
%    \begin{macrocode}
\def\MakeFramed#1{\par
%    \end{macrocode}
% measure added width and height; call result \cs{width} and \cs{height}
%    \begin{macrocode}
 \fb@sizeofframe\FrameCommand
 \let\width\fb@frw \let\height\fb@frh
%    \end{macrocode}
% insert pre-penalties and skips
%    \begin{macrocode}
 \begingroup
 \skip@\lastskip
 \if@nobreak\else 
    \penalty9999 % updates \page parameters
    \ifdim\pagefilstretch=\z@ \ifdim\pagefillstretch=\z@
%    \end{macrocode}
% not infinitely stretchable, so encourage a page break here
%    \begin{macrocode}
       \edef\@tempa{\the\skip@}%
       \ifx\@tempa\zero@glue \penalty-30
       \else \vskip-\skip@ \penalty-30 \vskip\skip@
    \fi\fi\fi
    \penalty\z@
%    \end{macrocode}
% Give a stretchy breakpoint that will always be taken in preference
% to the \cs{penalty} 9999 used to update page parameters.  The cube root
% of 10000/100 indicates a multiplier of 0.21545, but the maximum 
% calculated badness is really 8192, not 10000, so the multiplier
% is 0.2301. 
%    \begin{macrocode}
    \advance\skip@ \z@ plus-.5\baselineskip
    \advance\skip@ \z@ plus-.231\height
    \advance\skip@ \z@ plus-.231\skip@
    \advance\skip@ \z@ plus-.231\topsep
    \vskip-\skip@ \penalty 1800 \vskip\skip@
 \fi
 \addvspace{\topsep}%
 \endgroup
%    \end{macrocode}
% clear out pending page break
%    \begin{macrocode}
 \penalty\@M \vskip 2\baselineskip \vskip\height
 \penalty9999 \vskip -2\baselineskip \vskip-\height
 \penalty9999 % updates \pagetotal
|\message{After clearout, \pagetotal=\the\pagetotal, 
|         \pagegoal=\the\pagegoal. }%
 \fb@adjheight 
 \setbox\@tempboxa\vbox\bgroup
   #1% Modifications to \hsize (can use \width and \height)
   \textwidth\hsize \columnwidth\hsize}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\endMakeFramed}
%    \begin{macrocode}
\def\endMakeFramed{\par
     \kern\z@
     \hrule\@width\hsize\@height\z@
     \penalty-100 % put depth into height
 \egroup
  % {\showoutput\showbox\@tempboxa}%
 \begingroup 
   \fb@put@frame\FrameCommand\FirstFrameCommand
 \endgroup}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\fb@put@frame}
% \cs{fb@put@frame}\marg{nosplit}\marg{split} 
% takes the contents of \cs{@tempboxa} and puts all, 
% or a piece,
% of it on the page with a frame (\cs{FrameCommand}, \cs{FirstFrameCommand},
% \cs{MidFrameCommand}, or \cs{LastFrameCommand}).  It recurses until all of 
% \cs{@tempboxa} has been used up. (\cs{@tempboxa} must have zero depth.) \\
% \meta{nosplit} = attempted framing command, if no split \\
% \meta{split} = framing command if split.
%
% First iteration: Try to fit with \cs{FrameCommand}. If it does not fit,
% split for \cs{FirstFrameCommand}.
%
% Later iteration: Try to fit with \cs{LastFrameCommand}. If it does not
% fit, split for \cs{MidFrameCommand}.
%    \begin{macrocode}
\def\fb@put@frame#1#2{\relax
 \ifdim\pagegoal=\maxdimen \pagegoal\vsize \fi
 \ifinner
   \fb@putboxa#1%
   \fb@afterframe
 \else
  \dimen@\pagegoal \advance\dimen@-\pagetotal % natural space left on page
  \ifdim\dimen@<2\baselineskip % Too little room on page
|   \message{Page has only \the\dimen@\space room left; eject. }%
    \eject \fb@adjheight \fb@put@frame#1#2%
  \else % there's appreciable room left on the page
     \fb@sizeofframe#1%
|    \message{\string\pagetotal=\the\pagetotal,
|        \string\pagegoal=\the\pagegoal,
|        \string\pagestretch=\the\pagestretch,
|        \string\pageshrink=\the\pageshrink,
|        \string\fb@frh=\fb@frh. \space}
|    \message{Box of size \the\ht\@tempboxa\space + \fb@frh}%
     \begingroup % temporarily set \dimen@ to be...
     \advance\dimen@.8\pageshrink  % maximum space available on page
     \advance\dimen@-\fb@frh\relax % space available for frame's contents
     \expandafter\endgroup
%    \end{macrocode}
% expand \cs{ifdim}, then restore \cs{dimen@} to real room left on page
%    \begin{macrocode}
     \ifdim\dimen@>\ht\@tempboxa % whole box does fit
|       \message{fits in \the\dimen@. }%
%    \end{macrocode}
% Use vsplit anyway to capture the marks \\
% !!!???!!! MERGE THIS WITH THE else CLAUSE!!!
%    \begin{macrocode}
        \fb@putboxa#1%
        \fb@afterframe
     \else % box must be split
|       \message{must be split to fit in \the\dimen@. }%
%    \end{macrocode}
% update frame measurement to use \cs{FirstFrameCommand} 
% or \cs{MidFrameCommand}
%    \begin{macrocode}
        \fb@sizeofframe#2%
        \setbox\@tempboxa\vbox{% simulate frame and flexiblity of the page:
           \vskip \fb@frh \@plus\pagestretch \@minus.8\pageshrink
           \kern137sp\kern-137sp\penalty-30
           \unvbox\@tempboxa}%
        \edef\fb@resto@set{\boxmaxdepth\the\boxmaxdepth 
                           \splittopskip\the\splittopskip}%
        \boxmaxdepth\z@ \splittopskip\z@
|       \message{Padded box of size \the\ht\@tempboxa\space split 
|                to \the\dimen@}%
%    \end{macrocode}
% Split box here
%    \begin{macrocode}
        \setbox\tw@\vsplit\@tempboxa to\dimen@
|       \toks99\expandafter{\splitfirstmark}%
|       \toks98\expandafter{\splitbotmark}%
|       \message{Marks are: \the\toks99, \the\toks98. }%
        \setbox\tw@\vbox{\unvbox\tw@}% natural-sized
|       \message{Natural height of split box is \the\ht\tw@, leaving 
|          \the\ht\@tempboxa\space remainder. }%
%    \end{macrocode}
% If the split-to size $>$ (\cs{vsize}-\cs{topskip}), then set box to full size
%    \begin{macrocode}
        \begingroup
        \advance\dimen@\topskip
        \expandafter\endgroup
        \ifdim\dimen@>\pagegoal
|         \message{Frame is big -- Use up the full column. }%
          \dimen@ii\pagegoal
          \advance\dimen@ii -\topskip
          \advance\dimen@ii \FrameHeightAdjust\relax
        \else  % suspect this is wrong:
%    \end{macrocode}
% If the split-to size $>$ feasible room-on-page, rebox it smaller.
%    \begin{macrocode}
          \advance\dimen@.8\pageshrink
          \ifdim\ht\tw@>\dimen@
|           \message{Box too tall; rebox it to \the\dimen@. }%
            \dimen@ii\dimen@
          \else % use natural size
            \dimen@ii\ht\tw@
          \fi
        \fi
%    \end{macrocode}
% Re-box contents to desired size \cs{dimen@ii}
%    \begin{macrocode}
        \advance\dimen@ii -\fb@frh
        \setbox\tw@\vbox to\dimen@ii \bgroup
%    \end{macrocode}
% remove simulated frame and page flexibility:
%    \begin{macrocode}
        \vskip -\fb@frh \@plus-\pagestretch \@minus-.8\pageshrink
        \unvbox\tw@ \unpenalty\unpenalty
        \ifdim\lastkern=-137sp % whole box went to next page
|          \message{box split at beginning! }%
           % need work here???
           \egroup \fb@resto@set \eject % (\vskip for frame size was discarded) 
           \fb@adjheight
           \fb@put@frame#1#2% INSERTED ???
        \else % Got material split off at the head
           \egroup \fb@resto@set
           \ifvoid\@tempboxa % it all fit after all
|             \message{box split at end! }%
              \setbox\@tempboxa\box\tw@
              \fb@putboxa#1%
              \fb@afterframe
           \else % it really did split
|             \message{box split as expected. Its reboxed height 
|                      is \the\ht\tw@. }%
              \ifdim\wd\tw@>\z@
                \wd\tw@\wd\@tempboxa
%    \end{macrocode}
% PW: the next line was: \\
% \verb!\centerline{#2{\box\tw@}}%  ??? \centerline bad idea?! \\
% but I have changed it as follows so that \cs{centerline} can be changed
% from elsewhere if useful.
%    \begin{macrocode}
                \memfblineboxtwo{#2{\box\tw@}}%  ??? \centerline bad idea? \\
              \else
|               \message{Zero width means likely blank. 
|                        Don't frame it (guess)}%
                \box\tw@
              \fi
              \hrule \@height\z@ \@width\hsize
              \eject
              \fb@adjheight
              \fb@put@frame\LastFrameCommand\MidFrameCommand
  \fi\fi\fi\fi\fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\memfblineboxtwo}
% \begin{macro}{\memfblineboxa}
% PW: this is an addition of mine. There is a question mark against the
% use of \cs{centerline} within the \Lenv{framed} code. I have
% created these two macros which are used in the code instead of 
% \cs{centerline}, so that those parts of the code can be easily altered.
% are used instead
%    \begin{macrocode}
\newcommand{\memfblineboxtwo}[1]{\centerline{#1}}
\newcommand{\memfblineboxa}[1]{\centerline{#1}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\fb@putboxa}
%    \begin{macrocode}
\def\fb@putboxa#1{%
  \ifvoid\@tempboxa
%%%%    PackageWarning{framed}{Boxa is void -- discard it. }% 
    \@memwarn{Boxa is void -- discard it. }%
  \else
|   \message{Frame and place boxa. }%
|   %{\showoutput\showbox\@tempboxa}%
%%%%%%%    \centerline{#1{\box\@tempboxa}}%
    \memfblineboxa{#1{\box\@tempboxa}}%
  \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\fb@afterframe}
%    \begin{macrocode}
\def\fb@afterframe{%
    \nointerlineskip \null %{\showoutput \showlists}
    \penalty-30 \vskip\topsep \relax}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\fb@frw}
% \begin{macro}{\fb@frh}
% \begin{macro}{\fb@sizeofframe}
% \cs{fb@sizeofframe}\marg{framecommand} measures width and height added by 
% frame (\meta{framecommand}) and call the results \cs{fb@frw} and \cs{fb@frh}.
%    \begin{macrocode}
\newdimen\fb@frw
\newdimen\fb@frh
\def\fb@sizeofframe#1{\begingroup
 \setbox\z@\vbox{\vskip-5in \hbox{\hskip-5in 
   #1{\hbox{\vrule \@height 4.7in \@depth.3in \@width 5in}}}%
   \vskip\z@skip}%
|  \message{Measuring frame addition for \string#1 in \@currenvir\space 
|    gives ht \the\ht\z@\space and wd \the\wd\z@. }%
%{\showoutput\showbox\z@}%
 \global\fb@frw\wd\z@ \global\fb@frh\ht\z@
 \endgroup}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\fb@adjheight}
%    \begin{macrocode}
\def\fb@adjheight{%
  \vbox to\FrameHeightAdjust{}% get proper baseline skip from above.
  \penalty\@M \nointerlineskip
  \vskip-\FrameHeightAdjust
  \penalty\@M} % useful for tops of pages

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\zero@glue}
%    \begin{macrocode}
\edef\zero@glue{\the\z@skip}

\catcode`\|=\FrameRestore

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\FrameCommand}
% \begin{macro}{\FrameRule}
% \begin{macro}{\FrameSep}
% \begin{macro}{\FirstFrameCommand}
% \begin{macro}{\MidFrameCommand}
% \begin{macro}{\LastFrameCommand}
% Provide configuration commands:
%    \begin{macrocode}
\providecommand\FrameCommand{%
 \setlength\fboxrule{\FrameRule}\setlength\fboxsep{\FrameSep}%
 \fbox}
\@ifundefined{FrameRule}{\newdimen\FrameRule \FrameRule=\fboxrule}{}
\@ifundefined{FrameSep} {\newdimen\FrameSep  \FrameSep =3\fboxsep}{}
\providecommand\FirstFrameCommand{\FrameCommand}
\providecommand\MidFrameCommand{\FrameCommand}
\providecommand\LastFrameCommand{\FrameCommand}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\FrameHeightAdjust}
% Height of frame above first baseline when frame starts a page:
%    \begin{macrocode}
\providecommand\FrameHeightAdjust{6pt}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\FrameRestore}
% \cs{FrameRestore} has parts of \cs{@parboxrestore}, performing a similar but 
% less complete restoration of a default layout.  See how it is used in the 
% "settings" argument of \cs{MakeFrame}.  Though not a parameter, \cs{hsize} 
% should be set to the desired total line width available inside the
% frame before invoking \cs{FrameRestore}.  
%    \begin{macrocode}
\def\FrameRestore{%
   \let\if@nobreak\iffalse
   \let\if@noskipsec\iffalse
   \let\-\@dischyph
   \let\'\@acci\let\`\@accii\let\=\@acciii
   %  \message{FrameRestore:
   %    \@totalleftmargin=\the \@totalleftmargin,
   %    \rightmargin=\the\rightmargin, 
   %    \@listdepth=\the\@listdepth.  }%
%    \end{macrocode}
%  Test if we are in a list (or list-like paragraph)
%    \begin{macrocode}
   \ifnum \ifdim\@totalleftmargin>\z@ 1\fi  
          \ifdim\rightmargin>\z@ 1\fi
          \ifnum\@listdepth>0 1\fi 0>\z@
     %     \message{In a list: \linewidth=\the\linewidth, 
     %       \@totalleftmargin=\the\@totalleftmargin,
     %       \parshape=\the\parshape, \columnwidth=\the\columnwidth, 
     %       \hsize=\the\hsize, 
     %       \labelwidth=\the\labelwidth. }%
%    \end{macrocode}
% Now try to propagate changes of width from \cs{hsize} to list parameters.
% This is deficient, but a more advanced way to indicate modification to text 
% dimensions is not (yet) provided; in particular, no separate left/right
% adjustment. (PW. I have provided a macro for the next few lines as I think
% that I may have a reason to allow them to be easily changed).
%    \begin{macrocode}  
%%%     \@setminipage % snug fit around the item
%%%     \advance\linewidth-\columnwidth \advance\linewidth\hsize
%%%     \parshape\@ne \@totalleftmargin \linewidth
     \memfblistfixparams
   \else % Not in list
     \linewidth=\hsize
     %\message{No list, set \string\linewidth=\the\hsize. }%
   \fi
   \sloppy}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\memfblistfixparams}
% An extract of some code from \cs{FrameRestore}.
% Try to propagate changes of width from \cs{hsize} to list parameters.
% This is deficient, but a more advanced way to indicate modification to text 
% dimensions is not (yet) provided; in particular, no separate left/right
% adjustment. 
%    \begin{macrocode}
\newcommand*{\memfblistfixparams}{%
  \@setminipage % snug fit around the item
  \advance\linewidth-\columnwidth \advance\linewidth\hsize
  \parshape\@ne \@totalleftmargin \linewidth}

%    \end{macrocode}
% \end{macro}
%
%    I have moved the following from the start of the \Lpack{framed}
% package to here. 
%
% \begin{environment}{framed}
% \begin{environment}{shaded}
% \begin{environment}{leftbar}
% \begin{environment}{snugshade}
%    \begin{macrocode}
\newenvironment{framed}% using default \FrameCommand
  {\MakeFramed {\advance\hsize-\width \FrameRestore}}%
  {\endMakeFramed}

\newenvironment{shaded}{%
  \def\FrameCommand{\fboxsep=\FrameSep \colorbox{shadecolor}}%
  \MakeFramed {\FrameRestore}}%
  {\endMakeFramed}

\newenvironment{leftbar}{%
  \def\FrameCommand{\vrule width 3pt \hspace{10pt}}%
  \MakeFramed {\advance\hsize-\width \FrameRestore}}%
 {\endMakeFramed}

\newenvironment{snugshade}{%
  \def\FrameCommand{\colorbox{shadecolor}}%
  \MakeFramed {\FrameRestore\@setminipage}}%
 {\par\unskip\endMakeFramed}

%    \end{macrocode}
% \end{environment}
% \end{environment}
% \end{environment}
% \end{environment}
%
% As the package used \cs{newenvironment} it will
% burp if it is used with the class. There are two options: either
% prevent \Lpack{framed} from being loaded, or kill the environments
% if it is loaded. I'm going for the latter as Donald will be updating
% his package at some point and author's may want to use it before it's
% updated here.
%
%    \begin{macrocode}
\AtBeginPackage{framed}{%
  \let\framed\relax \let\endframed\relax
  \let\shaded\relax \let\endshaded\relax
  \let\leftbar\relax \let\endleftbar\relax
  \let\snugshade\relax \let\endsnugshade\relax}

%    \end{macrocode}
%
%
% \begin{environment}{qframe}
% This is from an email to me from DA shortly after he released \Lpack{framed}
% v 0.95.
% \begin{quote}
% A frame more like a simple parbox. 
% Notably useful for use
% inside a single list item --- the frame matches the text of the other
% items. 
% \end{quote}
% He actually called it \Lenv{pframe} and said that something similar
% could be in a later version of \Lpack{framed}.
%
% I have found it useful for framing \Lenv{quote} or \Lenv{adjustwidth}
% environments, or similar. Hence the name, from 
% `\textit{q}uote \textit{frame}'.
% \changes{v1.61803}{2008/01/30}{Added the qframe environment}
%    \begin{macrocode}
\newenvironment{qframe}{%
  \def\FrameCommand##1{\fboxrule=\FrameRule\fboxsep=\FrameSep
    \hskip\@totalleftmargin\fbox{##1}% There is no \@totalrightmargin, so...
      \hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
  \MakeFramed{\advance\hsize-\width 
              \advance\hsize \FrameSep
              \@totalleftmargin\z@ \linewidth=\hsize}}%
 {\endMakeFramed}

%    \end{macrocode}
% \end{environment}
%
% \begin{environment}{qshade}
% And here is my corresponding version for \Lenv{shaded}.
% \changes{v1.61803}{2008/01/30}{Added the qshade environment}
%    \begin{macrocode}
\newenvironment{qshade}{%
  \def\FrameCommand##1{\fboxsep=\FrameSep
    \hskip\@totalleftmargin
    \hskip -1\FrameSep
    \colorbox{shadecolor}{##1}% 
      \hskip-\linewidth \hskip-\@totalleftmargin 
      \hskip -1\FrameSep
      \hskip\columnwidth}%
  \MakeFramed{\advance\hsize-\width 
              \advance\hsize 3\FrameSep
              \@totalleftmargin\z@ \linewidth=\hsize}}%
 {\endMakeFramed}

%    \end{macrocode}
% \end{environment}
%
%
% \subsection{The newfile package}
%
% The following code is from the \Lpack{newfile} package.
% To try and avoid name clashes with other packages, each internal macro
% in this package includes the character string `\verb?stre@m?'.
%
% \begin{macro}{\newoutputstream}
% \cs{newoutputstream}\marg{stream} creates a new output stream called \meta{stream}.
% Different files may be associated with the \meta{stream}. Note that
% TeX permits no more than 16 output streams.
%    \begin{macrocode}
\newcommand*{\newoutputstream}[1]{%
  \@ifundefined{#1outstre@m}%
    {\expandafter\newwrite\csname #1outstre@m\endcsname
     \csname newif\expandafter\endcsname
       \csname ifstre@m#1open\endcsname
     \global\csname stre@m#1openfalse\endcsname
     \expandafter\ifx\csname atstreamopen#1\endcsname\relax
       \global\@namedef{atstreamopen#1}{}%
     \fi
     \expandafter\ifx\csname atstreamclose#1\endcsname\relax
       \global\@namedef{atstreamclose#1}{}%
     \fi
    }%
    {\@memwarn{Output stream #1\space is already defined}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\newinputstream}
% \cs{newinputstream}\marg{stream} creates a new input stream called \meta{stream}.
% Different files may be associated with the \meta{stream}. Note that
% TeX permits no more than 16 input streams.
%    \begin{macrocode}
\newcommand*{\newinputstream}[1]{%
  \@ifundefined{#1instre@m}%
    {\expandafter\newread\csname #1instre@m\endcsname
     \csname newif\expandafter\endcsname
       \csname ifstre@m#1open\endcsname
     \global\csname stre@m#1openfalse\endcsname
     \expandafter\ifx\csname atstreamopen#1\endcsname\relax
       \global\@namedef{atstreamopen#1}{}%
     \fi
     \expandafter\ifx\csname atstreamclose#1\endcsname\relax
       \global\@namedef{atstreamclose#1}{}%
     \fi
    }%
    {\@memwarn{Input stream #1\space is already defined}}}

%    \end{macrocode}
% \end{macro}
%
%    Some checking macros will be useful as some of the checks occur in
% multiple places.
%
% \begin{macro}{\IfStreamOpen}
% \cs{IfStreamOpen}\marg{stream}\marg{TRUE code}\marg{FALSE code}
% checks if stream \meta{stream} is currently open.
%    \begin{macrocode}
\newcommand{\IfStreamOpen}[3]{%
  \csname ifstre@m#1open\endcsname#2\else#3\fi}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\instre@mandopen}
% \cs{instre@mandopen}\marg{stream}\marg{TRUE code} checks if \meta{stream}
% is an input stream and is open. If so, it executes \meta{TRUE code}.
%    \begin{macrocode}
\newcommand{\instre@mandopen}[2]{%
  \@ifundefined{#1instre@m}{%
    \@memwarn{#1\space is not an input stream}}%
  {\IfStreamOpen{#1}{#2}{%
    \@memwarn{Input stream #1\space is not open}}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\instre@mandclosed}
% \cs{instre@mandclosed}\marg{stream}\marg{TRUE code} checks if \meta{stream}
% is an input stream and is closed (not open). 
% If so, it executes \meta{TRUE code}.
%    \begin{macrocode}
\newcommand{\instre@mandclosed}[2]{%
  \@ifundefined{#1instre@m}{%
    \@memwarn{#1\space is not an input stream}}%
  {\IfStreamOpen{#1}{%
    \@memwarn{Input stream #1\space is open}}{#2}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\outstre@mandopen}
% \cs{outstre@mandopen}\marg{stream}\marg{TRUE code} checks if \meta{stream}
% is an output stream and is open. If so, it executes \meta{TRUE code}.
%    \begin{macrocode}
\newcommand{\outstre@mandopen}[2]{%
  \@ifundefined{#1outstre@m}{%
    \@memwarn{#1\space is not an output stream}}%
  {\IfStreamOpen{#1}{#2}{%
    \@memwarn{Output stream #1\space is not open}}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\outstre@mandclosed}
% \cs{outstre@mandclosed}\marg{stream}\marg{TRUE code} checks if \meta{stream}
% is an output stream and is closed (not open). 
% If so, it executes \meta{TRUE code}.
%    \begin{macrocode}
\newcommand{\outstre@mandclosed}[2]{%
  \@ifundefined{#1outstre@m}{%
    \@memwarn{#1\space is not an output stream}}%
  {\IfStreamOpen{#1}{%
    \@memwarn{Output stream #1\space is open}}{#2}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\openoutputfile}
% \cs{openoutputfile}\marg{filename}\marg{stream} opens the file called 
% \meta{filename} and attaches it to the stream \meta{stream} for
% writing. However, if the \cs{nofiles} command has been given the
% file is \emph{not} attached to the stream. No more than one file can be 
% attached to a stream at any given time.
%    \begin{macrocode}
\newcommand*{\openoutputfile}[2]{%
  \outstre@mandclosed{#2}{%
    \global\@namedef{#1@filename}{#1}%
    \if@filesw 
      \immediate\openout\@nameuse{#2outstre@m}=\@nameuse{#1@filename}%
    \fi
    \global\csname stre@m#2opentrue\endcsname%
    \@nameuse{atstreamopen#2}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\closeoutputstream}
% \cs{closeoutputstream}\marg{stream} closes the stream \meta{stream}.
%    \begin{macrocode}
\newcommand*{\closeoutputstream}[1]{%
  \outstre@mandopen{#1}{%
    \@nameuse{atstreamclose#1}%
    \immediate\closeout\@nameuse{#1outstre@m}%
    \global\csname stre@m#1openfalse\endcsname}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\openinputfile}
% \cs{openinputfile}\marg{filename}\marg{stream} opens the file called 
% \meta{filename} and attaches it to the stream \meta{stream} for
% reading. The file is added to the list of files. 
% No more than one file can be attached to a stream at
% any given time.
%    \begin{macrocode}
\newcommand{\openinputfile}[2]{%
  \IfFileExists{#1}{%                   file exists
    \instre@mandclosed{#2}{% 
      \@addtofilelist{#1}%
      \global\@namedef{#1@filename}{#1}%
      \immediate\openin\@nameuse{#2instre@m}=\@nameuse{#1@filename}%
      \global\csname stre@m#2opentrue\endcsname%
      \@nameuse{atstreamopen#2}}}%
  {%                                    file not found
    \typeout{No file #1.}
  }}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\closeinputstream}
% \cs{closeinputstream}\marg{stream} closes the stream \meta{stream}.
%    \begin{macrocode}
\newcommand{\closeinputstream}[1]{%
  \instre@mandopen{#1}{%
     \@nameuse{atstreamclose#1}%
     \immediate\closein\@nameuse{#1instre@m}%
     \global\csname stre@m#1openfalse\endcsname}}

%    \end{macrocode}
% \end{macro}
%
% \begin{environment}{writeverbatim}
% \verb?\begin{writeverbatim}?\marg{stream} writes the contents of
% the environment as verbatim text to the given \meta{stream}.
%    \begin{macrocode}
\def\writeverbatim#1{%
  \@bsphack
  \let\do\@makeother\dospecials
  \catcode`\^^M\active
  \def\verbatim@processline{%
    \immediate\write\@nameuse{#1outstre@m}{\the\verbatim@line}}%
  \verbatim@start}
\def\endwriteverbatim{\@esphack}

%    \end{macrocode}
% \end{environment}
%
% \begin{macro}{\addtostream}
% \cs{addtostream}\marg{stream}\marg{text} writes \meta{text} to the
% given \meta{stream}.
%    \begin{macrocode}
\newcommand{\addtostream}[2]{%
  \@bsphack
  \outstre@mandopen{#1}{%
    {\let\protect\string
     \immediate\write\@nameuse{#1outstre@m}{#2}%
    }}%
  \@esphack}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ifstre@mnoteof}
% \begin{macro}{\checkstre@mnoteof}
% \cs{checkstre@mnoteof}\marg{stream} sets \cs{ifstre@mnoteof} to TRUE if
% \meta{stream} is not at the end of the file (i.e., it is the opposite
% of \cs{ifeof}).
%    \begin{macrocode}
\newif\ifstre@mnoteof
\newcommand{\checkstre@meof}[1]{%
  \stre@mnoteoftrue\ifeof\@nameuse{#1instre@m}\stre@mnoteoffalse\fi}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\readstream}
% \cs{readstream}\marg{stream} reads the contents of
% the given \meta{stream} as \cs{input} text.
%    \begin{macrocode}
\def\readstream#1{
  \instre@mandopen{#1}{%
    \loop \checkstre@meof{#1} \ifstre@mnoteof
      \read\@nameuse{#1instre@m} to\temptokstre@m
     \temptokstre@m
    \repeat
    }}
  
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\readaline}
% \cs{readaline}\marg{stream} reads what TeX considers to be one line
% from the given \meta{stream} as \cs{input} text.
%    \begin{macrocode}
\def\readaline#1{
  \instre@mandopen{#1}{%
    \ifeof\@nameuse{#1instre@m}
      \@memwarn{No more to read from stream #1}
    \else
      \read\@nameuse{#1instre@m} to\temptokstre@m
      \temptokstre@m
    \fi}}
  
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\readverbatim}
% \cs{readverbatim}\marg{stream} reads the contents of
% the given \meta{stream} as verbatim text.
%
% The read verbatim code is a slight variation on code from the
% \Lpack{verbatim} package. Most of the setup is done by the macros
% \cs{stre@mverb@input}\marg{setup}\marg{stream} and
% \cs{verbatim@readstre@m}\marg{stream}. Finally, \cs{verbatim@read@file}
% is a \Lpack{verbatim} package macro.
% \changes{v3.8.2}{2024/01/26}{Removed tabs support and added the tab
% marking support to the starred version like we did for \cs{verbatiminput}}
%    \begin{macrocode}
\def\readverbatim{\begingroup
  %\ift@bs
  %  \def\verbatim@processline{\tabverbatim@processline}%
  %\fi
  \@ifstar{\stre@mverb@input{\@setupverbvisiblespace\@vobeyspaces}}%{\@maybeobeytabs}}%
     {\stre@mverb@input{\frenchspacing\@vobeyspaces}}}%\@maybeobeytabs}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\stre@mverb@input}
% \begin{macro}{\@verbinstre@m}
% \cs{stre@mverb@input}\marg{setup}\marg{stream} is a stream
% version of \cs{verbatim@input}. It defines \cs{@verbinstre@m}
% to be \meta{stream}.
%
%    \begin{macrocode}
\newcommand{\stre@mverb@input}[2]{%
  \IfStreamOpen{#2}%
    {\@verbatim #1\relax
     \def\@verbinstre@m{\@nameuse{#2instre@m}}
     \verb@readstre@m\endtrivlist\endgroup\@doendpe}%
    {\@memwarn{Stream #2\space is not open}\endgroup}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\verb@readstre@m}
% \cs{verb@readstre@m} is the stream analogue to \cs{verbatim@readfile}.
%    \begin{macrocode}
\newcommand{\verb@readstre@m}{%
  \verbatim@startline
  \expandafter\endlinechar\expandafter\m@ne
  \expandafter\verbatim@read@stre@m
  \expandafter\endlinechar\the\endlinechar\relax
  \verbatim@finish}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\verbatim@read@stre@m}
% \cs{verbatim@read@stre@m} is the analogue to \cs{verbatim@readfile}.
% It gets its input from the stream \cs{@verbinstre@m}, which is defined
% in the \cs{stre@mverb@input} macro.
%    \begin{macrocode}
\newcommand{\verbatim@read@stre@m}{%
  \read\@verbinstre@m to\next
  \ifeof\@verbinstre@m
  \else
    \expandafter\verbatim@addtoline\expandafter{\next}%
    \verbatim@processline
    \verbatim@startline
    \expandafter\verbatim@read@stre@m
  \fi}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\readboxedverbatim}
% \cs{readboxedverbatim}\marg{stream} is the equivalent of
% \cs{readverbtim} except that it generates a boxed verbatim.
%    \begin{macrocode}
\newcommand{\readboxedverbatim}{\begingroup
  \@ifstar{\stre@mbvin\relax}%
          {\stre@mbvin{\frenchspacing\@vobeyspaces}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\stre@mbvin}
% \cs{stre@mbvin}\marg{setup}\marg{stream} is the workhorse for
% \cs{readboxedverbatim}, and in its turn it uses \cs{verb@readstre@m}.
%    \begin{macrocode}
\newcommand{\stre@mbvin}[2]{%
  \IfStreamOpen{#2}%
    {\setupboxverb@line
     \@verbatim #1\relax
     \def\@verbinstre@m{\@nameuse{#2instre@m}}%
     \setupbox@verb
     \verb@readstre@m\bvendrulehook\endtrivlist\endgroup\@doendpe}%
    {\@memwarn{Stream #2\space is not open}\endgroup}}

%    \end{macrocode}
% \end{macro}
%
%
%
% \section{Utilities}
%
%
% \subsection{Extra `provide' commands}
%
% \begin{macro}{\provideenvironment}
% Works like \cs{providecommand} but for environments.
% \changes{v1.2}{2002/08/04}{Added \cs{provideenvironment} and supports}
%    \begin{macrocode}
\newcommand{\provideenvironment}{\@star@or@long\m@mprovenv}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@mprovenv}
% This checks if the environment has been defined. If not it calls
% the kernel code for \cs{newenvironment} otherwise it calls code to
% discard arguments.
%    \begin{macrocode}
\newcommand{\m@mprovenv}[1]{\@ifundefined{#1}%
  {\new@environment{#1}}%       % create new environment
  {\@memwarn{Environment `#1' already defined}%
   \m@mgobbleoptsandtwo}}
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\m@mgobbleoptsandtwo}
% \begin{macro}{\m@mgobbleoptandtwo}
% \cs{m@mgobbleoptsandtwo} gobbles the \verb?[opt][opt]{begin}{end}? arguments to 
% \cs{provideenvironment}. It is actually more general than that as it will 
% gobble any sequence of any number of optional arguments followed by
% two required arguments. If there are no optional arguments it disposes
% of the two required ones, otherwise it calls a recursive procedure to
% discard any number of optionals, then two required ones.
%
% \cs{m@mgobbleoptandtwo} recursively discards optional arguments, then finally
% two required arguments.
%    \begin{macrocode}
\newcommand{\m@mgobbleoptsandtwo}{%
  \@ifnextchar [{\m@mgobbleoptandtwo}{\@gobbletwo}}
\def\m@mgobbleoptandtwo[#1]{%
  \@ifnextchar [{\m@mgobbleoptandtwo}{\@gobbletwo}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\providecounter}
% Works like the other \cs{provide...} commands, but for counters.
% Code is based on \cs{newcounter} in \file{ltcounts.dtx}.
% \changes{v1.2}{2002/07/17}{Added \cs{providecounter}}
%    \begin{macrocode}
\newcommand*{\providecounter}[1]{%
  \@ifundefined{c@#1}%
    {\newcounter{#1}}%
    {\@memwarn{Counter `#1' already defined}%
      \@ifnextchar[{\m@mgobbleopt}{}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@mgobbleopt}
% Gobble an optional argument.
% \changes{v1.2}{2002/07/07}{Added \cs{m@mgobbleopt}}
%    \begin{macrocode}
\def\m@mgobbleopt[#1]{}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\providelength}
% Works like the other \cs{provide...} commands, but for lengths.
% Code is based on \cs{provide@command} in \file{ltdefns.dtx}.
% \changes{v1.2}{2002/07/17}{Added \cs{providelength}}
%    \begin{macrocode}
\newcommand*{\providelength}[1]{%
  \begingroup
    \escapechar\m@ne\xdef\@gtempa{{\string#1}}%
  \endgroup
  \expandafter\@ifundefined\@gtempa
    {\newlength{#1}}%
    {\@memwarn{Length #1 already defined}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\newloglike}
% \begin{macro}{\m@mnewlog}
% \begin{macro}{\m@mnewlogs}
% For defining a new log-like math function.
% \verb?\newloglike{\fun}{string}? or \verb?\newloglike*{\fun}{string}?.
% The starred version is for functions with limits (like an integral sign).
% \changes{v1.6}{2004/01/28}{Added \cs{newloglike}}
% \MarkedForDeprecation{\cs{newloglike}}
%    \begin{macrocode}
\newcommand*{\newloglike}{%
  \MarkDeprecated{\newloglike}{in 2026. We recommand using\MessageBreak%
    \string\DeclareMathOperator\space from amsopn (amsmath) instead.}%
  \@ifstar{\m@mnewlogs}{\m@mnewlog}}
\newcommand*{\m@mnewlogs}[2]{%
  \newcommand*{#1}{\mathop{\operator@font #2}}}
\newcommand*{\m@mnewlog}[2]{%
  \newcommand*{#1}{\mathop{\operator@font #2}\nolimits}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% 
% \begin{macro}{\provideloglike}
% \begin{macro}{\m@mprovlogs}
% \begin{macro}{\m@mprovlog}
%  The provide version of \cs{newloglike}.
% \changes{v1.6}{2004/01/28}{Added \cs{provideloglike}}
% \MarkedForDeprecation{\cs{provideloglike}}
%    \begin{macrocode}
\newcommand*{\provideloglike}{%
  \MarkDeprecated*{\provideloglike}{in 2026}
  \@ifstar{\m@mprovlogs}{\m@mprovlog}}
\newcommand*{\m@mprovlogs}[2]{%
  \providecommand*{#1}{\mathop{\operator@font #2}}}
\newcommand*{\m@mprovlog}[2]{%
  \providecommand*{#1}{\mathop{\operator@font #2}\nolimits}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% 
%
% \subsection{Changing counters}
%
% \changes{v3.8.3}{2024/02/02}{Removed code for \cs{counterwithin},
% \cs{counterwithout} and \cs{@removefromreset}, they have been
% `provided' since 2018}
%
% The class used to have code similar to the package \Lpack{chngcntr}
% and \Lpack{remreset}. Since 2018 these have been in the
% \LaTeX-kernel and was just provided by the class. By 2024 the code
% was removed. 
%
% 
% \begin{macro}{\letcountercounter}
% \begin{macro}{\c@m@morig@ctr}
% \begin{macro}{\unletcounter}
% At times it is handy to `let' one counter act as if it was a
% different counter. Say you have two constructions, each with their
% own counter A and B, now you want them to cooperate, counting in
% unison. This can be done using the \verb?\letcountercounter?.
%
% \medskip
%
% \cs{letcountercounter}\marg{counterA}\marg{counterB} \cs{let}s 
% (make the same) \meta{counterA} to \meta{counterB}. The
% original of \meta{counterA} is kept in \cs{c@m@morig@ctr}\meta{counterA}.
%
% \cs{unletcounter}\marg{counterA} restores \meta{counterA} to its un\cs{let}
% condition.
%
% The code is based on Donald Arseneau's `Re: \cs{let}, \cs{csname} and 
% \cs{endcsname}', CTT, 2004/12/08. The long version, where \cs{xp}
% is actually \cs{expandafter} is along the lines of:
% \begin{verbatim}
% \xp\xp\xp\let\xp\csname\xp c@#1\xp\endcsname\csname c@#2\endcsname
% \end{verbatim}
% which employs 6 \cs{expandafter}s. DA's version uses only 2. The technique
% can be applied to other kinds of \cs{let}s.
%
%    \begin{macrocode}
\newcommand*{\letcountercounter}[2]{%
  \expandafter\let\csname c@m@morig@ctr#1\expandafter\endcsname%
                   \csname c@#1\endcsname
  \expandafter\let\csname c@#1\expandafter\endcsname%
                  \csname c@#2\endcsname}
\newcommand*{\unletcounter}[1]{%
 \expandafter\let\csname c@#1\expandafter\endcsname%
                 \csname c@m@morig@ctr#1\endcsname}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \subsection{Odd/even page checking}
%
% It is difficult to check robustly if the current page is odd or even.
% This code, which is based on the \Lpack{chngpage} package~\cite{CHNGPAGE}, 
% provides a method that has proved (so far) to be robust.
%    It works by writing out a label and on the next LaTeX run checks
% the page reference for the label.
%
% \begin{macro}{\ifoddpage}
% \begin{macro}{\oddpagetrue}
% \begin{macro}{\oddpagefalse}
% \begin{macro}{\ifstrictpagecheck}
% \begin{macro}{\strictpagechecktrue}
% \begin{macro}{\strictpagecheckfalse}
% \begin{macro}{\strictpagecheck}
% \begin{macro}{\easypagecheck}
% The boolean \cs{ifoddpage} is TRUE if the checked page is odd. The
% boolean \cs{ifstrictpagecheck} is for turning on (TRUE) and off (FALSE)
% the strictest method of page checking. 
% \changes{v1.61803}{2008/01/30}{Added \cs{strictpagecheck} and \cs{easypagecheck}}
%    \begin{macrocode}
\newif\ifoddpage
\newif\ifstrictpagecheck
  \strictpagecheckfalse
\newcommand*{\strictpagecheck}{\strictpagechecktrue}
\newcommand*{\easypagecheck}{\strictpagecheckfalse}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\c@cp@cntr}
% \begin{macro}{\cplabel}
% The counter \verb?cp@cntr? is used to make unique labels, which start 
% with \cs{cplabel}.
%    \begin{macrocode}
\newcounter{cp@cntr}
\newcommand{\cplabel}{^_}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\checkoddpage}
% This is the user level command to check for odd/even page. It does
% a robust check for \cs{strictpagecheck} otherwise the simple minded
% check. It sets \cs{ifoddpage} to TRUE if the page is odd, otherwise
% it sets it to FALSE.
%
%    This is now fixed so that it should work for non-arabic page numbering.
% It uses a new label/pageref variant based on the page counter value, not
% its printed representation. This also gets rid of worrying about hyperref!!
% The problem was discovered by Bastiaan Niels Veelo
%
% \changes{v1.4}{2003/11/22}{Complete rewrite of odd page checking 
%                            (from patch v1.6)}
%    \begin{macrocode}
\DeclareRobustCommand{\checkoddpage}{%
  \oddpagefalse%
  \ifstrictpagecheck%
    \stepcounter{cp@cntr}\pmemlabel{\cplabel\thecp@cntr}%
    \@memcnta=\pmemlabelref{\cplabel\thecp@cntr}\relax
    \ifodd\@memcnta\oddpagetrue\fi
  \else
    \ifodd\c@page\oddpagetrue\fi
  \fi}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\thepmemc@@page}
% The value of the page counter.
%    \begin{macrocode}
\gdef\thepmemc@@page{\the\c@page}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\pmemprotected@write}
% \cs{pmemprotected@write} is a modified version of the kernel's
% \cs{protected@write}.
%
% This version of the macro was provided by Romano Giannetti on 15
% July 2003.
%    \begin{macrocode}
\long\def\pmemprotected@write#1#2#3{%
  \begingroup
  \let\thepmemc@@page\relax
  #2%
  \let\protect\@unexpandable@protect
  \edef\reserved@a{\write#1{#3}}%
  \reserved@a
  \endgroup
  \if@nobreak\ifvmode\nobreak\fi\fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\pmemlabel}
% A version of \cs{label} that uses \cs{pmemprotected@write}.
%    \begin{macrocode}
\newcommand{\pmemlabel}[1]{\@bsphack
  \pmemprotected@write\@auxout{}%
    {\string\newpmemlabel{#1}{\thepmemc@@page}}%
  \@esphack}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\newpmemlabel}
% \begin{macro}{\pmemlabelref}
% We have to be able to cope with a particular label
% not (yet) being in the the \file{.aux} file when we come to check 
% the page number.
%    \begin{macrocode}
\newcommand{\newpmemlabel}[2]{{\global\@namedef{m@#1}{#2}}}
\newcommand{\pmemlabelref}[1]{%
  \expandafter\ifx\csname m@#1\endcsname\relax
    0%
  \else
    \csname m@#1\endcsname
  \fi}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%  \subsection{Checking for empty arguments}
%
%  Like page checking, testing for an empty macro argument is more
% difficult than it might appear at first sight.
%
%    The following code is from the \Lpack{ifmtarg} package~\cite{IFMTARG}.
%
% \begin{macro}{\@ifmtarg}
% \begin{macro}{\@ifnotmtarg}
% \cs{@ifmtarg}\marg{arg}\marg{code when empty}\marg{code when arg not empty} \\
% \cs{@ifnotmtarg}\marg{arg}\marg{code when arg not empty} \\
%    \begin{macrocode}
\begingroup
\catcode`\Q=3
\long\gdef\@ifmtarg#1{\@xifmtarg#1QQ\@secondoftwo\@firstoftwo\@nil}
\long\gdef\@xifmtarg#1#2Q#3#4#5\@nil{#4}
\long\gdef\@ifnotmtarg#1{\@xifmtarg#1QQ\@firstofone\@gobble\@nil}
\endgroup

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%    Some example uses:
% \begin{verbatim}
% \newcommand{\isempty}[1]{%
%    \@ifmtarg{#1}{\typeout{YES}}{\typeout{NO}}}
% \newcommand{\isnotempty}[1]{%
%    \@ifnotmtarg{#1}{\typeout{YES}}}
%
% \isempty{}    -> YES  \isnotempty{}    -> 
% \isempty{   } -> YES  \isnotempty{   } -> 
% \isempty{A}   -> NO   \isnotempty{A}   -> YES 
% \isempty{ A } -> NO   \isnotempty{ A } -> YES 
% \end{verbatim}
%
%
% \subsection{Changing the page layout in the document}
%
%  You should not do this, but\ldots
%
% The following code is essentially from the \Lpack{chngpage} 
% package~\cite{CHNGPAGE}.
%
% \begin{macro}{\ch@ngetext}
% This macro sets the page output parameters.
%    \begin{macrocode}
\DeclareRobustCommand{\ch@ngetext}{%
  \setlength{\@colht}{\textheight}\setlength{\@colroom}{\textheight}%
  \setlength{\vsize}{\textheight}\setlength{\columnwidth}{\textwidth}%
  \if@twocolumn%
    \advance\columnwidth-\columnsep \divide\columnwidth\tw@%
    \@firstcolumntrue%
  \fi%
  \setlength{\hsize}{\columnwidth}%
  \setlength{\linewidth}{\hsize}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\changetext}
% \cs{changetext}\marg{H}\marg{W}\marg{E}\marg{O}\marg{G}
% adds the given lengths to 5 main bits of the page layout. An empty
% argument means `no change'.
%    \begin{macrocode}
\DeclareRobustCommand{\changetext}[5]{%
  \@ifmtarg{#1}{}{\addtolength{\textheight}{#1}}%
  \@ifmtarg{#2}{}{\addtolength{\textwidth}{#2}}%
  \@ifmtarg{#3}{}{\addtolength{\evensidemargin}{#3}}%
  \@ifmtarg{#4}{}{\addtolength{\oddsidemargin}{#4}}%
  \@ifmtarg{#5}{}{\addtolength{\columnsep}{#5}}%
  \ch@ngetext}

%    \end{macrocode}
% \end{macro}
%
% Any given change lasts until another \cs{changetext} command is given.
% A \cs{changetext} command should only be issued between two paragraphs.
%
% \cs{changetext} should not be used by anyone unless they really
% know what they are doing. If you really know what you are doing
% then you should know enough not to use it.
%
% \begin{macro}{\changepage}
% Change the page layout, but DON'T.
% \changes{v1.61803}{2008/01/30}{Added \cs{changepage} to match chngpage.sty}
%    \begin{macrocode}
\DeclareRobustCommand{\changepage}[9]{%
  \@ifmtarg{#1}{}{\addtolength{\textheight}{#1}}%
  \@ifmtarg{#2}{}{\addtolength{\textwidth}{#2}}%
  \@ifmtarg{#3}{}{\addtolength{\evensidemargin}{#3}}%
  \@ifmtarg{#4}{}{\addtolength{\oddsidemargin}{#4}}%
  \@ifmtarg{#5}{}{\addtolength{\columnsep}{#5}}%
  \ch@ngetext
  \@ifmtarg{#6}{}{\addtolength{\topmargin}{#6}}%  
  \@ifmtarg{#7}{}{\addtolength{\headheight}{#7}}%  
  \@ifmtarg{#8}{}{\addtolength{\headsep}{#8}}%  
  \@ifmtarg{#9}{}{\addtolength{\footskip}{#9}}}  

%    \end{macrocode}
% \end{macro}
%
% \subsection{Temporarily changing the text width}
%
%
% \begin{environment}{adjustwidth}
% \begin{environment}{adjustwidth*}
% \verb?\begin{adjustwidth}?\marg{left}\marg{right}
% adds the given lengths to the left and right hand margins. A positive
% value will shorten the text and a negative value will widen it. The
% starred version of the environment will cause the
% margin changes to switch between odd and even pages.
%
% This code is based on the \Lpack{chngpage} package.
% \changes{v0.2}{2001/06/03}{Replaced optional arg of adjustwidth by adjustwidth*}
%    \begin{macrocode}
\newenvironment{adjustwidth}[2]{%
  \begin{list}{}{%
    \topsep\z@%
    \listparindent\parindent%
    \parsep\parskip%
    \@ifmtarg{#1}{\setlength{\leftmargin}{\z@}}%
                 {\setlength{\leftmargin}{#1}}%
    \@ifmtarg{#2}{\setlength{\rightmargin}{\z@}}%
                 {\setlength{\rightmargin}{#2}}%
    }
    \item[]}{\end{list}}

%    \end{macrocode}
%
%    \begin{macrocode}
\newenvironment{adjustwidth*}[2]{%
  \begin{list}{}{%
    \topsep\z@%
    \listparindent\parindent%
    \parsep\parskip%
    \checkoddpage
    \ifoddpage  % odd numbered page
      \@ifmtarg{#1}{\setlength{\leftmargin}{\z@}}%
                   {\setlength{\leftmargin}{#1}}%
      \@ifmtarg{#2}{\setlength{\rightmargin}{\z@}}%
                   {\setlength{\rightmargin}{#2}}%
    \else       % even numbered page
      \@ifmtarg{#2}{\setlength{\leftmargin}{\z@}}%
                   {\setlength{\leftmargin}{#2}}%
      \@ifmtarg{#1}{\setlength{\rightmargin}{\z@}}%
                   {\setlength{\rightmargin}{#1}}%
    \fi
    }
    \item[]}{\end{list}}

%    \end{macrocode}
% \end{environment}
% \end{environment}
%
%  The environments only work for complete paragraphs.
%
% \subsection{Centering text}
%
% \begin{macro}{\calccentering}
% This macro calculates the amount to be added to the spine margin
% (and subtracted from the foredge margin) 
% in order to center the textblock. Call as \\
% \verb?\calccentering{\length}? and it sets \cs{length}
% to the required value. Then use as \\
% \verb?\begin{adjustwidth*}{\length}{-\length}...?
%    \begin{macrocode}
\newcommand{\calccentering}[1]{
  #1 = \paperwidth
  \advance #1 by -\textwidth
  \divide #1 by \tw@
  \advance #1 by -\spinemargin}

%    \end{macrocode}
% \end{macro}
%
% \begin{environment}{vplace}
% \verb?\begin{vplace}?\oarg{decimal number} centers its body vertically. The
% optional argument \meta{decimal number} increases ($>1.0$) or decreases
% ($<1.0$) the space above the body with respect to the space below.
% This is more robust than the method proposed in the manual.
% \changes{v1.61803}{2008/01/30}{Added vplace environment (mempatch v4.4)}
% \changes{v3.6g}{2010/08/27}{Both should be \cs{vspace*}}
%    \begin{macrocode}
\newenvironment{vplace}[1][1]{%
  \par\vspace*{\stretch{#1}}%
}{%
  \vspace*{\stretch{1}}%
  \par}

%    \end{macrocode}
% \end{environment}
%
%
% \subsection{Moving from the current page}
%
% Much of this code is taken from the \Lpack{nextpage} package~\cite{NEXTPAGE}.
%
% Clear to next page is \cs{clearpage}.
%
% \begin{macro}{\cleartoevenpage}
%  \cs{cleartoevenpage}\oarg{text} clears to the next even 
% numbered page, 
%  putting the optional \meta{text} on the skipped page, if any.
%    \begin{macrocode}
\newcommand{\cleartoevenpage}[1][\@empty]{%
  \clearpage%
  \ifodd\c@page\hbox{}#1\clearpage\fi}

%    \end{macrocode}
% \end{macro}
%
% Move to the next page without flushing floats is \cs{newpage}.
%
% \begin{macro}{\movetoevenpage}
%  \cs{movetoevenpage}\oarg{text} moves to the next even 
% numbered page without flushing floats, 
%  putting the optional \meta{text} on the skipped page, if any.
%    \begin{macrocode}
\newcommand{\movetoevenpage}[1][\@empty]{%
  \newpage%
  \ifodd\c@page\hbox{}#1\newpage\fi}

%    \end{macrocode}
% \end{macro}
%
% Clear to next odd numbered page is \cs{cleardoublepage}.
%
% \begin{macro}{\cleartooddpage}
%  \cs{cleartooddpage}\oarg{text} clears to the next odd
% numbered page, 
%  putting the optional \meta{text} on the skipped page, if any.
%    \begin{macrocode}
\newcommand{\cleartooddpage}[1][\@empty]{%
  \clearpage%
  \ifodd\c@page\else\hbox{}#1\clearpage\fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\movetooddpage}
%  \cs{movetooddpage}\oarg{text} moves to the next odd
% numbered page without flushing floats, 
%  putting the optional \meta{text} on the skipped page, if any.
%    \begin{macrocode}
\newcommand{\movetooddpage}[1][\@empty]{%
  \newpage%
  \ifodd\c@page\else\hbox{}#1\newpage\fi}

%    \end{macrocode}
% \end{macro}
%
% Example uses: \\
% \begin{verbatim}
% \cleartooddpage                         % same as \cleardouble page
% \cleartooddpage[\thispagestyle{empty}]  % No headings on the skipped page
% \cleartoevenpage                        % go to next even numbered page
% Next example puts text on a skipped page
% \cleartoevenpage[\vspace*{\hfill}THIS PAGE LEFT BLANK\vspace*{\hfill}]
% \end{verbatim}
%
%
%
% \subsection{Needing space at the bottom of a page}
%
% \begin{macro}{\needspace}
% \cs{needspace}\marg{length} checks if the is \meta{length} amount
% of vertical space left on the page. If there is not it will start
% a new page. The code is a variant of code thought of for the 
% \Lpack{needspace} package~\cite{NEEDSPACE}.
% \changes{v1.4}{2003/11/16}{Added patch v1.4 versions of needspace macros}
% \changes{v3.6g}{2010/09/09}{Added a \cs{vskip0pt} at the end to make
% it work better with \cs{section} and friends}
%    \begin{macrocode}
\newcommand{\needspace}[1]{\begingroup\setlength{\dimen@}{#1}%
  \vskip\z@\@plus\dimen@\penalty -100\vskip\z@\@plus-\dimen@
  \vskip\dimen@\penalty 9999\vskip-\dimen@\vskip\z@skip\endgroup}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\Needspace}
% \begin{macro}{\Needspace*}
% \cs{Needspace} and \cs{Needspace*} are more robust versions of \cs{needspace},
% which depends on penalties. If either \cs{needspace} or \cs{Needspace}
% produce a short page it will be ragged bottom, even if \cs{flushbottom}
% is in effect. The \cs{Needspace*} version honours the \cs{...bottom}
% declaration.
%    \begin{macrocode}    
\newcommand{\Needspace}{\@ifstar{\M@sneedsp@}{\M@needsp@}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\M@sneedsp@}
% \begin{macro}{\M@needsp@}
% These implement \cs{Needspace*} and \cs{needspace} respectively.
%    \begin{macrocode}    
\newcommand{\M@sneedsp@}[1]{\par \penalty-100\begingroup
  \setlength{\dimen@}{#1}%
  \dimen@ii\pagegoal \advance\dimen@ii-\pagetotal
  \ifdim \dimen@>\dimen@ii
    \break
  \fi\endgroup}
\newcommand{\M@needsp@}[1]{\par \penalty-100\begingroup
  \setlength{\dimen@}{#1}%
  \dimen@ii\pagegoal \advance\dimen@ii-\pagetotal
  \ifdim \dimen@>\dimen@ii
    \ifdim \dimen@ii>\z@
      \vfil
    \fi
    \break
  \fi\endgroup}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \subsection{Overlong lines}
%
% LaTeX provides \cs{fussy} and \cs{sloppy} to control the amount of slack
% in a line while trying to make justified lines. Their definitions are:
% \begin{verbatim}
% \def\fussy{%
%   \emergencystretch\z@
%   \tolerance 200%
%   \hfuzz .1\p@
%   \vfuzz\hfuzz}
% \def\sloppy{%
%   \tolerance 9999%
%   \emergencystretch 3em%
%   \hfuzz .5\p@
%   \vfuzz\hfuzz}
% \end{verbatim}
%
% \begin{macro}{\midsloppy}
% Somewhere between \cs{fussy} and \cs{sloppy}.
% \changes{v1.61803}{2008/01/30}{Added \cs{midsloppy} and midsloppypar
%                   (mempatch v4.5)}
%    \begin{macrocode}
\newcommand*{\midsloppy}{%
  \tolerance 5000%
  \hbadness 4000%
  \emergencystretch 1.5em%
  \hfuzz .1\p@
  \vfuzz\hfuzz}
%    \end{macrocode}
% \end{macro}
%
% \begin{environment}{midsloppypar}
% A paragraph form of \cs{midsloppy}; equivalent to \verb?\par \midsloppy ... \par}?
%    \begin{macrocode}
\newenvironment{midsloppypar}{\par\midsloppy}{\par}

%    \end{macrocode}
% \end{environment}
%
% \subsection{Text spacing commands}
%
% While we're at it, new text spacing commands to supplement
% the kernel's \\
% \verb?\, (\thinspace) = 3/18 em?
% \changes{v1.4}{2003/11/16}{Extra text spacing macros from patch v1.4}
% \changes{v3.7l}{2020/06/02}{Added kernel wrapper}
% As of the kernel/format update for october 2020, these will be moved
% to the kernel, so we remove them of you are using that kernel.
%    \begin{macrocode}
\@ifl@t@r\fmtversion{2020-10-01}{
  % nothing to do with newer kernel
}{%
%    \end{macrocode}
% \begin{macro}{\medspace}
% \begin{macro}{\:}
% Medium space \verb?\: (\medspace) = 4/18 em?
% \changes{v3.7q}{2022/02/17}{use \cs{providecommand} on \cs{medspace}}
%    \begin{macrocode}    
\providecommand{\medspace}{\kern .22222em }
\DeclareRobustCommand{\:}{%
  \relax\ifmmode\mskip\medmuskip\else\medspace\fi}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\!}
% Negative thin space (- 3/18 em).
% Patrik Nyman (private email 2003/10/06) pointed out I had missed
% the final \verb?\fi? !!!!. 
%    \begin{macrocode}
\DeclareRobustCommand{\!}{%
  \relax\ifmmode\mskip-\thinmuskip\else\negthinspace\fi}

} % end kernel version wrapper
%    \end{macrocode}
% \end{macro}
%
% \subsection{Fractions and subscripts}
%
%
% Styles for fractions like 3/4 (but better).
%
% \begin{macro}{\slashfracstyle}
% \cs{slashfracstyle} based on the kernel \cs{textsuperscript} macro
% \changes{v1.4}{2003/11/16}{Added \cs{slashfrac} and supports (from patch v1.4)}
%    \begin{macrocode}    
\DeclareRobustCommand*{\slashfracstyle}[1]{%
  {\m@th\ensuremath{\mbox{\fontsize\sf@size\z@\selectfont #1}}}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\slashfrac}
% \cs{slashfrac} based on TeXbook exercise 11.6
%    \begin{macrocode}    
\DeclareRobustCommand*{\slashfrac}[2]{\leavevmode
  \raise.5ex\hbox{\slashfracstyle{#1}}\kern-.13em/%
  \kern-.15em\lower.25ex\hbox{\slashfracstyle{#2}}}

%    \end{macrocode}
% \end{macro}
%
%
%  \subsection{Numbers to names}
%
%    \begin{macrocode}
%%%%%%%%%%%%%%%%%%%% number formatting

%    \end{macrocode}
%
% The macros here convert an integer number in the range 0--2147483647
% (TeX's maximum) into
% the natural language name of the number.
% \changes{v1.4}{2003/11/16}{Much extended numbers to names (patch v1.2)}
%
% \begin{macro}{\iflowernumtoname}
% A flag for lowercasing the initial letters.
%    \begin{macrocode}
\newif\iflowernumtoname
  \lowernumtonamefalse
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ifpriornum}
% \begin{macro}{\ifminusnumber}
% \begin{macro}{\ifnotnumtonameallcaps}
% \begin{macro}{\ifmakeordinal}
% Some new booleans
%    \begin{macrocode}
\newif\ifpriornum
\newif\ifminusnumber
\newif\ifnotnumtonameallcaps
\newif\ifmakeordinal

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\namenumberand}
% \begin{macro}{\namenumbercomma}
% \begin{macro}{\lcminusname}
% \begin{macro}{\ucminusname}
% \begin{macro}{\minusname}
% Some macros representing characters/words for number formatting.
%    \begin{macrocode}
\newcommand*{\namenumberand}{ and }
\newcommand*{\namenumbercomma}{, }
\newcommand*{\lcminusname}{minus }
\newcommand*{\ucminusname}{Minus }
\let\minusname\lcminusname
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\fnumbersep}
% \begin{macro}{\tensunitsep}
% \begin{macro}{\nthstring}
% \begin{macro}{\iststring}
% \begin{macro}{\iindstring}
% \begin{macro}{\iiirdstring}
% \begin{macro}{\tiethstring}
% \begin{macro}{\teenstring}
% More characters/words for formatting
%    \begin{macrocode}
\newcommand*{\fnumbersep}{,}
\newcommand*\tensunitsep{-}
\newcommand*{\nthstring}{th}      % nth
\newcommand*{\iststring}{st}      % 1st
\newcommand*{\iindstring}{nd}     % 2nd
\newcommand*{\iiirdstring}{rd}    % 3rd
\newcommand*{\tiethstring}{tieth} % tieth
\newcommand*{\teenstring}{teen}   % teen
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\ordscript}
% How to format the ordinal string
%    \begin{macrocode}
\newcommand{\ordscript}[1]{#1}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@mten}
% An internal shorthand for 10
%    \begin{macrocode}
\chardef\m@mten=10 % shorthand for 10

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\c@ism@mctr}
% \begin{macro}{\c@xsm@mctr}
% \begin{macro}{\c@csm@mctr}
% \begin{macro}{\c@ksm@mctr}
% \begin{macro}{\c@xksm@mctr}
% Counters for digits (units to ten thousands) in a number
%    \begin{macrocode}
\newcounter{ism@mctr}  % units
\newcounter{xsm@mctr}  % tens
\newcounter{csm@mctr}  % hundreds
\newcounter{ksm@mctr}  % thousands
\newcounter{xksm@mctr} % ten thousands
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\c@cksm@mctr}
% \begin{macro}{\c@msm@mctr}
% \begin{macro}{\c@xmsm@mctr}
% \begin{macro}{\c@cmsm@mctr}
% \begin{macro}{\c@bsm@mctr}
% Counters for digits (hundred thousands to billions) in a number
%    \begin{macrocode}
\newcounter{cksm@mctr} % hundred thousands
\newcounter{msm@mctr}  % millions
\newcounter{xmsm@mctr} % ten millions
\newcounter{cmsm@mctr} % hundred millions
\newcounter{bsm@mctr}  % billions
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\c@workm@mctr}
% A `work' counter.
%    \begin{macrocode}
\newcounter{workm@mctr}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\numdigits}
% \cs{numdigits}\marg{number} splits the \meta{number} into individual digits.
% It sets \cs{minusnumbertrue} if the number is negative, otherwise it is false.
%    \begin{macrocode}
\newcommand*{\numdigits}[1]{%
  \setcounter{ism@mctr}{0}%
  \setcounter{xsm@mctr}{0}%
  \setcounter{csm@mctr}{0}%
  \setcounter{ksm@mctr}{0}%
  \setcounter{xksm@mctr}{0}%
  \setcounter{cksm@mctr}{0}%
  \setcounter{msm@mctr}{0}%
  \setcounter{xmsm@mctr}{0}%
  \setcounter{cmsm@mctr}{0}%
  \setcounter{bsm@mctr}{0}%
  \setcounter{workm@mctr}{#1}%
  \minusnumberfalse
  \ifnum \c@workm@mctr < \z@  % negative
    \minusnumbertrue
    \c@workm@mctr = -\c@workm@mctr
  \fi
  \ifnum \c@workm@mctr > \m@ne     % units
    \c@ism@mctr = \c@workm@mctr
    \divide \c@workm@mctr by \m@mten
    \multiply \c@workm@mctr by \m@mten
    \advance \c@ism@mctr by -\c@workm@mctr
    \divide \c@workm@mctr by \m@mten
  \fi
  \ifnum \c@workm@mctr > \z@    % tens
    \c@xsm@mctr = \c@workm@mctr
    \divide \c@workm@mctr by \m@mten
    \multiply \c@workm@mctr by \m@mten
    \advance \c@xsm@mctr by -\c@workm@mctr
    \divide \c@workm@mctr by \m@mten
  \fi
  \ifnum \c@workm@mctr > \z@   % hundreds
    \c@csm@mctr = \c@workm@mctr
    \divide \c@workm@mctr by \m@mten
    \multiply \c@workm@mctr by \m@mten
    \advance \c@csm@mctr by -\c@workm@mctr
    \divide \c@workm@mctr by \m@mten
  \fi
  \ifnum \c@workm@mctr > \z@   % thousands
    \c@ksm@mctr = \c@workm@mctr
    \divide \c@workm@mctr by \m@mten
    \multiply \c@workm@mctr by \m@mten
    \advance \c@ksm@mctr by -\c@workm@mctr
    \divide \c@workm@mctr by \m@mten
  \fi
  \ifnum \c@workm@mctr > \z@   % ten thousands
    \c@xksm@mctr = \c@workm@mctr
    \divide \c@workm@mctr by \m@mten
    \multiply \c@workm@mctr by \m@mten
    \advance \c@xksm@mctr by -\c@workm@mctr
    \divide \c@workm@mctr by \m@mten
  \fi
  \ifnum \c@workm@mctr > \z@   % hundred thousands
    \c@cksm@mctr = \c@workm@mctr
    \divide \c@workm@mctr by \m@mten
    \multiply \c@workm@mctr by \m@mten
    \advance \c@cksm@mctr by -\c@workm@mctr
    \divide \c@workm@mctr by \m@mten
  \fi
  \ifnum \c@workm@mctr > \z@   % millions
    \c@msm@mctr = \c@workm@mctr
    \divide \c@workm@mctr by \m@mten
    \multiply \c@workm@mctr by \m@mten
    \advance \c@msm@mctr by -\c@workm@mctr
    \divide \c@workm@mctr by \m@mten
  \fi
  \ifnum \c@workm@mctr > \z@  % ten millions
    \c@xmsm@mctr = \c@workm@mctr
    \divide \c@workm@mctr by \m@mten
    \multiply \c@workm@mctr by \m@mten
    \advance \c@xmsm@mctr by -\c@workm@mctr
    \divide \c@workm@mctr by \m@mten
  \fi
  \ifnum \c@workm@mctr > \z@  % hundred millions
    \c@cmsm@mctr = \c@workm@mctr
    \divide \c@workm@mctr by \m@mten
    \multiply \c@workm@mctr by \m@mten
    \advance \c@cmsm@mctr by -\c@workm@mctr
    \divide \c@workm@mctr by \m@mten
  \fi
  \ifnum \c@workm@mctr > \z@% billions
    \c@bsm@mctr = \c@workm@mctr
    \divide \c@workm@mctr by \m@mten
    \multiply \c@workm@mctr by \m@mten
    \advance \c@bsm@mctr by -\c@workm@mctr
  \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\form@tnumber}
% \cs{form@tnumber}\marg{number} formats \meta{number} as digits.
%    \begin{macrocode}
\newcommand*{\form@tnumber}[1]{%
  \numdigits{#1}%
  \ifminusnumber-\fi
  \priornumfalse
  \ifnum \c@bsm@mctr > \z@ % billions
    \priornumtrue
    \thebsm@mctr\fnumbersep
  \fi
  \ifpriornum                 % hundred millions
    \thecmsm@mctr
  \else
    \ifnum \c@cmsm@mctr > \z@
      \priornumtrue
      \thecmsm@mctr
    \fi
  \fi
  \ifpriornum                 % ten millions
    \thexmsm@mctr
  \else
    \ifnum \c@xmsm@mctr > \z@
      \priornumtrue
      \thexmsm@mctr
    \fi
  \fi
  \ifpriornum                 % millions
    \themsm@mctr\fnumbersep
  \else
    \ifnum \c@msm@mctr > \z@
      \priornumtrue
      \themsm@mctr\fnumbersep
    \fi
  \fi
  \ifpriornum                % hundred thousands
    \thecksm@mctr
  \else
    \ifnum \c@cksm@mctr > \z@
      \priornumtrue
      \thecksm@mctr
    \fi
  \fi
  \ifpriornum                % ten thousands
    \thexksm@mctr
  \else
    \ifnum \c@xksm@mctr > \z@
      \priornumtrue
      \thexksm@mctr
    \fi
  \fi
  \ifpriornum                % thousands
    \theksm@mctr\fnumbersep
  \else
    \ifnum \c@ksm@mctr > \z@
      \priornumtrue
      \theksm@mctr\fnumbersep
    \fi
  \fi
  \ifpriornum                % hundreds
    \thecsm@mctr
  \else
    \ifnum \c@csm@mctr > \z@
      \priornumtrue
      \thecsm@mctr
    \fi
  \fi
  \ifpriornum                % tens
    \thexsm@mctr
  \else
    \ifnum \c@xsm@mctr > \z@
      \priornumtrue
      \thexsm@mctr
    \fi
  \fi
  \theism@mctr}              % units

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\cardinal}
% \cs{cardinal}\marg{number} prints \meta{number} unformatted.
%    \begin{macrocode}
\newcommand*{\cardinal}[1]{%
  \begingroup
  \let\fnumbersep\relax
  \form@tnumber{#1}%
  \endgroup}
%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\fcardinal}
% \cs{fcardinal}\marg{number} prints \meta{number} formatted.
%    \begin{macrocode}
\newcommand*{\fcardinal}[1]{%
  \begingroup
  \form@tnumber{#1}%
  \endgroup}
  
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ordinal}
% \cs{ordinal}\marg{number} prints \meta{number} as an unformatted ordinal.
%    \begin{macrocode}
\newcommand*{\ordinal}[1]{%
  \begingroup
  \let\fnumbersep\relax
  \form@tnumber{#1}%
  \let\ordstring\nthstring
  \ifnum \c@xsm@mctr=\@ne\else
    \ifcase \c@ism@mctr
      \or \let\ordstring\iststring%    1st
      \or \let\ordstring\iindstring%   2nd
      \or \let\ordstring\iiirdstring%  3rd
    \fi
  \fi
  \ordscript{\ordstring}%
  \endgroup
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\fordinal}
% \cs{fordinal}\marg{number} prints \meta{number} as a formatted ordinal.
%    \begin{macrocode}
\newcommand*{\fordinal}[1]{%
  \begingroup
  \form@tnumber{#1}%
  \let\ordstring\nthstring
  \ifnum \c@xsm@mctr=\@ne\else
    \ifcase \c@ism@mctr
      \or \let\ordstring\iststring%    1st
      \or \let\ordstring\iindstring%   2nd
      \or \let\ordstring\iiirdstring%  3rd
    \fi
  \fi
  \ordscript{\ordstring}%
  \endgroup
}

%    \end{macrocode}
% \end{macro}
%
% The next, tedious, code is for translating numbers into names.
%
% \begin{macro}{\nNameo}
% \begin{macro}{\nNamec}
% \begin{macro}{\nNamem}
% \begin{macro}{\nNamemm}
% \begin{macro}{\nNamemmm}
% Names of major numbers: $0$, $10^{2}$, $10^{3}$, $10^{6}$, and $10^{9}$.
%    \begin{macrocode}
\newcommand*\nNameo{\iflowernumtoname z\else Z\fi ero}
\newcommand*\nNamec{\iflowernumtoname h\else H\fi undred}
\newcommand*\nNamem{\iflowernumtoname t\else T\fi housand}
\newcommand*\nNamemm{\iflowernumtoname m\else M\fi illion}
\newcommand*\nNamemmm{\iflowernumtoname b\else B\fi illion}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\nNamei}
% \begin{macro}{\nNameii}
% \begin{macro}{\nNameiii}
% \begin{macro}{\nNameiv}
% \begin{macro}{\nNamev}
%    These are the names for numbers 1 to 5.
%    \begin{macrocode}
\newcommand*\nNamei{\iflowernumtoname o\else O\fi ne}
\newcommand*\nNameii{\iflowernumtoname t\else T\fi wo}
\newcommand*\nNameiii{\iflowernumtoname t\else T\fi hree}
\newcommand*\nNameiv{\iflowernumtoname f\else F\fi our}
\newcommand*\nNamev{\iflowernumtoname f\else F\fi ive}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\nNamevi}
% \begin{macro}{\nNamevii}
% \begin{macro}{\nNameviii}
% \begin{macro}{\nNameix}
% \begin{macro}{\nNamex}
%    These are the names for numbers 6 to 10.
%    \begin{macrocode}
\newcommand*\nNamevi{\iflowernumtoname s\else S\fi ix}
\newcommand*\nNamevii{\iflowernumtoname s\else S\fi even}
\newcommand*\nNameviii{\iflowernumtoname e\else E\fi ight}
\newcommand*\nNameix{\iflowernumtoname n\else N\fi ine}
\newcommand*\nNamex{\iflowernumtoname t\else T\fi en}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\nNamexi}
% \begin{macro}{\nNamexii}
% \begin{macro}{\nNamexiii}
% \begin{macro}{\nNamexiv}
% \begin{macro}{\nNamexv}
%    These are the names for numbers 11 to 15.
%    \begin{macrocode}
\newcommand*\nNamexi{\iflowernumtoname e\else E\fi leven}
\newcommand*\nNamexii{\iflowernumtoname t\else T\fi welve}
\newcommand*\nNamexiii{\iflowernumtoname t\else T\fi hir\teenstring}
\newcommand*\nNamexiv{\iflowernumtoname f\else F\fi our\teenstring}
\newcommand*\nNamexv{\iflowernumtoname f\else F\fi if\teenstring}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\nNamexvi}
% \begin{macro}{\nNamexvii}
% \begin{macro}{\nNamexviii}
% \begin{macro}{\nNamexix}
% \begin{macro}{\nNamexx}
%    These are the names for numbers 16 to 20.
%    \begin{macrocode}
\newcommand*\nNamexvi{\iflowernumtoname s\else S\fi ix\teenstring}
\newcommand*\nNamexvii{\iflowernumtoname s\else S\fi even\teenstring}
\newcommand*\nNamexviii{\iflowernumtoname e\else E\fi igh\teenstring}
\newcommand*\nNamexix{\iflowernumtoname n\else N\fi ine\teenstring}
\newcommand*\nNamexx{\iflowernumtoname t\else T\fi wenty}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\nNamexxx}
% \begin{macro}{\nNamexl}
% \begin{macro}{\nNamel}
% \begin{macro}{\nNamelx}
% \begin{macro}{\nNamelxx}
%    These are the names for numbers 30 to 70.
%    \begin{macrocode}
\newcommand*\nNamexxx{\iflowernumtoname t\else T\fi hirty}
\newcommand*\nNamexl{\iflowernumtoname f\else F\fi orty}
\newcommand*\nNamel{\iflowernumtoname f\else F\fi ifty}
\newcommand*\nNamelx{\iflowernumtoname s\else S\fi ixty}
\newcommand*\nNamelxx{\iflowernumtoname s\else S\fi eventy}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\nNamelxxx}
% \begin{macro}{\nNamexc}
%    These are the names for numbers 80 to 90.
%    \begin{macrocode}
\newcommand*\nNamelxxx{\iflowernumtoname e\else E\fi ighty}
\newcommand*\nNamexc{\iflowernumtoname n\else N\fi inety}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
%
% \begin{macro}{\unitnumbername}
% Get the name of a unit (0 -- 9).
%    \begin{macrocode}
\newcommand*{\unitnumbername}[1]{%
  \ifcase #1 \nNameo\or
   \nNamei\or
   \nNameii\or
   \nNameiii\or
   \nNameiv\or
   \nNamev\or
   \nNamevi\or
   \nNamevii\or
   \nNameviii\or
   \nNameix\fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\teennumbername}
% Get the name of a 'teen number (10 -- 19)
%    \begin{macrocode}
\newcommand*{\teennumbername}[1]{%
  \ifcase #1 \nNamex\or
   \nNamexi\or
   \nNamexii\or
   \nNamexiii\or
   \nNamexiv\or
   \nNamexv\or
   \nNamexvi\or
   \nNamexvii\or
   \nNamexviii\or
   \nNamexix\fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\tensnumbername}
% Get the name of a tens number (20 -- 90)
%    \begin{macrocode}
\newcommand*{\tensnumbername}[2]{%
  \ifnum #1=\@ne
    \teennumbername{#2}\ifnotnumtonameallcaps\lowernumtonametrue\fi
  \else
    \ifcase #1
    \or
    \or \nNamexx
    \or \nNamexxx
    \or \nNamexl
    \or \nNamel
    \or \nNamelx
    \or \nNamelxx
    \or \nNamelxxx
    \or \nNamexc
    \fi
    \ifnotnumtonameallcaps\lowernumtonametrue\fi
    \ifnum #2 > \z@ \tensunitsep\unitnumbername{#2}\fi
  \fi}

%    \end{macrocode}
% \end{macro}
%
% Names of small ordinals. The use of \cs{nthstring} instead of `th' saves
% some tokens.
%    \begin{macrocode}
\newcommand*\nthNameo{\nNameo\nthstring}
\newcommand*\nthNamei{\iflowernumtoname f\else F\fi irst}
\newcommand*\nthNameii{\iflowernumtoname s\else S\fi econd}
\newcommand*\nthNameiii{\iflowernumtoname t\else T\fi hird}
\newcommand*\nthNameiv{\nNameiv\nthstring}
\newcommand*\nthNamev{\iflowernumtoname f\else F\fi if\nthstring}
\newcommand*\nthNamevi{\nNamevi\nthstring}
\newcommand*\nthNamevii{\nNamevii\nthstring}
\newcommand*\nthNameviii{\iflowernumtoname e\else E\fi igh\nthstring}
\newcommand*\nthNameix{\iflowernumtoname n\else N\fi in\nthstring}
\newcommand*\nthNamexii{\iflowernumtoname t\else T\fi welf\nthstring}

%    \end{macrocode}
%
% \begin{macro}{\unitordinalname}
% Get the ordinal name of a unit (0 -- 9)
%    \begin{macrocode}
\newcommand*{\unitordinalname}[1]{%
  \ifcase #1 \nthNameo\or
  \nthNamei\or
  \nthNameii\or
  \nthNameiii\or
  \nthNameiv\or
  \nthNamev\or
  \nthNamevi\or
  \nthNamevii\or
  \nthNameviii\or
  \nthNameix\fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\teenordinalname}
% Get the ordinal name of a 'teen number (10 -- 19). Using \cs{nthstring}
% instead of `th' to save some tokens.
%    \begin{macrocode}
\newcommand*{\teenordinalname}[1]{%
  \ifcase #1 \nNamex\nthstring\or
  \nNamexi\nthstring\or
  \nthNamexii\or
  \nNamexiii\nthstring\or
  \nNamexiv\nthstring\or
  \nNamexv\nthstring\or
  \nNamexvi\nthstring\or
  \nNamexvii\nthstring\or
  \nNamexviii\nthstring\or
  \nNamexix\nthstring\fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\tensordinalname}
% Get the ordinal name of a tens number (20 -- 90)
% (Mathew Dafilis) sent Email on 2003/11/14
% saying that \cs{ordinaltoname} didn't work for 20, 30, etc. He was
% correct. It is now fixed.
%    \begin{macrocode}
\newcommand*{\tensordinalname}[2]{%
  \ifnum #1=\@ne
    \teenordinalname{#2}\ifnotnumtonameallcaps\lowernumtonametrue\fi
  \else
    \ifnum #2> \z@
      \ifcase #1
      \or 
      \or \nNamexx
      \or \nNamexxx
      \or \nNamexl
      \or \nNamel
      \or \nNamelx
      \or \nNamelxx
      \or \nNamelxxx
      \or \nNamexc
      \fi
      \ifnotnumtonameallcaps\lowernumtonametrue\fi
      \tensunitsep\unitordinalname{#2}
    \else
      \ifcase #1
      \or 
      \or \nthNamexx
      \or \nthNamexxx
      \or \nthNamexl
      \or \nthNamel
      \or \nthNamelx
      \or \nthNamelxx
      \or \nthNamelxxx
      \or \nthNamexc
      \fi
      \ifnotnumtonameallcaps\lowernumtonametrue\fi
    \fi
  \fi}
  
%    \end{macrocode}
% \end{macro}
%
%    The names of tens ordinals. The use of \cs{tiethstring} instead
% of `tieth' saves somes tokens.
%    \begin{macrocode}
\newcommand*\nthNamexx{\iflowernumtoname t\else T\fi wen\tiethstring}
\newcommand*\nthNamexxx{\iflowernumtoname t\else T\fi hir\tiethstring}
\newcommand*\nthNamexl{\iflowernumtoname f\else F\fi or\tiethstring}
\newcommand*\nthNamel{\iflowernumtoname f\else F\fi if\tiethstring}
\newcommand*\nthNamelx{\iflowernumtoname s\else S\fi ix\tiethstring}
\newcommand*\nthNamelxx{\iflowernumtoname s\else S\fi even\tiethstring}
\newcommand*\nthNamelxxx{\iflowernumtoname e\else E\fi igh\tiethstring}
\newcommand*\nthNamexc{\iflowernumtoname n\else N\fi ine\tiethstring}

%    \end{macrocode}
%
% \begin{macro}{\n@me@number}
% \cs{n@me@number}\marg{number} is an internal macro to convert a 
% \meta{number} to names.
%    \begin{macrocode}
\newcommand*{\n@me@number}[1]{%
\begingroup
    \numdigits{#1}%
    \ifminusnumber\minusname\fi
    \priornumfalse
%% billions
    \ifnum \c@bsm@mctr > \z@
      \unitnumbername{\thebsm@mctr}\space
      \ifnotnumtonameallcaps\lowernumtonametrue\fi\nNamemmm
      \priornumtrue
    \fi
%% hundred millions
    \ifnum \c@cmsm@mctr > \z@
      \ifpriornum\namenumbercomma\fi
      \unitnumbername{\thecmsm@mctr}\space
      \ifnotnumtonameallcaps\lowernumtonametrue\fi\nNamec
      \priornumtrue
    \fi
%% tens/units millions
    \ifnum \c@xmsm@mctr > \z@
      \ifpriornum
        \ifnum\c@cmsm@mctr>\z@\namenumberand\else\namenumbercomma\fi
      \fi
      \tensnumbername{\thexmsm@mctr}{\themsm@mctr}%
      \priornumtrue
    \else
      \ifnum \c@msm@mctr > \z@
        \ifpriornum
          \ifnum\c@cmsm@mctr>\z@\namenumberand\else\namenumbercomma\fi
        \fi
        \unitnumbername{\themsm@mctr}%
        \ifnotnumtonameallcaps\lowernumtonametrue\fi
        \priornumtrue
      \fi
    \fi
    \ifnum \c@cmsm@mctr > \z@
      \ifpriornum\space\fi
      \nNamemm
    \else
      \ifnum \c@xmsm@mctr > \z@
        \ifpriornum\space\fi
        \nNamemm
      \else
        \ifnum \c@msm@mctr > \z@
          \ifpriornum\space\fi
          \nNamemm
        \fi
      \fi
    \fi
%% hundred thousands
    \ifnum \c@cksm@mctr > \z@
      \ifpriornum\namenumbercomma\fi
      \unitnumbername{\thecksm@mctr}\space
        \ifnotnumtonameallcaps\lowernumtonametrue\fi\nNamec
      \priornumtrue
    \fi
%% tens/units thousands
    \ifnum \c@xksm@mctr > \z@
      \ifpriornum
        \ifnum\c@cksm@mctr>\z@\namenumberand\else\namenumbercomma\fi
      \fi
      \tensnumbername{\thexksm@mctr}{\theksm@mctr}%
      \priornumtrue
    \else
      \ifnum \c@ksm@mctr > \z@
        \ifpriornum
          \ifnum\c@cksm@mctr>\z@\namenumberand\else\namenumbercomma\fi
        \fi
        \unitnumbername{\theksm@mctr}%
        \ifnotnumtonameallcaps\lowernumtonametrue\fi
        \priornumtrue
      \fi
    \fi
    \ifnum \c@cksm@mctr > \z@
      \ifpriornum\space\fi
      \nNamem
    \else
      \ifnum \c@xksm@mctr > \z@
        \ifpriornum\space\fi
        \nNamem
      \else
        \ifnum \c@ksm@mctr > \z@
          \ifpriornum\space\fi
          \nNamem
        \fi
      \fi
    \fi
%% hundreds
    \ifnum \c@csm@mctr > \z@
      \ifpriornum\namenumbercomma\fi
      \unitnumbername{\thecsm@mctr}\space
        \ifnotnumtonameallcaps\lowernumtonametrue\fi\nNamec
      \priornumtrue
    \fi
%% tens/units
  \ifmakeordinal
    \ifnum \c@xsm@mctr > \z@
      \ifpriornum\namenumberand\fi
      \tensordinalname{\thexsm@mctr}{\theism@mctr}%
    \else
      \ifnum \c@ism@mctr > \z@
        \ifpriornum\namenumberand\fi
        \unitordinalname{\theism@mctr}%
      \else
        \ifpriornum\nthstring\else\unitordinalname{\theism@mctr}\fi
      \fi
    \fi
  \else  % not ordinal
    \ifnum \c@xsm@mctr > \z@
      \ifpriornum\namenumberand\fi
      \tensnumbername{\thexsm@mctr}{\theism@mctr}%
    \else
      \ifnum \c@ism@mctr > \z@
        \ifpriornum\namenumberand\fi
        \unitnumbername{\theism@mctr}%
      \else
        \ifpriornum\else\unitnumbername{\theism@mctr}\fi
      \fi
    \fi
  \fi % end ifmakeordinal
\endgroup}

%    \end{macrocode}
% \end{macro}
%
% \changes{v1.61803}{2008/01/30}{Made all \cs{(num/ordinal)toname} robust}
% \begin{macro}{\numtoname}
% Lowercase all names
%    \begin{macrocode}
\DeclareRobustCommand{\numtoname}[1]{%
  \makeordinalfalse
  \notnumtonameallcapstrue%
  \lowernumtonametrue%
  \n@me@number{#1}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\numtoName}
% Uppercase first letter of first name (all else lowercase).
%    \begin{macrocode}
\DeclareRobustCommand{\numtoName}[1]{%
  \makeordinalfalse
  \notnumtonameallcapstrue%
  \lowernumtonamefalse%
  \n@me@number{#1}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\NumToName}
% Uppercase first letter of all names (all else lowercase).
%    \begin{macrocode}
\DeclareRobustCommand{\NumToName}[1]{%
  \makeordinalfalse
  \notnumtonameallcapsfalse%
  \lowernumtonamefalse%
  \n@me@number{#1}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ordinaltoname}
% Lowercase all ordinal names
%    \begin{macrocode}
\DeclareRobustCommand{\ordinaltoname}[1]{%
  \makeordinaltrue
  \notnumtonameallcapstrue%
  \lowernumtonametrue%
  \n@me@number{#1}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ordinaltoName}
% Uppercase first letter of first ordinal name (all else lowercase).
%    \begin{macrocode}
\DeclareRobustCommand{\ordinaltoName}[1]{%
  \makeordinaltrue
  \notnumtonameallcapstrue%
  \lowernumtonamefalse%
  \n@me@number{#1}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\OrdinalToName}
% Uppercase first letter of all ordinal names (all else lowercase).
%    \begin{macrocode}
\DeclareRobustCommand{\OrdinalToName}[1]{%
  \makeordinaltrue
  \notnumtonameallcapsfalse%
  \lowernumtonamefalse%
  \n@me@number{#1}}

%    \end{macrocode}
% \end{macro}
%
%
% \subsection{A fix for two column headings}
%
%
% This is from a posting by Donald Arseneau to \ctt{} on 23 April 2001 to fix
% a problem --- `When I use \verb?\onecolumn\chapter...? its headline
% is printed lower on the page than for two-column chapters'
%
% DA and I had previously discussed this in relation to the Index
% and I had put a hack into the \Lpack{tocbibind} package to fix the Index.
%
% Donald posted the following.
%
% \cs{vspace*} gives bad spacing after a pagebreak and \cs{@makechapterhead}
% starts with \cs{vspace*}.
% The biggest problem is the definition of \cs{@topnewpage}, which is used
% for the two-column spanning text. Here is a redefinition:
% \changes{v0.2}{2001/06/03}{Added DA's redefinition of \cs{@topnewpage}}
% \begin{macro}{\@topnewpage}
%    \begin{macrocode}
\long\def \@topnewpage [#1]{%
  \@nodocument
  \@next\@currbox\@freelist{}{}%
  \global \setbox\@currbox
    \vbox {%
      \break
      \prevdepth\z@
      \begingroup
      \normalcolor
      \hsize\textwidth
      \@parboxrestore
      \col@number \@ne
      #1%
      \vskip -\dbltextfloatsep
      \endgroup
      \null % ordinary \baselineskip
      \vskip -\topskip
  }%
  \begingroup %% \showbox\@currbox
    \splitmaxdepth\maxdepth \splittopskip\topskip
    \setbox\@tempboxa \vsplit\@currbox to \z@
  \endgroup %% \showbox\@currbox
  \ifdim \ht\@currbox>\textheight
    \ht\@currbox \textheight
  \fi
  \global \count\@currbox \tw@
  \@tempdima -\ht\@currbox
  \advance \@tempdima -\dbltextfloatsep
  \global \advance \@colht \@tempdima
  \ifx \@dbltoplist \@empty
  \else
    \@latexerr{Float(s) lost}\@ehb
    \let \@dbltoplist \@empty
  \fi
  \@cons \@dbltoplist \@currbox
  \global \@dbltopnum \m@ne
  \ifdim \@colht<2.5\baselineskip
    \@latex@warning@no@line {Optional argument of \noexpand\twocolumn
        too tall on page \thepage}%
    \@emptycol
    \if@firstcolumn
    \else
      \@emptycol
    \fi
  \else
    \global \vsize \@colht
    \global \@colroom \@colht
    \@floatplacement
  \fi}

%    \end{macrocode}
% \end{macro}
%
% The original version of \cs{@topnewpage} is in \file{ltouput.dtx}, line 159.
%
% \subsection{Time of day}
%
% William Adams (2006/08/28) supplied a basis for 
% \cs{printime}, which he needed for \cs{quarkmarks} but I have used one 
% from \textit{TeX for the Impatient} 
% as it saves some counters.
% \changes{v1.61803}{2008/01/30}{Added \cs{printime} and friends (mempatch v4.6)}
% \begin{macro}{\m@mcalchm}
% Calculate the hours and minutes from \cs{time}.
%    \begin{macrocode}
\newcommand*{\m@mcalchm}{%
  \count0 = \time \divide \count0 by 60\relax
  \count2 = \count0\relax%    the hour
  \count4 = \time \multiply\count0 by 60\relax
  \advance\count4 by -\count0\relax% the minute
  \ifnum\count4<10 \toks1 = {0}%  make a leading zero
  \else \toks1 = {}%
  \fi}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\hmpunct}
% \begin{macro}{\amname}
% \begin{macro}{\pmname}
% User format controls for \cs{printtime}
%    \begin{macrocode}
%%% punctuation, am and pm for \printtime
\newcommand*{\hmpunct}{:}% hours minutes separator
\newcommand*{\amname}{am}% ante meridiem
\newcommand*{\pmname}{pm}% post meridiem

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\printtime}
% \begin{macro}{\printtime*}
% Print the time of day as 24 hour clock or 12 hour clock
% \cs{printtime} prints the time par 24 hour clock and \cs{printtime*}
% per 12 hour clock.
%    \begin{macrocode}
\newcommand*{\printtime}{%
  \@ifstar{\m@msprtime}{\m@mprtime}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\m@mprtime}
% \begin{macro}{\m@msprtime}
% These implement time printing: \cs{m@mprtime} as 24 hour clock and
% \cs{m@msprtime} as 12 hour clock
%    \begin{macrocode}
\newcommand*{\m@mprtime}{\begingroup
  \m@mcalchm
  \number\count2\hmpunct\the\toks1 \number\count4
  \endgroup}
\newcommand*{\m@msprtime}{\begingroup
  \m@mcalchm
  \def\@mpm{\pmname}%
  \ifnum\count2<1\relax% early in the morning
    \count2=12\relax
    \ifnum\count4>0\relax% not midnight
      \def\@mpm{\amname}%
    \fi
  \else
    \ifnum\time<721\relax% noon or earlier
      \def\@mpm{\amname}%
    \else
      \ifnum\time>779\relax% 1300 hrs or later
        \advance\count2 by -12\relax
      \fi
    \fi
  \fi
  \number\count2\hmpunct\the\toks1 \number\count4\ \@mpm
  \endgroup}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \subsection{Sequential sheet (page) numbers}
%
% \begin{macro}{\c@sheetsequence}
% Peter Heslin asked for the ability to add a sequential page number
% (1 for the first page, N for the last page, no matter what value
% the page counter has) to the trimming marks.
%
%    \cs{c@sheetsequence} is a new counter for pages starting at the 
% beginning and independent
% of the standard page counter. This should not be reset by anything.
% The counter increment has to be added to the output routine.
%
%     This may also be useful for page N of M numbering.
% \changes{v1.3}{2002/10/10}{Added sheetsequence counter.}
%    \begin{macrocode}
\newcounter{sheetsequence}
  \setcounter{sheetsequence}{1}
  \renewcommand{\thesheetsequence}{\@arabic\c@sheetsequence}
\g@addto@macro{\@outputpage}{\stepcounter{sheetsequence}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\c@lastsheet}
% \begin{macro}{\c@lastpage}
% While we're at it, might as well provide for lastpage and lastsheet counters
% \changes{v1.3}{2002/11/14}{Added lastsheet and lastpage functions.}
%    \begin{macrocode}
\newcounter{lastsheet}
  \setcounter{lastsheet}{0}
\newcounter{lastpage}
  \setcounter{lastpage}{0}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\dol@stsheet}
% \begin{macro}{\dol@stpage}
% These two macros write the values of lastsheet and lastpage to the
% \file{aux} file. They have to be called at the end of the document
% after a \cs{clearpage} to flush out any floats.
% \changes{v1.4}{2003/02/27}{In \cs{dol@stpage} use the page counter value,
%                            not \cs{thepage} otherwise problems with
%                            non-arabic page numbers (patch 1.1)}
% \changes{v1.61}{2004/03/21}{In \cs{dol@stpage} use the sheet counter value,
%                              not \cs{thesheetsequence} otherwise problems
%                              if (e.g., hangul.sty) \cs{@arabic} is redefined}
% \changes{v1.618}{2005/09/02}{Made \cs{dol@stsheet} and \cs{dol@stpage}
%  obey \cs{nofiles}}
% \changes{v1.61803}{2008/01/30}{Made \cs{dol@stsheet} and \cs{dolastpage}
%                    use \cs{memsetcounter} instead of \cs{setcounter}}

%    \begin{macrocode}
\newcommand{\dol@stsheet}{%
  \if@filesw
    \addtocounter{sheetsequence}{-1}%
    \immediate\write\@auxout%
      {\string\memsetcounter{lastsheet}{\the\c@sheetsequence}}%
    \stepcounter{sheetsequence}%
  \fi}
\newcommand{\dol@stpage}{%
  \if@filesw
    \addtocounter{page}{-1}%
    \immediate\write\@auxout%
      {\string\memsetcounter{lastpage}{\the\c@page}}%
    \stepcounter{page}%
  \fi}
%    \end{macrocode}
% I originally used this: \\
% \verb?\AtEndDocument{\clearpage\dol@stsheet\dol@stpage}?
% but following the CTT thread \textit{AtEndDocument produces unwanted page
% break}, 2004/03/11, and in particular Dan Luecking's response I now
% try as hard as possible to do it right at the end, but even this is not
% 100\% reliable. The only way to ensure reliability is to modify the kernel
% \verb?\enddocument? which doesn't seem to be a particularly wise thing
% to do.
% \changes{v1.61}{2004/03/14}{Changed location of calls to \cs{dol@stsheet}
%                             and \cs{dol@stpage}}
%    \begin{macrocode}
\AtBeginDocument{\AtEndDocument{\clearpage\dol@stsheet\dol@stpage}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \subsection{Leaves per gathering}
%
%     Traditionally books are assembled in terms of gatherings, or signatures, 
% with perhaps 8 or 16 pages (or leaves) per grouping (a leaf has two pages, 
% recto and one verso). At the request of Alan Ristow code for this has
% been included in the class.
%
% \begin{macro}{\ifcntrmod}
% \begin{macro}{\ifnotcntrmod}
% \begin{macro}{\iscntrmod}
% \cs{iscntrmod}\marg{counter}\marg{number} returns \cs{cntrmod(true|false)}
% and \cs{notcntrmod(false|true)} if \meta{counter} is a multiple of 
% \meta{number}.
% \changes{v1.61803}{2008/01/30}{Added \cs{iscntrmod}}
%    \begin{macrocode}
\newif\ifcntrmod
\newif\ifnotcntrmod
\newcommand*{\iscntrmod}[2]{
  \@tempcnta=\@nameuse{c@#1}%
  \@tempcntb=\@tempcnta
  \divide\@tempcnta #2\relax
  \multiply\@tempcnta #2\relax
  \advance\@tempcntb-\@tempcnta
  \ifnum\@tempcntb=0\relax
    \cntrmodtrue
    \notcntrmodfalse
  \else
    \cntrmodfalse
    \notcntrmodtrue
  \fi}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@memensuresigpages}
% Ouput enough (empty) pages to make up a complete final signature.
% \changes{v1.61803}{2008/01/30}{Added \cs{@memensuresigpages}}
%    \begin{macrocode}
\newcommand*{\@memensuresigpages}{%
  \ifnum\@mempagespersig<\@ne
  \else
    \iscntrmod{sheetsequence}{\@mempagespersig}
    \ifcntrmod
    \else
        \clearpage
        \pagestyle{empty}
        \mbox{}
      \loop
        \iscntrmod{sheetsequence}{\@mempagespersig}
        \ifnotcntrmod
        \clearpage
        \pagestyle{empty}
        \mbox{}
      \repeat
    \fi
  \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\leavespergathering}
% \cs{leavespergathering}\marg{num} is the user command for specifying that
% there must be \meta{num} leaves per gathering (2\meta{num} pages per 
% gathering). For \meta{num} more than one the total number of pages output
% is exactly divisible by 2\meta{num}. \meta{num} less than two (the default)
% has no effect.
% \changes{v1.61803}{2008/01/30}{Added \cs{leavespergathering}}
%    \begin{macrocode}
\newcommand*{\leavespergathering}[1]{\@memcnta=#1\relax
                                     \ifnum\@memcnta<\tw@
                                       \def\@mempagespersig{-1}%
                                     \else
                                       \multiply\@memcnta \tw@
                                       \edef\@mempagespersig{\@memcnta}%
                                     \fi}
\leavespergathering{0}

%    \end{macrocode}
% \end{macro}
%
% Finally, make sure that the requested number of pages is output.
%    \begin{macrocode}
\AtEndDocument{\@memensuresigpages}

%    \end{macrocode}
%
% \subsection{Text case}
% \changes{v3.6k}{2012/09/13}{Included a copy of the \texttt{textcase}
% package.}
% 
% \changes{3.7i}{2019/10/22}{Made textcase into a required package instead}
%
% Since, say, \cs{MakeUppercase} does too much, i.e.\ also upper case
% math and arguments to, say, \cs{ref}, we provide a version that does
% not. David Carlisle wrote the simple package ---
% \Lpack{textcase}~\cite{TEXTCASE} which we simply present as a carbon
% copy including Davids explanations. We do \emph{not} mark this
% package as have been emulated. Loading \texttt{textcase} just
% overwrites the macros if they exist.
%
% As of October 2019, we will instead load the  \texttt{textcase}
% package if found. If not we resort to the old version we had
% embedded. 
%
% As of Summer 2022 the functionality of \Lpack{textcase} was build
% into the kernel \cs{MakeUppercase} and \cs{MakeLowercase}, plus
% their functionalily regarding UTF8 was greatly extended. We will
% instead let \cs{MakeTextUppercase} and \cs{MakeTextLowercase} be
% aliases for the original.
% 
% \changes{v3.8.4}{2025/08/08}{Got rid of the textcase package.}
%    \begin{macrocode}
\AtBeginDocument{
  \providecommand\MakeTextUppercase{\MakeUppercase}
  \providecommand\MakeTextLowercase{\MakeLowercase}
}
\newcommand\MemRestoreOrigMakecase{
  \@memarn{\string\MemRestoreOrigMakecase\ no longer does anything and can be removed}
}
%    \end{macrocode}
%
%
% \section{Initialization} \label{sec:init}
%
% \subsection{Words and phrases}
% 
% This document class is for documents prepared in the English language.
% To prepare a version for another language, various English words 
% and phrases must
% be replaced.  The English elements that require replacement are
% defined below in command names.
%
% \begin{macro}{\abstractname}
% \begin{macro}{\contentsname}
% \begin{macro}{\listfigurename}
% \begin{macro}{\listtablename}
% \begin{macro}{\bookname}
% \begin{macro}{\partname}
% \begin{macro}{\chaptername}
% \begin{macro}{\appendixname}
% \begin{macro}{\appendixtocname}
% \begin{macro}{\appendixpagename}
% \begin{macro}{\bibname}
% \begin{macro}{\indexname}
% \begin{macro}{\glossaryname}
%
%    This list is for titles of document sections.
%
%    \begin{macrocode}
\newcommand*{\abstractname}{Abstract}
\newcommand*{\contentsname}{Contents}
\newcommand*{\listfigurename}{List of Figures}
\newcommand*{\listtablename}{List of Tables}
\newcommand*{\bookname}{Book}
\newcommand*{\partname}{Part}
\newcommand*{\chaptername}{Chapter}
\newcommand*{\appendixname}{Appendix}
\newcommand*{\appendixtocname}{Appendices}
\newcommand*{\appendixpagename}{Appendices}
\newcommand*{\bibname}{Bibliography}
\newcommand*{\indexname}{Index}
\newcommand*{\glossaryname}{Glossary}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\figurename}
% \begin{macro}{\tablename}
% \begin{macro}{\figurerefname}
% \begin{macro}{\tablerefname}
% \begin{macro}{\pagename}
% \begin{macro}{\pagrefename}
%
%    These are the names and phrases used for general elements.
% 
% \changes{v3.8.4}{2025/07/30}{\cs{...refname} ought to refer to \cs{...nane}}
%    \begin{macrocode}
\newcommand*{\figurename}{Figure}
\newcommand*{\tablename}{Table}
\newcommand*{\figurerefname}{\figurename}
\newcommand*{\tablerefname}{\tablename}
\newcommand*{\pagename}{page}
\newcommand*{\pagerefname}{\pagename}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\bookrefname}
% \begin{macro}{\partrefname}
% \begin{macro}{\chapterrefname}
% \begin{macro}{\sectionrefname}
% \begin{macro}{\appendixrefname}
% More names for referencing.
% \changes{v1.2}{2002/07/27}{Added \cs{partrefname}, \cs{chapterrefname}
%                            and \cs{sectionrefname}}
% \changes{v1.61803}{2008/01/30}{Added \cs{bookrefname} (mempatch v4.9+)}
% \changes{v1.61803}{2008/05/17}{Added \cs{appendixrefname}}
% \changes{v3.8.4}{2025/07/22}{These should not use hardcoded words, use \cs{...name} macros, plus removed tilde from them}
%    \begin{macrocode}
\newcommand*{\bookrefname}{\bookname}
\newcommand*{\partrefname}{\partname}
\newcommand*{\chapterrefname}{\chaptername}
\newcommand*{\sectionrefname}{\S}
\newcommand*{\appendixrefname}{\appendixname}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \subsection{Date}
%
% \begin{macro}{\today}
%    This macro uses the \TeX\ primitives \cs{month}, \cs{day} and \cs{year}
%    to provide the date of the \LaTeX-run.
%    \begin{macrocode}
\newcommand{\today}{\ifcase\month\or
  January\or February\or March\or April\or May\or June\or
  July\or August\or September\or October\or November\or December\fi
  \space\number\day, \number\year}
%    \end{macrocode}
% \end{macro}
%
% \subsection{Two column mode}
%
% \begin{macro}{\columnsep}
%    This gives the distance between two columns in two column mode.
%    \begin{macrocode}
\setlength\columnsep{10\p@}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\columnseprule}
%    This gives the width of the rule between two columns in two
%    column mode. We have no visible rule.
%    \begin{macrocode}
\setlength\columnseprule{0\p@}
%    \end{macrocode}
% \end{macro}
%
% \subsection{Some counters}
%    We set the sectional counters to zero, the \verb?tocdepth? to
%    one (sections and above listed), the \verb?secnumdepth? to
%    two (sections and above numbered), and \cs{maxsecnumdepth} to
% the same.
% \changes{v1.1a}{2002/04/28}{Added initialisation of \cs{maxsecnumdepth}}
%    \begin{macrocode}
\setcounter{part}{0}
\setcounter{chapter}{0}
\setcounter{tocdepth}{1}
\setcounter{secnumdepth}{2}
\maxsecnumdepth{section}

%    \end{macrocode}
%
% Set the \cs{linenumberfrequency} to zero to prohibit line numbering
% and also set the font for line numbers. Can now set the final space
% for boxed verbatim line numbers.
%    \begin{macrocode}
\linenumberfrequency{0}
\linenumberfont{\small\rmfamily}
\settowidth{\bvnumlength}{\vlvnumfont 9999}

%    \end{macrocode}
%
%
% \subsection{Single or double sided printing}
%
%
%    Unless the \Lopt{twoside} wasn't specified, We do not try to make 
% each page of equal height.
%    \begin{macrocode}
\if@twoside
\else
  \raggedbottom
\fi
%    \end{macrocode}
%    When the \Lopt{twocolumn} option was specified we call
%    \cs{twocolumn} to activate this mode. We try to make each column as
%    long as the others, but call \cs{sloppy} to make our life easier.
%    \begin{macrocode}
\if@twocolumn
  \twocolumn
  \sloppy
  \flushbottom
%    \end{macrocode}
%    Normally we call \cs{onecolumn} to initiate typesetting in one
%    column.
%    \begin{macrocode}
\else
  \onecolumn
\fi

%    \end{macrocode}
%
% \subsection{Floats}
%
%    Here are the implementations of the figure and table environments
% and their accompanying List of\ldots
%
% \begin{environment}{figure}
% \begin{environment}{figure*}
%    This is the definition of the actual environment. The form with the
%    \verb?*? is used for double column figures. We use \cs{newfloat} to set it.
% In this class figures are numbered per chapter, but we need to change 
% the default definition of \cs{thefigure} if a figure
% is in a pre-numbered chapter.
% \changes{v1.3a}{2002/11/22}{Added \cs{kill@lastcounter} after new 
%                             figure float}
% \changes{v1.61803}{2008/01/30}{Killed \cs{kill@lastcounter} after new 
%                             figure float}
%    \begin{macrocode}
\newfloat[chapter]{figure}{lof}{\figurename}
\renewcommand{\thefigure}{\thechapter.\@arabic\c@figure}

%    \end{macrocode}
% \end{environment}
% \end{environment}
%
% \begin{macro}{\listoffigures}
% \begin{macro}{\listoffigures*}
% These macros request that LaTeX produces a list of figures.
% The LoF heading is added to the ToC unless the starred
% version is used.
% \changes{v1.3}{2002/11/14}{Added \cs{kill@lastcounter} after new 
%                             list of figures}
% \changes{v1.61803}{2008/01/30}{Killed \cs{kill@lastcounter} after new 
%                             listoffigures}
%    \begin{macrocode}
\newlistof{listoffigures}{lof}{\listfigurename}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\l@figure}
%  \cs{l@figure}\marg{title}\marg{page} typesets the LoF entry for
% a \cs{figure} caption heading. 
% \changes{v1.3a}{2002/11/22}{Deleted \cs{kill@lastcounter} after new 
%                             figure listentry}
%    \begin{macrocode}
\newlistentry[chapter]{figure}{lof}{0}
  \cftsetindents{figure}{0em}{2.3em}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{environment}{table}
% \begin{environment}{table*}
%  The definition for tables is almost identical.
% \changes{v1.3a}{2002/11/22}{Added \cs{kill@lastcounter} after new 
%                             table float}
% \changes{v1.61803}{2008/01/30}{Killed \cs{kill@lastcounter} after new 
%                             table float}
%    \begin{macrocode}
\newfloat[chapter]{table}{lot}{\tablename}
\renewcommand{\thetable}{\thechapter.\@arabic\c@table}

%    \end{macrocode}
% \end{environment}
% \end{environment}
%
% \begin{macro}{\listoftables}
% \begin{macro}{\listoftables*}
% These macros request that LaTeX produces a list of tables.
% The LoT heading is added to the ToC unless the starred
% version is used.
% \changes{v1.3}{2002/11/14}{Added \cs{kill@lastcounter} after new 
%                             list of tables}
% \changes{v1.61803}{2008/01/30}{Killed \cs{kill@lastcounter} after new 
%                             list of tables}
%    \begin{macrocode}
\newlistof{listoftables}{lot}{\listtablename}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\l@table}
%  \cs{l@table}\marg{title}\marg{page} typesets the LoT entry for
% a \cs{table} caption heading. 
% \changes{v1.3a}{2002/11/22}{Deleted \cs{kill@lastcounter} after new 
%                             table listentry}
%    \begin{macrocode}
\newlistentry[chapter]{table}{lot}{0}
  \cftsetindents{table}{0em}{2.3em}

%    \end{macrocode}
% \end{macro}
%
% The \Lpack{subfigure} package defines \verb?lofdepth? and \verb?lotdepth?
% counters. If is not used, then we have to define them. The \Lpack{subfig}
% package replaced \Lpack{subfigure} in 2005, and this only defined
% the counters if they were not previously defined. It now seems sensible
% to ignore any use of the \Lpack{subfigure} package. This makes life a lot
% simpler.
% \changes{v1.61803}{2008/01/30}{Ignore subfig(ure) package re \cs{lofdepth}
%                    and \cs{lotdepth}}
%    \begin{macrocode}
%%%\AtBeginDocument{%
%%%  \@ifundefined{c@lofdepth}%
%%%     {\newcounter{lofdepth}\setcounter{lofdepth}{1}}{}
%%%  \@ifundefined{c@lotdepth}%
%%%     {\newcounter{lotdepth}\setcounter{lotdepth}{1}}{}}

%    \end{macrocode}
%
% \subsection{The \Lopt{article} option}
%
% The \Lopt{article} option requires changes to the default chapterstyle,
% and the numbering of floats, etc.
%
% Emanuele Vicentini (2003/07/21) suggested making \cs{maketitle} more
% closely match the real article's appearance.  Alan Budden commented
% on 2003/12/18 that the equation counter should be continuous.
% \changes{v1.0a}{2001/12/07}{Added footnote and chaptername changes to the article option}
% \changes{v1.4}{2003/11/22}{Added some resets of maketitle macros to 
% the article option (from patch v1.7)}
% \changes{v1.4}{2003/12/18}{Added equation counter to article resets}
%
% Victor Ivrii (October 2014) noted that adding \pstyle{headings} and
% english \Lpack{babel} produce unexpected headers containing the
% frase ``Chapter''.
%    \begin{macrocode}
\ifartopt
  \chapterstyle{article}
  \counterwithout{figure}{chapter}
  \counterwithout{table}{chapter}
  \counterwithout{footnote}{chapter}
  \counterwithout{equation}{chapter}
%    \end{macrocode}
% Setting \cs{chaptername} empty was added in v1.0a, with no
% indication why. Because of \Lpack{babel} (and others) this is
% clearly not a good idea. We will adjust \pstyle{headings} in a
% different manner, but leave all the other page styles alone as using
% the \Lopt{article} as the basis of design work might not be
% recommended. 
% \changes{v3.7d}{2014/11/05}{Redone \cs{chaptername} adjustment plus
% \pstyle{headings} under \Lopt{article} option}
%    \begin{macrocode}
  %\renewcommand{\chaptername}{}
  \if@twoside
    \addtopsmarks{headings}{}{%
      \createmark{chapter}{left}{shownumber}{}{. \ }
    }
  \else
    \addtopsmarks{headings}{}{%
      \createmark{chapter}{right}{shownumber}{}{. \ }
    }
  \fi
  \renewcommand{\maketitlehookb}{%
    \vskip -1.5\topsep\vskip -1.5\partopsep}
  \renewcommand{\maketitlehookc}{%
    \vskip -1.5\topsep\vskip -1.5\partopsep}
\fi

%    \end{macrocode}
%
%
% \subsection{The \Lopt{ms} option}
%
% This should be done last as it makes various changes to the defaults.
%
% \begin{macro}{\msdoublespacing}
% \begin{macro}{\mssinglespacing}
%  These do nothing unless the \Lopt{ms} option is used; then they change
% the \cs{baselinestretch}.
%    \begin{macrocode}
\newcommand{\msdoublespacing}{}
\newcommand{\mssinglespacing}{}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%    \begin{macrocode}
\ifmsdoc
  \renewcommand{\msdoublespacing}{%
    \renewcommand{\baselinestretch}{1.6}\large\normalsize}
  \renewcommand{\mssinglespacing}{%
    \renewcommand{\baselinestretch}{1.0}\large\normalsize}
  \renewcommand{\familydefault}{cmtt}
  \renewcommand{\rmdefault}{cmtt}
  \renewcommand{\sfdefault}{cmtt}
  \renewcommand{\bfdefault}{m}
  \renewcommand{\itdefault}{n}
  \renewcommand{\sldefault}{n}
  \renewcommand{\scdefault}{n}
  \renewcommand{\baselinestretch}{1.6}
  \@twocolumnfalse
  \onecolumn
  \sloppy
  \@twosidefalse
  \raggedbottom
  \pagestyle{plain}
\fi

%    \end{macrocode}
%
% \subsection{Emulated packages}
%
%    Many of the `emulations' are extensions and integration of package
% facilities. In some cases an `emulated' package just won't work with the
% class, so I've added it here to prevent it from being loaded. In any case, 
% most of the packages are mine.
% \changes{v1.6180339}{2008/07/23}{Added dates to emulated packages}
% \changes{v1.61803398d}{2010/02/13}{Emulated tocvsec2, used the date
% from the other lines, tocvsec2 provides the same macros as memoir}
%    \begin{macrocode}
\EmulatedPackage{abstract}[2008/07/23]
\EmulatedPackage{appendix}[2008/07/23]
%    \end{macrocode}
% \changes{v3.6k}{2012/07/19}{Changed the enumated date for the
% \Lpack{array} package. Apparently the only thing changed between
% v2.4b (2005) and c (2008) are some copyright years.}
% \changes{v3.7g}{2018/03/05}{Embedded the latest version of the
% \Lpack{array} package}
% \changes{v3.7h}{2018/09/06}{\Lpack{array} no longer embedded,
% required instead}
% \changes{v3.8}{2023/07/28}{booktabs no longer emulated}
%    \begin{macrocode}
 % \EmulatedPackage{array}[2016/10/06]
 % \EmulatedPackage{booktabs}[2016/05/16]
\EmulatedPackage{ccaption}[2008/07/23]
\EmulatedPackage{changepage}[2008/07/23]
\EmulatedPackage{chngcntr}[2008/07/23]
\EmulatedPackage{chngpage}[2008/07/23]
\EmulatedPackage{crop}
%    \end{macrocode}
% \changes{v3.7h}{2018/09/06}{\Lpack{dcolumn} is no longer embedded,
% emulation removed. We require it instead}
%    \begin{macrocode}
 % \EmulatedPackage{dcolumn}[2008/07/23]
%    \end{macrocode}
% \changes{v3.7g}{2018/03/06}{Adjusted the date for \Lpack{delarray},
% the code is the same}
% \changes{v3.7h}{2018/09/06}{\Lpack{delarray} is no longer embedded,
% emulation removed. We require it instead}
%    \begin{macrocode}
 % \EmulatedPackage{delarray}[2014/10/28]
\EmulatedPackage{enumerate}[2008/07/23]
\EmulatedPackage{epigraph}[2008/07/23]
%%%%%\EmulatedPackage{framed}[2008/07/23]
\EmulatedPackage{ifmtarg}[2008/07/23]
%    \end{macrocode}
% \changes{v3.7g}{2018/03/08}{Removed if\meta{engine} emulation}
%    \begin{macrocode}
 %\ifm@mifetex\EmulatedPackage{ifetex}[2008/07/23]\fi
 %\ifm@mifluatex\EmulatedPackage{ifluatex}[2008/07/23]\fi
 %\ifm@mifpdf\EmulatedPackage{ifpdf}[2008/07/23]\fi
 %\ifm@mifxetex\EmulatedPackage{ifxetex}[2008/07/23]\fi
\EmulatedPackage{index}[2008/07/23]
\EmulatedPackage{makeidx}[2008/07/23]
\EmulatedPackage{moreverb}[2008/07/23]
%    \end{macrocode}
% \changes{v3.8.2a}{2024/01/29}{shortvrb is no longer emulated. No need to release as it is loaded before the emulation}
% \changes{v3.7o}{2021/03/22}{removed mparhack emulation, as we don't
% emulate all of it, especially not the fix for \cs{if@firstcolumn},
% instead load it if twocolumn }
% \changes{v3.8.3}{2025/03/04}{Removed mparhack loading. There are packages not compatible with it, and we should not autoload it when we don't know if the user needs it.}
%    \begin{macrocode}
 % \if@twocolumn
 %   \RequirePackage{mparhack}
 % \fi
  %\EmulatedPackage{mparhack}[2008/07/23]
\EmulatedPackage{needspace}[2008/07/23]
\EmulatedPackage{newfile}[2008/07/23]
\EmulatedPackage{nextpage}[2008/07/23]
\EmulatedPackage{pagenote}[2008/07/23]
\EmulatedPackage{parskip}[2008/07/23]
\EmulatedPackage{patchcmd}[2008/07/23]
\EmulatedPackage{setspace}[2008/07/23]
%    \end{macrocode}
% 
% \changes{v3.8.3}{2025/03/05}{Forgot to remove shortvrb emulation in 3.8.2}
%    \begin{macrocode}
 % \EmulatedPackage{shortvrb}[2008/07/23]
\EmulatedPackage{showidx}[2008/07/23]
%    \end{macrocode}
% \changes{v3.7g}{2018/03/02}{Updated the embedded version of \Lpack{tabularx} to v2.11 2016/02/03}
% \changes{v3.7h}{2018/09/08}{\Lpack{tabularx} is no longer emulated,
% but a required package}
% \changes{v3.8.2a}{2024/01/29}{shortvrb is no longer emulated. No need to release as it is loaded before the emulation}
%    \begin{macrocode}
 % \EmulatedPackage{tabularx}[2016/02/03]
\EmulatedPackage{titleref}[2008/07/23]
\EmulatedPackage{titling}[2008/07/23]
\EmulatedPackage{tocbibind}[2008/07/23]
\EmulatedPackage{tocloft}[2008/07/23]
\EmulatedPackage{tocvsec2}[2008/07/23]
 % \EmulatedPackage{verbatim}[2008/07/23]
\EmulatedPackage{verse}[2008/07/23]

%    \end{macrocode}
%
% \subsection{Interaction with the \Lpack{caption} package}
%
% As of 2020, whenever the \Lpack{caption} package is loaded with the
% memoir class, it will map relevant memoir captioning macros onto the
% corresponding features provided by \Lpack{caption}. As this is now
% done automatically, we have removed the code that reset \cs{caption}
% to something more friendly to \Lpack{caption} in earler versions of
% the class.
%
% \changes{v3.7o}{2021/03/15}{removed code to reset for the caption package}
%
% \subsection{Interaction with the \Lpack{float} package}
%
%    The \Lpack{float} package also defines \cs{newfloat}, so kill memoir's
% version when the \Lpack{float} package gets used.
% \changes{v1.61803}{2008/01/30}{Killed \cs{newfloat} when float package is
%                    used (mempatch v4.9)}
%    \begin{macrocode}
\AtBeginPackage{float}{\let\newfloat\relax}

%    \end{macrocode}
%
%
% \subsection{Interaction with the \Lpack{hyperref} package}
%
% Ulrike Fischer has ask that the \Lpack{memhfixc} autoload is moved
% from \Lpack{hyperref} to \Lpack{memoir}.
% \changes{v3.7q}{2022/02/20}{Added autoloading}
%    \begin{macrocode}
\AtEndPackage{hyperref}{\RequirePackage{memhfixc}}      
%    \end{macrocode}
%
% \subsection{Package that should not be used with memoir}
%
%   Some packages should not be used with the class. Primarily because
%   we already provide a more well integrated solution, or if the
%   package break class functionalily. We may add warnings for when
%   users load certain of these package.
%
% \changes{v3.8.3}{2024/02/15}{Added warning about fancyhdr}
%    \begin{macrocode}
\AtBeginPackage{fancyhdr}{
  \@memwarn{The fancyhdr package is not
    recommended with memoir.\MessageBreak
    We have our own well integrated interface
    to handle\MessageBreak headers and footers. See the manual
    section 7.3\MessageBreak onwards for details.}
}
%    \end{macrocode}
% \changes{v3.8.3}{2024/03/04}{Added warning about titlesec}
%    \begin{macrocode}
\AtBeginPackage{titlesec}{
  \@memwarn{The titlesec package is not
    recommended with memoir.\MessageBreak
    With it we loose some of the features provides by the\MessageBreak
    class. We provide our own interface to adjust how \MessageBreak
    sections and chapters should look like.\MessageBreak
    See the manual sections 6.4 through 6.6 for details.
  }
}
%    \end{macrocode}
% \changes{v3.8.3}{2024/03/04}{Added warning about titleps}
%    \begin{macrocode}
\AtBeginPackage{titleps}{
  \@memwarn{The titleps package is not
    recommended with memoir.\MessageBreak
    It cannot really work properly without the titlesec\MessageBreak
    package, which is already incomparible with memoir.\MessageBreak
    We have our own well integrated interface to \MessageBreak
    handle headers and footers.\MessageBreak
    See the manual section 7.3 onwards for details.
  }
}
%    \end{macrocode}
%   \changes{v3.8.3}{2024/03/04}{Added warning about sectsty, probably
%   now needed as sectsty is unusable in modern LaTeX}
%    \begin{macrocode}
\AtBeginPackage{sectsty}{
  \@memwarn{%
    The sectsty package is super old (has not been updated\MessageBreak
    since 2002) and is unlikely to be compatible with modern\MessageBreak
    LaTeX. We provide our own interface to adjust how \MessageBreak
    sections and chapters should look like.\MessageBreak
    See the manual sections 6.4 through 6.6 for details.
  }
}
%    \end{macrocode}
%
% \changes{v3.8.4}{2025/09/17}{Added warning about subfigure and subfig}
%    \begin{macrocode}
\AtBeginPackage{subfigure}{
  \@memwarn{%
    The subfigure package is marked obsolete,\MessageBreak
    consider using the subcaption package instead.
  }
}
\AtBeginPackage{subfig}{
  \@memwarn{%
    The subfig package hasn't been updated since 2005.\MessageBreak
    Consider using the subcaption package instead.
  }
}
%    \end{macrocode}
%
% \subsection{Default page style}
%    We use the page style \pstyle{headings} by
%    default and arabic page numbering. But if the \verb?article?
%    class option is in effect, we will use the \pstyle{plain} style
%    which is the default in the \verb?article? class.
% \changes{v3.6d}{2010/05/13}{When emulating the article class the
% plain page style should used instead of headings}
% \changes{v3.7i}{2019/01/07}{Moved here because
% \cs{newlistof}{...}{X}{...} also defines \cs{Xmark}, but using
% \cs{markboth}, and thus if \Lopt{oneside} is active \cs{lofmark}
% will still be using \cs{mathboth} and not \cs{markright} that the
% \pstyle{headings} style dictates}
%    \begin{macrocode}
\ifartopt
\pagestyle{plain}
\else
\pagestyle{headings}
\fi
\pagenumbering{arabic}

%    \end{macrocode}






% ^^A\subsection{Patch file}
% ^^A
% ^^A At the suggestion of Danie Els, Dan Leucking
% ^^A  and others, input a patch file, if one exists,
% ^^A as the final act. (This is preferable to my series of \file{memfixa.sty},
% ^^A \file{memfixb.sty} packages, and so on, for each release of the class.)
% ^^A \changes{v1.3}{2002/11/14}{Added input of mempatch.sty}
% ^^A \changes{v1.6180339c}{2008/12/26}{Added the two missing arguments when inputting
% ^^A  mempatch.sty (courtesy of Wilhelm Muller)}
% ^^A \changes{v1.61803398}{2009/07/27}{PW: changed call to mempatch, which I think
% ^^A          restores Lars' v1.6180339h change}
% ^^A \changes{v3.7g}{2018/03/08}{mempatch have been empty for almost
% ^^A 10years, we will no longer load it.}
% ^^A    \begin{macrocode}
% ^^A\IfFileExists{mempatch.sty}{%
% ^^A  \RequirePackage{mempatch}}{} 
% ^^A
% ^^A    \end{macrocode}
% ^^A
%    The end of the class definitions.
%    \begin{macrocode}
%</class>
%    \end{macrocode}
%
% \section{Glossary Makeindex style file}
%
% Here is the basic style (configuration) file for Makeindex 
% for use with the default glossary setup.
% \changes{v1.618}{2005/09/25}{Added basic.gst file}
%
%    \begin{macrocode}
%<*gst>
%%%%% basic.gst    basic makeindex glossary configuration file for memoir
%%%%% Output style parameters
preamble "\\begin{theglossary}"
postamble "\n\\end{theglossary}\n"
group_skip "\n\\glossaryspace\n"
item_0    "\n\\glossitem"
delim_0   "{\\memglonum{"
encap_suffix "}}}"
%%% Input style parameters
keyword "\\glossaryentry"

%</gst>
%    \end{macrocode}
%
% The end of the configuration file code
%
% \bibliographystyle{alpha}
% \begingroup
% \raggedright
% \begin{thebibliography}{GMSN94A}
%
%
%    \bibitem[ABH90]{bk:Impatient}
%      Paul W.~Abrahams, Karl Berry and Kathryn A.~Hargreaves.
%      \newblock \emph{TeX{} for the Impatient}.
%      \newblock
%       Addison-Wesley, Reading, Massachusetts, 1990.
%      \newblock (Available from CTAN in \texttt{info/impatient})
%
% \bibitem[Ars01a]{TITLEREF}
% Donald Arseneau.
% \newblock \emph{\Lpack{Titleref} package (version 3.1)}.
% \newblock April 2001.
% \newblock (Available from CTN as
%            \texttt{macros/latex/contrib/misc/titleref.sty})
%
% \bibitem[Ars01b]{CHAPTERBIB}
% Donald Arseneau.
% \newblock \emph{\Lpack{Chapterbib} package (version 1.9)}.
% \newblock September 2001.
% \newblock (Available from CTN as
%            \texttt{macros/latex/contrib/misc/chapterbib.sty})
%
% \bibitem[Ars03]{FRAMED}
% Donald Arseneau.
% \newblock \emph{\Lpack{Framed} package (version 0.8a)}.
% \newblock July 2003.
% \newblock (Available from CTAN as
%            \texttt{macros/latex/contrib/misc/framed.sty})
%
% \bibitem[Ars05]{PLACEINS}
% Donald Arseneau.
% \newblock \emph{\Lpack{Placeins} package (version 2.2)}.
% \newblock May 2005.
% \newblock (Available from CTAN as
%            \texttt{macros/latex/contrib/placeins/placeins.sty})
%  
%
% \bibitem[ArWi00]{IFMTARG}
% Donald Arseneau and Peter Wilson.
% \newblock \emph{The ifmtarg package}.
% \newblock March, 2000.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/misc})
%
% \bibitem[Source2e]{SOURCE2E}
%   Johannes Braams, David Carlisle, Alan Jeffrey, Leslie Lamport, Frank Mittelbach,
%   Chris Rowley and Rainer Schöpf (maintained by the \LaTeX\ Project).
%   \newblock \emph{The \LaTeX2e\ Sources}
%   \newblock November 2023.
%   \newblock (Available from CTAN as
%                  \texttt{/macros/latex/base/source2e.pdf})
%
% 
%  \bibitem[Car94]{DELARRAY}
%  David Carlisle.
%  \newblock \emph{The \Lpack{delarray} package}.
%  \newblock March 1994.
%  \newblock (Available from CTAN in
%             \texttt{/macros/latex/required/tools})
%
%
% \bibitem[Car98a]{ENUMERATE}
% David Carlisle.
% \newblock \emph{The enumerate package}.
% \newblock August, 1998.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/required/tools})
%
% \bibitem[Car98b]{REMRESET}
% David Carlisle.
% \newblock \emph{The remreset package}.
% \newblock August, 1998.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/carlisle})
%
%  \bibitem[Car99]{TABULARX}
%  David Carlisle.
%  \newblock \emph{The \Lpack{tabularx} package}.
%  \newblock February 2016.
%  \newblock (Available from CTAN in
%             \texttt{/macros/latex/required/tools})
%
%  \bibitem[Car01]{DCOLUMN}
%  David Carlisle.
%  \newblock \emph{The \Lpack{dcolumn} package}.
%  \newblock May, 2001.
%  \newblock (Available from CTAN in
%             \texttt{/macros/latex/required/tools})
%
% \bibitem[Car19]{TEXTCASE}
%  David Carlisle.
% \newblock \emph{The \Lpack{textcase} package}.
% \newblock September, 2019.
% \newblock (Available from CTAN in 
%       \texttt{/macros/latex/contrib/textcase})
%
% \bibitem[Coc02]{SUBFIGURE}
% Steven Douglas Cochran.
% \newblock \emph{The subfigure package}.
% \newblock March, 2002.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/subfigure})
%
% \bibitem[Dal99]{NATBIB}
% Patrick W. Daly.
% \newblock \emph{Natural Sciences Citations and References}.
% \newblock May, 1999.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/natbib})
%
% \bibitem[Dow00]{PATCHCMD}
% Michael J. Downes
% \newblock \emph{The patchcmd package}.
% \newblock July 2000.
% \newblock (Available from CTAN in
%            \texttt{/macros/latex/contrib/patchcmd})
%
%  \bibitem[LTX3]{LTX3}
%  The \LaTeX{} Project.
% \newblock \emph{The \LaTeX3 sources}
% \newblock June, 2023.
% \newblock (Available from CTAN in \texttt{/macros/latex/contrib/l3kernel})
%
% \bibitem[Fai98]{MOREVERB}
% Robin Fairbairns.
% \newblock \emph{The moreverb package}.
% \newblock December, 1998.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/moreverb})
%
% \bibitem[Fai03]{FOOTMISC}
% Robin Fairbairns.
% \newblock \emph{\Lpack{footmisc} --- a portmanteau package for 
%            customising footnotes in LaTeX}.
% \newblock February 2003.
% \newblock (Available from CTAN in
%            \texttt{macros/latex/contrib/footmisc})
%
%
%    \bibitem[Fea03]{BOOKTABS}
%      Simon Fear.
%      \newblock \emph{Publication quality tables in \LaTeX}.
%       \newblock March, 2003.
%      \newblock (Available from CTAN in 
%                 \texttt{macros/latex/contrib/booktabs})
%
% \bibitem[Fra00]{CROP}
% Melchior Franz.
% \newblock \emph{The crop package}.
% \newblock February, 2000.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/crop})
%
%
% \bibitem[GMS94]{GOOSSENS94}
% Michel Goossens, Frank Mittelbach, and Alexander Samarin.
% \newblock \emph{The LaTeX Companion}.
% \newblock Addison-Wesley Publishing Company, 1994.
%
%
%
%    \bibitem[Knu84]{bk:knuth}  
%       Donald E. Knuth.
%       \newblock  \emph{The \TeX{}book}.
%       \newblock
%       Addison-Wesley, Reading, Massachusetts, 1984.
%
%
% \bibitem[KWG]{TUFTE}
% Bil Kleb, Bill Wood, and Kevin Godby.
% \newblock \emph{Tufte LaTeX}.
% \newblock December 2009.
% \newblock (Available from CTAN in \texttt{macros/latex/contrib/tufte-latex/})
% 
%    \bibitem[Lam94]{bk:lamport} 
%       Leslie Lamport.
%       \newblock  \emph{\LaTeX\ --- A Document Preparation System}.
%       \newblock
%       Addison-Wesley, Reading, Massachusetts, 1994.
%
% \bibitem[LMB99]{CLASSES}
% Leslie Lamport, Frank Mittelbach and Johannes Braams.
% \newblock \emph{Standard Document Classes for LaTeX version 2e}.
% \newblock September, 1999.
% \newblock (Available from CTAN as 
%            \texttt{/macros/latex/base/classes.dtx})
%
% \bibitem[LPT19]{IFTEX}
% The \LaTeX{} Project Team.
% \newblock \emph{The iftex package}.
% \newblock November, 2019.  
% \newblock (Available from CTAN in \texttt{/macros/latex/contrib/iftex})
%
%  \bibitem[MC98]{ARRAY}
%  Frank Mittelbach and David Carlisle.
%  \newblock \emph{A new implementation of LaTeX's tabular and array 
%                  environment}
%  \newblock April 2017.
%  \newblock (Available from CTAN in
%             \texttt{/macros/latex/required/tools})
%
% \bibitem[Mit2020a]{LTFILEHOOK}
%   Frank Mittelbach
%   \newblock \emph{The ltfilehook package}
%    \newblock July 2020. 
%
%  \bibitem[Mit2023a]{LTHOOKS}
%   Frank Mittelbach
%   \newblock \emph{\LaTeX's hook management}
%    \newblock June 2023. 
%
%  \bibitem[Mit2020c]{LTSHIPOUT}
%   Frank Mittelbach
%   \newblock \emph{The ltshipout package}
%    \newblock July 2020. 
%
%  \bibitem[Mit2023b]{SHORTVRB}
%    Frank Mittelbach
%    \newblock \emph{The doc and shortvrb Packages}
%   \newblock November 2023.
%
% \bibitem[Oos96]{FANCYHDR}
% Piet van Oostrum.
% \newblock \emph{Page layout in LaTeX}.
% \newblock June, 1996.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/fancyhdr})
%
%
% \bibitem[Rah23]{NAMEREF}
% Sebastian Rahtz, Heiko Oberdiek, The \LaTeX{} project.
% \newblock \emph{Section name references in LaTeX}.
% \newblock 2023.
% \newblock (Available from CTAN in
%            \texttt{/macros/latex/contrib/hyperref})
%
% \bibitem[Rah02]{HYPERREF}
% Sebastian Rahtz.
% \newblock \emph{Hypertext marks in LaTeX}.
% \newblock March 2002.
% \newblock (Available from CTAN in
%            \texttt{/macros/latex/contrib/hyperref})
%
%
% \bibitem[Sch98]{EVERYSHI}
% Martin Schr\"{o}der.
% \newblock \emph{The everyshi package}.
% \newblock August, 1998.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/ms})
%
% \bibitem[SRR01]{VERBATIM}
% Rainer Sch\"{o}pf, Bernd Raichle and Chris Rowley.
% \newblock \emph{A new implementation of LaTeX's verbatim and verbatim*
%                 environments}.
% \newblock March, 2001.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/required/tools})
%
% \bibitem[Wil99]{TOCVSEC2}
% Peter Wilson.
% \newblock \emph{The tocvsec2 package}.
% \newblock January, 1999.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/tocvsec2})
%
% \bibitem[Wil00a]{EPIGRAPH}
% Peter Wilson.
% \newblock \emph{The epigraph package}.
% \newblock February, 2000.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/epigraph})
%
% \bibitem[Wil00b]{ISOCLASS}
% Peter Wilson.
% \newblock \emph{LaTeX files for typesetting ISO standards}.
% \newblock February, 2000.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/isostds/iso})
%
% \bibitem[Wil00c]{NEXTPAGE}
% Peter Wilson.
% \newblock \emph{The nextpage package}.
% \newblock February, 2000.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/misc})
%
% \bibitem[Wil00d]{NEEDSPACE}
% Peter Wilson.
% \newblock \emph{The needspace package}.
% \newblock March, 2000.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/misc})
%
% \bibitem[Wil01a]{ABSTRACT}
% Peter Wilson.
% \newblock \emph{The abstract package}.
% \newblock February, 2001.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/abstract})
%
% \bibitem[Wil01b]{CHNGPAGE}
% Peter Wilson.
% \newblock \emph{The chngpage package}.
% \newblock February, 2001.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/misc})
%
% \bibitem[Wil01c]{APPENDIX}
% Peter Wilson.
% \newblock \emph{The appendix package}.
% \newblock March, 2001.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/appendix})
%
% \bibitem[Wil01d]{CCAPTION}
% Peter Wilson.
% \newblock \emph{The ccaption package}.
% \newblock March, 2001.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/ccaption})
%
% \bibitem[Wil01e]{CHNGCNTR}
% Peter Wilson.
% \newblock \emph{The chngcntr package}.
% \newblock March, 2001.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/misc})
%
% \bibitem[Wil01f]{HANGING}
% Peter Wilson.
% \newblock \emph{The hanging package}.
% \newblock March, 2001.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/hanging})
%
% \bibitem[Wil01g]{TITLING}
% Peter Wilson.
% \newblock \emph{The titling package}.
% \newblock March, 2001.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/titling})
%
% \bibitem[Wil01h]{TOCBIBIND}
% Peter Wilson.
% \newblock \emph{The tocbibind package}.
% \newblock April, 2001.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/tocbibind})
%
% \bibitem[Wil01i]{TOCLOFT}
% Peter Wilson.
% \newblock \emph{The tocloft package}.
% \newblock April, 2001.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/tocloft})
%
% \bibitem[Wil01j]{VERSE}
% Peter Wilson.
% \newblock \emph{Typesetting simple verse with LaTeX}.
% \newblock August, 2001.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/verse})
%
%
% \bibitem[Wil03]{LEDMAC}
% Peter Wilson.
% \newblock \emph{\Lpack{ledmac}: A presumptuous attempt to port EDMAC and
%                 TABMAC to LaTeX}. 
% \newblock August 2003.
% \newblock (Available from CTAN in
%            \texttt{macros/latex/contrib/ledmac})
%
% \bibitem[Wil07]{GLISTER07}
% Peter Wilson.
% \newblock `Glisterings' \emph{TUGboat}, 28(2):229--232,
% \newblock 2007.
%
% \bibitem[Wil08]{GLISTER08}
% Peter Wilson.
% \newblock `Glisterings' \emph{TUGboat}, 29(2):324--327,
% \newblock 2008.
%
%
%
%
%
% \end{thebibliography}
% \endgroup
%
%
%
% ^^A\Finale
%
\endinput

%% \CharacterTable
%%  {Upper-case    \A\B\C\D\E\F\G\H\I\J\K\L\M\N\O\P\Q\R\S\T\U\V\W\X\Y\Z
%%   Lower-case    \a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p\q\r\s\t\u\v\w\x\y\z
%%   Digits        \0\1\2\3\4\5\6\7\8\9
%%   Exclamation   \!     Double quote  \"     Hash (number) \#
%%   Dollar        \$     Percent       \%     Ampersand     \&
%%   Acute accent  \'     Left paren    \(     Right paren   \)
%%   Asterisk      \*     Plus          \+     Comma         \,
%%   Minus         \-     Point         \.     Solidus       \/
%%   Colon         \:     Semicolon     \;     Less than     \<
%%   Equals        \=     Greater than  \>     Question mark \?
%%   Commercial at \@     Left bracket  \[     Backslash     \\
%%   Right bracket \]     Circumflex    \^     Underscore    \_
%%   Grave accent  \`     Left brace    \{     Vertical bar  \|
%%   Right brace   \}     Tilde         \~}
%%

