% \iffalse
% LuaTufte documented source. LPPL 1.3c or later.
% Derived from kaobook, copyright 2020-2021 Federico Marotta.
% Maintainer: Lukas C. Bossert <lukas@texografie.de>. See MANIFEST.md.
%<*driver>
\documentclass[sections=numbered,titlepage,fontsize=11pt]{luatufte}
\usepackage[english]{babel}
\usepackage{csquotes}
\usepackage[style=authoryear]{luatufte-biblio}
\DeclareLabeldate{\field{date}\field{year}\literal{nodate}}
\addbibresource{references.bib}
% doc sets up an inner margin for macro descriptions. Keep the book's outer notes.
\edef\restorebookmargin{\noexpand\normalmarginpar
  \marginparwidth=\the\marginparwidth\relax
  \marginparsep=\the\marginparsep\relax
  \marginparpush=\the\marginparpush\relax}
% doc supplies its own title command. Keep the book's renderer for this guide.
\NewCommandCopy{\luatuftemanualtitle}{\maketitle}
\usepackage[nohyperref,noindex,reportchangedates]{doc}
\RenewCommandCopy{\maketitle}{\luatuftemanualtitle}
\restorebookmargin
\usepackage{listings,booktabs,catchfilebetweentags}
\usepackage[nostfloats]{hvfloat}
% Render and print the same tagged float from this documented source.
\NewDocumentCommand{\showfloatexample}{m}{%
  \begingroup
  \captionsetup{font=footnotesize,justification=raggedright,
    singlelinecheck=false}
  \CatchFileBetweenTags{\manualfloatbody}{luatufte.dtx}{#1}[\endlinechar=13\relax]
  \manualfloatbody
  \endgroup
  \begin{wideblock}
    \lstinputlisting[gobble=0,rangeprefix=\%,linerange={<*#1>-</#1>},
      includerangemarker=false]{luatufte.dtx}
  \end{wideblock}}
% Read the book's tagged source for each worked example.
\NewDocumentCommand{\booksource}{m}{%
  \lstinputlisting[gobble=0,rangeprefix=\%,linerange={<*#1>-</#1>},
    includerangemarker=false]{luatufte.dtx}}
\NewDocumentCommand{\bookresult}{m}{%
  \CatchFileBetweenTags{\bookexamplebody}{luatufte.dtx}{#1}[\endlinechar=13\relax]%
  \bookexamplebody}
% A scale drawing for the layout chapter. The blank between the segments
% is the actual margin separation. Resolve the side where the drawing lands.
\ExplSyntaxOn
\NewExpandableDocumentCommand \manualmillimetres { m }
  { \fp_eval:n {round(\dim_to_fp:n {#1} / \dim_to_fp:n {1mm}, 1)} }
\ExplSyntaxOff
\NewDocumentCommand{\manualmeasure}{m m}{%
  \parbox[b]{#1}{\raggedright\footnotesize\sffamily #2 (\manualmillimetres{\linewidth}\,mm)\par
    \vspace{2pt}{\color{luatuftepetrol}\hrule height .55pt}}}
\NewDocumentCommand{\manualpagewidths}{}{%
  \begin{wideblock}
    \noindent
    \Ifthispageodd
      {\manualmeasure{\dimexpr\linewidth-\marginparsep-\marginparwidth\relax}{Main text}%
       \hspace{\marginparsep}\manualmeasure{\marginparwidth}{Outer notes}}
      {\manualmeasure{\marginparwidth}{Outer notes}\hspace{\marginparsep}%
       \manualmeasure{\dimexpr\linewidth-\marginparsep-\marginparwidth\relax}{Main text}}%
  \end{wideblock}}
\RecordChanges
% Save the body-width heading before the class installs its wide chapter style.
\NewCommandCopy{\manualbodychapterlines}{\chapterlinesformat}
\makeatletter
% The release entries share one level. Give continuation lines a small indent.
\renewenvironment{theglossary}{%
  \GlossaryParms
  \let\item\@idxitem
  \renewcommand*{\subitem}{\par\hangindent=1em\relax}%
  \let\subsubitem\subitem
}{\par}
\makeatother
\lstset{language=[LaTeX]TeX,basicstyle=\small\ttfamily,
  gobble=2,columns=fullflexible,keepspaces=true,showstringspaces=false,
  keywordstyle=\color{luatufteblue},breaklines=true,
  aboveskip=6pt plus 1pt,belowskip=6pt plus 1pt}
\setlength{\MacrocodeTopsep}{6pt plus 1pt}
\renewcommand*\MacroFont{\normalfont\ttfamily\fontsize{9}{11}\selectfont}
\renewcommand*\AltMacroFont{\MacroFont}
\setlength{\MacroIndent}{1em}
\GetFileInfo{luatufte.cls}
\author{LuaTufte project}
\title{The LuaTufte Manual}
\subtitle{Author guide and documented source}
\publishers{Release \fileversion}
\date{\filedate}
\hypersetup{pdftitle={The LuaTufte Manual},pdfsubject={Author guide and documented source},
  pdfauthor={LuaTufte project},bookmarksnumbered=true}
\begin{document}
\maketitle
\DocInput{luatufte.dtx}
\end{document}
%</driver>
% \fi
%
% \addchap{Getting started}
% \changes{0.0.1}{2026-12-02}{Open the manual with the class title page and release number.}
% A book with two reading paths needs a reliable place for each.
% LuaTufte gives the argument a main column and its supporting evidence
% an outer one. This manual uses the same class it describes.
% \marginpar{\raggedright\small Maintained by Lukas C. Bossert\par
% \href{mailto:lukas@texografie.de}{lukas@texografie.de}}
%
% \section*{A first page}
% \changes{0.0.1}{2026-12-02}{Extract a working example from the same source that prints it in the manual.}
% Put \texttt{luatufte.cls} beside your manuscript. The following file is
% a complete LuaLaTeX book.
% \iffalse
%<*example>
% \fi
%    \begin{macrocode}
\documentclass{luatufte}
\begin{document}
\chapter{Observing the series}
We kept all forty records.\sidenote{One per minute.}
\end{document}
%    \end{macrocode}
% \iffalse
%</example>
% \fi
% Build this page with \texttt{make quickstart}.
% Use \texttt{make example} for \emph{The Measurement Record}.
% \changes{0.0.1}{2026-12-02}{Integrate worked examples from the scientific book into the manual.}
%
% \section*{Add a title page}
% Set the title fields in the preamble and call \verb|\maketitle| after
% \verb|\begin{document}|. Use \texttt{titlepage=false} for a flush-left italic title on the opening text page.
% \begin{lstlisting}
% \title{Field Notes}
% \subtitle{A reproducible measurement study}
% \author{A. Writer}
% \date{2 December 2026}
% \end{lstlisting}
%
% \par\medskip\noindent\textit{In this manual}\par
% \noindent\hyperref[manual:notes]{Notes, sources and figures}
% \dotfill\pageref{manual:notes}\par
% \noindent\hyperref[manual:hvfloat]{Side captions with hvfloat}
% \dotfill\pageref{manual:hvfloat}\par
% \noindent\hyperref[manual:layout]{Width and page breaks}
% \dotfill\pageref{manual:layout}\par
% \noindent\hyperref[manual:profile]{Choosing individual settings}
% \dotfill\pageref{manual:profile}\par
% \noindent\hyperref[manual:specimen]{A typesetting specimen}
% \dotfill\pageref{manual:specimen}\par
% \noindent\hyperref[manual:source]{Building from the documented source}
% \dotfill\pageref{manual:source}\par
% \noindent\hyperref[manual:implementation]{Annotated implementation}
% \dotfill\pageref{manual:implementation}\par
% \noindent\hyperref[manual:changes]{Changelog}\dotfill\pageref{manual:changes}\par
%
% \chapter{Notes, sources and figures}\label{manual:notes}
% Attach a note to the sentence it qualifies.\sidenote{The number links this sentence
% to its note in the outer margin.} The superscript and the marginal text share a counter, which
% restarts at each numbered chapter.
% \begin{lstlisting}
% Retain every record.\sidenote{One per minute.}
% \end{lstlisting}
% For a source, load \texttt{luatufte-biblio} with your biblatex options
% and name your bibliography file in the preamble. The numbered source
% beside this paragraph points to the original kaobook project.\footcite{kaobook}
% \begin{lstlisting}
% \usepackage[style=authoryear]{luatufte-biblio}
% \addbibresource{references.bib}
% \end{lstlisting}
% A single optional argument gives a page. Two give a prenote and page.
% \begin{lstlisting}
% \footcite[42]{key}
% \footcite[see][42]{key}
% \end{lstlisting}
% Ordinary footnotes also enter the outer margin. The following
% notes move down 3\,pt. A negative length raises them.
% \begin{lstlisting}
% \marginnote{Source: field log}[3pt]
% \sidenote[][3pt]{Checked twice.}
% \end{lstlisting}
%
% \section*{Choosing the caption position}
% \changes{0.0.1}{2026-12-02}{Generate the specimen title and illustrate its missing-record audit.}
% A \texttt{marginfigure} keeps a small illustration and its caption together.
% The rule alongside this paragraph was produced by the example below.
% \begin{marginfigure}
% \rule{\linewidth}{0.5pt}
% \caption{The marginal measure.}
% \label{fig:measure}
% \end{marginfigure}
% \begin{lstlisting}
% \begin{marginfigure}
%   \rule{\linewidth}{0.5pt}
%   \caption{The marginal measure.}
%   \label{fig:measure}
% \end{marginfigure}
% \end{lstlisting}
% For a body-width object, use an ordinary \texttt{figure} or
% \texttt{table}. Its caption automatically occupies the outer margin.
% A \texttt{margintable} puts both the data and the legend in that margin.
% Both marginal environments accept a vertical offset.
%
% \clearpage
% \section*{A figure with hvfloat}\label{manual:hvfloat}
% \changes{0.0.1}{2026-12-02}{Typeset and print the hvfloat figure and table from the documented source on facing pages.}
% Load the package in the preamble. The table on the facing page also uses
% \texttt{booktabs} for its horizontal rules.
% \begin{lstlisting}
% \usepackage[nostfloats]{hvfloat}
% \usepackage{booktabs}
% \end{lstlisting}
% Figure~\ref{fig:offset} centres the calculation in the main column.
% The caption occupies the outer margin, on the left of this page.
% \showfloatexample{offset}
% The four braced arguments give the float type, the object, the caption
% and the label, in that order. The command creates the float itself.
% Here \texttt{wide} makes the outer column available, and
% \verb|floatCapSep=\marginparsep| aligns the caption with the book's notes.
%
% \clearpage
% \section*{A table with hvfloat}
% Table~\ref{tab:readings} uses the same placement keys. Its caption
% appears on the right of this page. The table fills the body column,
% so the numbers align independently of the caption length.
% \showfloatexample{readings}
% Use \verb|\ref{tab:readings}| to refer to the numbered table in the
% text. Both calls are part of the documented source.
% The final audit in \emph{The Measurement Record} uses the same keys for
% the missing-minute diagram and its table of estimation errors.
% \changes{0.0.1}{2026-12-02}{Use hvfloat in the book for the missing-minute diagram and its error table.}
%
% \chapter{Width and page breaks}\label{manual:layout}
% The default A4 sheet allocates 111\,mm to the main text and 48\,mm to
% the margin column. A 7\,mm gutter separates them. The 27\,mm inner
% inset includes 3\,mm for binding. The outer trim allowance is 17\,mm.\sidenote{The default size is 10\,pt. This manual and the specimen
% request 11\,pt. The two-sided layout mirrors the columns at the spine.}
%
% \section*{One object across two columns}
% \changes{0.0.1}{2026-12-02}{Extend single-page tables and code into the outer margin using the final page side.}
% A table can use the full 166\,mm between the outer and inner
% margins. The two lines below follow the actual columns. The
% space between them is the 7\,mm gutter.
% \par\addvspace{8pt}
% \manualpagewidths
% \par\addvspace{12pt}
% Put the caption and table inside a starred table float.
% Inside the block, \verb|\linewidth| spans both columns and the gutter.
% \begin{lstlisting}
% \begin{table*}[tbp]
%     \caption{Reported means}\label{tab:means}
%     \begin{tabular*}{\linewidth}
%         {l@{\extracolsep{\fill}}r}
%       Working copy & Mean (°C) \\
%       All readings & 19.59 \\
%     \end{tabular*}
% \end{table*}
% \end{lstlisting}
% Use this layout for an object that fits on one page. Keep notes clear
% of the space it occupies. For the forty readings in the specimen,
% \texttt{longtblr} uses the main column and repeats the header after
% each page break with \texttt{rowhead=1}.
%
% \section*{Change the design in the preamble}
% Set the binding correction with KOMA and the outer column with LuaTufte.
% Both settings also work in the class options.
% \begin{lstlisting}
% \KOMAoptions{BCOR=5mm}
% \LuaTufteSetup{margin-width=45mm,margin-gap=7mm}
% \setkomafont{chapter}{\huge\itshape}
% \newtheorem{result}{Result}[chapter]
% \newtheorem{lemma}[result]{Lemma}
% \end{lstlisting}
% \changes{0.0.1}{2026-12-02}{Check shared theorem counters alongside figure and table numbering.}
% \chapter{Choosing individual settings}\label{manual:profile}
% \changes{0.0.1}{2026-12-02}{Offer wide unnumbered chapters, outer captions, margin footnotes and independent marginal typography.}
% \changes{0.0.1}{2026-12-02}{Apply the book layout to the class, manual and specimen.}
% The bare class declaration gives a book wide unnumbered chapters,
% ragged-right prose, and captions and footnotes in the outer margin.
% The specimen adds heading numbers for its scientific cross-references.
% \begin{lstlisting}
% \documentclass[sections=numbered]{luatufte}
% \end{lstlisting}
% A numbered wide chapter opens with its number on a separate line.
% A \verb|\paragraph| starts an italic run-in heading.
% The standard \texttt{secnumdepth} counter controls how deeply the
% numbering goes. Select other changes individually, for example
% \begin{lstlisting}
% note-placement=foot
% body-align=justified
% float-captions=standard
% chapter-style=compact
% \end{lstlisting}
%
% \section*{One caption, two placements}
% With outer captions, write the ordinary figure or table. Its caption
% may precede or follow the object. Short list entries, starred captions
% and labels follow the usual syntax. The object stays in the text
% column and its legend appears in the outer column on the float page.
% Wrapped lines begin at the label edge in marginal, body-width and
% full-width captions, including listings and continued table captions.
% \changes{0.0.1}{2026-12-02}{Align caption continuations and set wide-float legends in the note measure.}
% \begin{lstlisting}
% \begin{figure}[tbp]
%   \setfloatalignment{c}
%   \rule{\linewidth}{2pt}
%   \caption[Scale]{The full length represents one hour.}
%   \label{fig:scale}
% \end{figure}
% \end{lstlisting}
% The letters \texttt{t}, \texttt{c} and \texttt{b} select top,
% centre and bottom alignment.
% Lower it with \verb|\setcaptionoffset{2pt}|. Override the predicted
% side with \verb|\forcerectofloat| or \verb|\forceversofloat|.
%
% \clearpage
% \section*{Choosing the width of a legend}
% In \texttt{figure*} and \texttt{table*} the object spans both columns.
% The legend occupies the note measure. Put \verb|\caption| above or below
% the object in the source. Select \texttt{wide-captions=full} for a
% legend spanning the whole object.
%
% For the reference A4 proportions use \texttt{measure=tufte-a4}.
% At the default binding allowance the columns and gap measure 107, 49.4
% and 8.2\,mm. Add \texttt{margin-side=right} to keep the same text origin
% on both pages while the running heads alternate.
%
% \section*{Material that continues onto another page}
% Use \texttt{fullwidth} around paragraphs or a listing. Each page
% segment mirrors independently. Keep insertions such as footnotes,
% marginal notes and floats outside the environment. For a table
% that supplies its own page breaks, give it a run of full-width pages.
% \begin{lstlisting}
% \begin{fullwidthpages}
%   \begin{longtable}{lr}
%     Record & Value \\ \endhead
%     M01 & 19.26 \\
%   \end{longtable}
% \end{fullwidthpages}
% \end{lstlisting}
% Load \texttt{longtable} in the preamble for this example. After the
% closing page break, the regular text and margin measures resume.
% For a subject index, load \texttt{makeidx}, issue \verb|\makeindex|
% in the preamble, mark terms with \verb|\index{term}| and place
% \verb|\printindex| at the end. The specimen has a working three-column
% index. The project build invokes MakeIndex automatically.
%
% \clearpage
% \section*{Notes, extracts and letterspacing}
% In margin mode \verb|\footnote[][2pt]{Source note.}| moves a note down
% two points. Notes in a minipage keep their local marker and placement.
% \verb|\footcite| continues to use the chosen biblatex style.
% The \texttt{sidenote}, \texttt{marginnote}, \texttt{caption} and
% \texttt{citation} keys take \texttt{justified}, \texttt{raggedleft},
% \texttt{raggedright}, \texttt{raggedouter} or \texttt{auto}.
% Use \texttt{marginnote-syntax=tufte} for
% \verb|\marginnote[3pt]{Text}|. The native form is \verb|\marginnote{Text}[3pt]|.
% Adjacent numbered notes print a comma between their marks.
% Load \texttt{luatufte-biblio} with \texttt{cite=margin} to print an
% unstarred \verb|\cite[42]{key}| as a full entry beside the text.
% Inside a sidenote it prints in that note. The default is \texttt{cite=inline}.
% The auto setting follows body alignment. Set all four with \texttt{marginals}.
% Use \texttt{sfsidenotes} for sans-serif notes, or customise one font.
% \begin{lstlisting}
% \setsidenotefont{\footnotesize\itshape}
% \setcaptionfont{\small\sffamily}
% \end{lstlisting}
% Set the font for an unnumbered note with \verb|\setmarginnotefont|.
% A marginal citation has its own setter, \verb|\setcitationfont|.
% The KOMA font element \texttt{extract}
% styles \texttt{quote}, \texttt{quotation} and \texttt{verse}.
% Use \verb|\smallcaps{Text}| or \verb|\allcaps{Text}| for tracked
% capitals, and \verb|\tuftebreak| for a paragraph break with space.
%
% \section*{Contents and running heads}
% Set \verb|\setcounter{tocdepth}{1}| to include sections. Shorten long
% running heads with \verb|\runningtitle{Field Notes}| and the optional
% chapter title. With \verb|\frontmatter| and \verb|\mainmatter| the
% Arabic folios continue across the division. To restart after Roman
% preliminaries, use \verb|\frontmatter[roman]| and \verb|\mainmatter[arabic]|.
%
% \chapter{A typesetting specimen}\label{manual:specimen}
% These examples come from \emph{The Measurement Record}. The manual
% prints the book's source and sets it again here. The finished reading
% edition is supplied as \path{luatufte-specimen.pdf}.
%
% \section*{The book declaration}
% \booksource{booksetup}
% Numbering gives the audit a compact way to refer back to the original
% calculation. Opening chapters on either side also allows a part divider
% and its first chapter to form a spread.
%
% \section*{Two kinds of evidence in the margin}
% \bookresult{auditnote}\par
% \booksource{auditnote}
% \bookresult{auditcite}\par
% \booksource{auditcite}
% The note gives the denominator. The citation supplies a definition
% and its locator. Both marks belong to the same sequence.
%
% \clearpage
% \section*{A comparison across both columns}
% \bookresult{meanrows}
% \bookresult{auditwidth}
% Table~\ref{tab:audit-width} sets the two populations side by side.
% The narrow legend sits above the outer edge. The rows use the full width.
% \booksource{auditwidth}
% The last command supplies these rows.
% \begin{wideblock}\booksource{meanrows}\end{wideblock}
%
% \section*{A caption beside the data}
% \bookresult{estimaterows}
% \bookresult{hvtablecall}
% \booksource{hvtablecall}
% Here the object fits the text column. Its legend identifies the sign
% convention for the error. The audit in the reading edition uses this
% same table after deriving the midpoint estimate.
%
% \clearpage
% \section*{A smaller book and its floating objects}
% \changes{0.0.1}{2026-12-02}{Add the B5 measure, caption offsets and ordering, float styles and reusable title fields.}
% Select \texttt{B5} to use the 176 by 250\,mm trim and the
% \textsf{tufte-book} B5 proportions. At the default 3\,mm binding
% allowance the text is 102.66\,mm wide, the gutter 7.33\,mm and the
% note column 36.66\,mm. A bare KOMA \texttt{b5paper} changes the trim
% and retains the current LuaTufte measure.
% \begin{lstlisting}
% \documentclass[B5,wide-caption-order=alignment]{luatufte}
% \usepackage[chapter]{algorithm}
% \publisher[Field Press]{Field Press\thanks{Imprint credit.}}
% \end{lstlisting}
% \verb|\plainpublisher| prints the short imprint.\par
% \verb|\thanklesspublisher| prints the full imprint without credits.
% Title and author have the same two forms. \verb|\thedate| omits credits.
%
% \section*{Moving a legend}
% \begin{lstlisting}
% \caption[Scale][4pt]{Calibration scale.}
% \end{lstlisting}
% This lowers the legend by 4\,pt. A negative length raises it.
% Empty first brackets use the full text for the list entry.
% Starred floats normally follow source order. With the alignment
% option above, a bottom float (\texttt{[b]}) sets its legend
% above the object. Other placements set it below.
% Inside the float, \verb|\setfloatalignment{b}| or
% \verb|\setfloatalignment{t}| overrides that choice.
%
% \section*{Algorithms and custom floats}
% Load \textsf{algorithm} for a numbered algorithm with an outer legend.
% Choose a plain, ruled or boxed body in the package options.
% \begin{lstlisting}
% \begin{algorithm}[tb]
%   Read the next sample. Stop at the first missing value.
%   \caption[Gap search]{Locate the first gap.}\label{alg:gap}
% \end{algorithm}
% \end{lstlisting}
% With \textsf{float}, select a style before declaring a new float.
% \begin{lstlisting}
% \floatstyle{tufteruled}
% \newfloat{observation}{tbp}{lob}
% \end{lstlisting}
% The other styles are \texttt{tufteplain}, \texttt{tufteplaintop}
% and \texttt{tufteboxed}.
%
% \chapter{Building from the documented source}\label{manual:source}
% \changes{0.0.1}{2026-12-02}{Ship the specimen PDF and its six LPPL sources in the DTX.}
% \texttt{luatufte.dtx} contains the manual driver, the explanatory text and
% the implementation. Edit the class or bibliography code there. Running the
% installer extracts the runtime files, quickstart and six specimen sources.
% The book and manual share the extracted bibliography.
%
% \begin{lstlisting}[language={}]
% make example      # full specimen
% make quickstart   # example in Getting started
% make doc          # this manual
% make ctan         # local distribution archive
% \end{lstlisting}
% Run these targets at the project root. Find the PDFs under the build
% directory. The CTAN archive is saved as \path{build/ctan/luatufte.zip}.
% From the unpacked distribution, run \texttt{tex luatufte.ins}, then
% \texttt{latexmk -lualatex luatufte.dtx} to rebuild this manual.
%
% \section*{Design and provenance}
% The manifest records kaobook's pinned sources and notices.
% Tufte-LaTeX 3.5.2 (Apache~2.0) provides the visual reference for the
% title, contents and running heads. LuaTufte implements them on KOMA
% under LPPL~1.3c or later. The part label draws on Tufte's
% \emph{The Visual Display of Quantitative Information}.
% \AtNextBibliography{\small}\printbibliography[heading=subbibliography,title={Sources cited in this manual}]
%
% \chapter{Annotated implementation}\label{manual:implementation}
% \changes{0.0.1}{2026-12-02}{Use the book geometry throughout the manual and widen only implementation listings.}
% DocStrip extracts the class and bibliography package from separate guards.
% The public commands and environments use the LaTeX kernel. The book uses the typearea package loaded by KOMA-Script.
% The public title command retains KOMA's optional starting page number.
% Its private renderer uses expl3 under the \verb|__luatufte_| prefix.
% \changes{0.0.1}{2026-12-02}{Explain layout and citation choices beside the source listings.}
% \begingroup
% \interlinepenalty=10000
% \AddToHook{env/macrocode/before}{\par\nobreak\addvspace{6pt plus 1pt}%
%   \nobreak\begin{wideblock}}
% \AddToHook{env/macrocode/after}{\end{wideblock}\addvspace{8pt plus 1pt}}
% \section*{The engine and base class}
% \changes{0.0.1}{2026-12-02}{Require LuaLaTeX before loading KOMA-Script and forward book options.}
% LuaLaTeX provides the font and mathematics engines. The check runs before loading KOMA-Script. Defaults and author-supplied options both pass to the base class.
%    \begin{macrocode}
%<*class>
\NeedsTeXFormat{LaTeX2e}[2022-06-01]
\ProvidesClass{luatufte}[2026/12/02 v0.0.1 LuaLaTeX margin book derived from kaobook]
\ExplSyntaxOn
\sys_if_engine_luatex:F
  {
    \prop_gput:Nnn \g_msg_module_type_prop {luatufte}{Class}
    \msg_new:nnn {luatufte}{wrong-engine}
      {LuaTufte~requires~LuaLaTeX.~Run~lualatex~on~this~document.}
    \msg_fatal:nn {luatufte}{wrong-engine}
  }
\bool_new:N \l__luatufte_fonts_bool
\bool_set_true:N \l__luatufte_fonts_bool
\bool_new:N \l__luatufte_tracking_bool
\bool_set_true:N \l__luatufte_tracking_bool
\bool_new:N \l__luatufte_hyper_bool
\bool_set_true:N \l__luatufte_hyper_bool
\bool_new:N \l__luatufte_toc_bool
\bool_set_true:N \l__luatufte_toc_bool
%    \end{macrocode}
% The class installs its book layout before processing author options.
% Each explicit option then changes the relevant setting.
%    \begin{macrocode}
\dim_new:N \l__luatufte_inner_dim
\dim_new:N \l__luatufte_outer_dim
\bool_new:N \l__luatufte_right_bool
\bool_new:N \l__luatufte_bfive_bool
\cs_new_protected:Npn \__luatufte_measure:nnnn #1#2#3#4
  {
    \bool_set_false:N \l__luatufte_bfive_bool
    \dim_set:Nn \l__luatufte_inner_dim {#1}
    \dim_set:Nn \l__luatufte_outer_dim {#2}
    \keys_set:nn {luatufte}{margin-width=#3,margin-gap=#4}
  }
\keys_define:nn { luatufte }
  {
    margin-width .dim_set:N = \l__luatufte_margin_dim,
    margin-width .initial:n = 48mm,
    margin-gap   .dim_set:N = \l__luatufte_gap_dim,
    margin-gap   .initial:n = 7mm,
    measure .choice:,
    measure / book .code:n =
      {\__luatufte_measure:nnnn {24mm}{17mm}{48mm}{7mm}},
    measure / tufte-a4 .code:n =
      {\__luatufte_measure:nnnn {21.8mm}{20.6mm}{49.4mm}{8.2mm}},
    measure / tufte-b5 .code:n =
      {
        \__luatufte_measure:nnnn {11.66mm}{14.69mm}{36.66mm}{7.33mm}
        \bool_set_true:N \l__luatufte_bfive_bool
      },
    measure .initial:n = book,
    B5 .code:n = {\keys_set:nn {luatufte}{measure=tufte-b5}
      \IfClassLoadedTF{scrbook}{\KOMAoptions{paper=b5}}
        {\PassOptionsToClass{b5paper}{scrbook}}},
    wide-caption-order .choices:nn = {source,alignment}
      {\tl_set_eq:NN \l__luatufte_wide_order_tl \l_keys_choice_tl},
    wide-caption-order .initial:n = source,
    margin-side .choices:nn = {outer,right}
      { \str_if_eq:nnTF {#1}{right}
          {\bool_set_true:N \l__luatufte_right_bool}
          {\bool_set_false:N \l__luatufte_right_bool} },
    wide-captions .choices:nn = {margin,full}
      { \tl_set_eq:NN \l__luatufte_wide_caption_tl \l_keys_choice_tl },
    wide-captions .initial:n = margin,
    marginnote-syntax .choices:nn = {native,tufte}
      { \tl_set_eq:NN \l__luatufte_margin_syntax_tl \l_keys_choice_tl },
    marginnote-syntax .initial:n = native,
    chapter-style .choices:nn = {compact,wide}
      { \tl_set_eq:NN \l__luatufte_chapter_tl \l_keys_choice_tl },
    sections .choices:nn = {numbered,unnumbered}
      { \tl_set_eq:NN \l__luatufte_numbers_tl \l_keys_choice_tl },
    float-captions .choices:nn = {standard,outer}
      { \tl_set_eq:NN \l__luatufte_floats_tl \l_keys_choice_tl },
    note-placement .choices:nn = {foot,margin}
      { \tl_set_eq:NN \l__luatufte_notes_tl \l_keys_choice_tl },
    body-align .choices:nn = {justified,raggedright}
      { \tl_set_eq:NN \l__luatufte_body_tl \l_keys_choice_tl },
%    \end{macrocode}
% The profile is shorthand for individual keys. Font selection,
% tracking, hyperlinks and contents styling also have independent
% switches for manuscripts that supply their own setup.
%    \begin{macrocode}
    marginals .meta:n = {sidenote=#1,marginnote=#1,citation=#1,caption=#1},
    tufte .meta:n = {chapter-style=wide,float-captions=outer,
      sections=unnumbered,note-placement=margin,
      body-align=raggedright,marginals=auto},
    sfsidenotes .code:n = {\bool_set_true:N \l__luatufte_sans_bool},
    nofonts .code:n = {\bool_set_false:N \l__luatufte_fonts_bool},
    fonts .code:n = {\bool_set_true:N \l__luatufte_fonts_bool},
    nols .code:n = {\bool_set_false:N \l__luatufte_tracking_bool},
    ls .code:n = {\bool_set_true:N \l__luatufte_tracking_bool},
    nohyper .code:n = {\bool_set_false:N \l__luatufte_hyper_bool},
    hyper .code:n = {\bool_set_true:N \l__luatufte_hyper_bool},
    toc .code:n = {\tl_if_empty:nTF {#1}
      {\bool_set_true:N \l__luatufte_toc_bool}{\PassOptionsToClass{toc=#1}{scrbook}}},
    toc .default:n = {},
    notoc .code:n = {\bool_set_false:N \l__luatufte_toc_bool},
    justified .meta:n = {body-align=justified},
    symmetric .code:n = {\keys_set:nn {luatufte}{margin-side=outer}
      \PassOptionsToClass{twoside}{scrbook}},
    nobib .code:n = {},
    notitlepage .code:n = {\PassOptionsToClass{titlepage=false}{scrbook}},
    bidi .code:n = {\bool_set_true:N \l__luatufte_bidi_bool},
    nobidi .code:n = {\bool_set_false:N \l__luatufte_bidi_bool},
    debug .code:n = {\PassOptionsToPackage{draft}{graphicx}
      \AtBeginDocument{\PrintTufteSettings}}
  }
%    \end{macrocode}
%
% Each remaining option goes to \texttt{scrbook} with its original value.
% For example, LuaTufte consumes \texttt{margin-gap=6mm} itself, while
% KOMA interprets \texttt{BCOR=5mm} as a binding correction.
%    \begin{macrocode}
\bool_new:N \l__luatufte_bidi_bool
\bool_new:N \l__luatufte_sans_bool
\clist_map_inline:nn {sidenote,marginnote,citation,caption}
  {
    \keys_define:nn {luatufte}
      {
        #1 .choices:nn = {auto,justified,raggedleft,raggedright,raggedouter}
          { \tl_set_eq:cN {l__luatufte_#1_align_tl} \l_keys_choice_tl },
      }
  }
\keys_set:nn {luatufte}{tufte}
\PassOptionsToClass{a4paper,fontsize=10pt,twoside,open=any,BCOR=3mm}{scrbook}
\DeclareOption*
  {
    \keys_set_known:nVN { luatufte } \CurrentOption \l_tmpa_tl
    \tl_if_empty:NF \l_tmpa_tl
      { \exp_args:NV \PassOptionsToClass \CurrentOption {scrbook} }
  }
\ProcessOptions*\relax
\bool_if:NT \l__luatufte_bidi_bool {\PassOptionsToPackage{bidi=basic}{babel}}
\ExplSyntaxOff
\LoadClass{scrbook}
\KOMAoptions{areasetadvanced,mpinclude,headinclude=false,footinclude=false}
%    \end{macrocode}
%
% \section*{Setting the book area}
% \changes{0.0.1}{2026-12-02}{Add typearea measures, fixed-right or mirrored margins and binding correction.}
% KOMA reports the binding correction as a braced option value when it
% calculates an area. The callback unwraps that value and saves a length.
% A later request for \texttt{BCOR=current} can then reuse the last
% numerical correction.
%    \begin{macrocode}
\ExplSyntaxOn
\dim_new:N \l__luatufte_binding_dim
\cs_new_protected:Npn \__luatufte_store_binding:n #1
  { \dim_set:Nn \l__luatufte_binding_dim { \use:n #1 } }
\cs_new_protected:Npn \__luatufte_read_binding:
  { \KOMAoptionOf[\__luatufte_store_binding:n]{typearea.sty}{BCOR} }
\__luatufte_read_binding:
\AfterCalculatingTypearea{\__luatufte_read_binding:}
%    \end{macrocode}
%
% On A4 the main column is $210-3-24-17-48-7=111$\,mm wide.
% The trim insets total 41\,mm in the default measure. The 55\,mm
% in the height calculation reserves 27\,mm above the text and 28\,mm
% below it. Checking both results before calling \verb|\areaset| catches,
% for example, a note column that consumes the entire page.
%    \begin{macrocode}
\cs_new_protected:Npn \__luatufte_set_area:
  {
    \dim_set:Nn \l_tmpa_dim
      { \paperwidth - \l__luatufte_binding_dim
        - \l__luatufte_inner_dim - \l__luatufte_outer_dim
        - \l__luatufte_margin_dim - \l__luatufte_gap_dim }
    \bool_if:nTF
      {
        \dim_compare_p:n { \l_tmpa_dim > 0pt } &&
        \dim_compare_p:n { \l__luatufte_margin_dim > 0pt } &&
        \dim_compare_p:n { \l__luatufte_gap_dim >= 0pt } &&
        \dim_compare_p:n { \paperheight > 55mm }
      }
      {
        \dim_set:Nn \l_tmpb_dim {\paperheight-55mm}
        \bool_if:NT \l__luatufte_bfive_bool {\dim_set:Nn \l_tmpb_dim {532pt}}
        \areaset[current]{\l_tmpa_dim}{\l_tmpb_dim}
      }
      { \ClassError{luatufte}{Invalid~book~dimensions}
          {Check~the~paper~size,~binding~correction,~margin-width~and~margin-gap.} }
  }
%    \end{macrocode}
% TeX measures the side and top margins from a point one inch inside the
% sheet. For a recto the text begins 24\,mm plus the binding allowance
% from the left trim. For a verso its right edge is the same distance
% from the opposite trim. A one-sided book uses the recto origin on
% every page. The header occupies the space above the top text edge.
%    \begin{macrocode}
\cs_new_protected:Npn \__luatufte_position_area:
  {
    \dim_set_eq:NN \marginparwidth \l__luatufte_margin_dim
    \dim_set_eq:NN \marginparsep \l__luatufte_gap_dim
    \dim_set:Nn \oddsidemargin { \l__luatufte_inner_dim + \l__luatufte_binding_dim - 1in }
    \if@twoside
      \dim_set:Nn \evensidemargin { \paperwidth - \textwidth - \oddsidemargin - 2in }
    \else
      \dim_set_eq:NN \evensidemargin \oddsidemargin
    \fi
    \bool_if:NT \l__luatufte_right_bool
      {\dim_set_eq:NN \evensidemargin \oddsidemargin}
    \dim_set:Nn \headheight {18pt}
    \dim_set:Nn \headsep {6mm}
    \dim_set:Nn \footskip {12mm}
    \dim_set:Nn \topmargin { 27mm - 1in - \headheight - \headsep }
    \bool_if:NT \l__luatufte_bfive_bool
      {
        \dim_set:Nn \topmargin {13.88mm-1in}
        \dim_set:Nn \headheight {14pt}
        \dim_set:Nn \headsep {28pt}
      }
  }
%    \end{macrocode}
%
% KOMA runs this hook after it has set the area and before it activates
% the output dimensions. This restores the outer column on a repeated
% area calculation. The preamble command reads any changed note dimensions
% and refits the text. An empty argument applies the current settings.
%    \begin{macrocode}
\AfterSettingArea
  { \__luatufte_read_binding: \__luatufte_position_area: }
\NewDocumentCommand \LuaTufteSetup { m }
  {
    \keys_set:nn { luatufte } {#1}
    \__luatufte_set_area:
  }
\@onlypreamble\LuaTufteSetup
\LuaTufteSetup{}
\ExplSyntaxOff
%    \end{macrocode}
%
% \section*{The book typefaces}
% \changes{0.0.1}{2026-12-02}{Set mirrored outer notes and a binding allowance with ETbb text and Pagella mathematics.}
% ETbb supplies the book's roman face. Matching the sans and monospaced
% x-heights keeps labels and code proportionate beside the body. The
% explicit filenames resolve the same four faces from the TeX installation.
% Pagella Math supplies a separate OpenType mathematics font.
%    \begin{macrocode}
\RequirePackage{unicode-math}
\ExplSyntaxOn
\bool_if:NT \l__luatufte_fonts_bool
  {
\setmainfont{ETbb}[Extension=.otf,UprightFont=*-Regular,
  ItalicFont=*-Italic,BoldFont=*-Bold,BoldItalicFont=*-BoldItalic,Scale=1.06]
\setsansfont{GilliusADF}[Extension=.otf,UprightFont=*-Regular,
  ItalicFont=*-Italic,BoldFont=*-Bold,BoldItalicFont=*-BoldItalic,Scale=MatchLowercase]
\setmonofont{SourceCodePro}[Extension=.otf,UprightFont=*-Regular,
  ItalicFont=*-RegularIt,BoldFont=*-Bold,BoldItalicFont=*-BoldIt,Scale=MatchLowercase]
\setmathfont{texgyrepagella-math.otf}
  }
\ExplSyntaxOff
%    \end{macrocode}
%
% \section*{Headings and running matter}
% \changes{0.0.1}{2026-12-02}{Set part dividers with a light uppercase label and a flush-left roman title, italic chapter openings and small-cap paragraph leads.}
% In \emph{The Visual Display of Quantitative Information}, Tufte names the
% first division with an uppercase label followed by a mixed-case title.
% For this edition both lines share the left edge of the text column.
% The small label and regular-weight title distinguish their roles. The
% 24/36\,pt title setting comes from the Tufte-LaTeX heading table.
%    \begin{macrocode}
\RequirePackage{microtype,xcolor}
\definecolor{luatufteblue}{HTML}{204D68}
\definecolor{luatuftepetrol}{HTML}{12686A}
\linespread{1.08}
\setkomafont{disposition}{\normalfont\rmfamily\mdseries}
%    \end{macrocode}
%
% KOMA owns numbering, contents entries, PDF destinations and page opening.
% Capitalise only the printed label so the language and Roman numeral come
% from the book. A starred part skips the label and its gap. The start skip
% places the first line near the upper third, independently of title length.
% Reset the body leading before selecting an exact title baseline.
%    \begin{macrocode}
\ExplSyntaxOn
\cs_new_protected:Npn \__luatufte_part_font:nn #1#2
  { \normalfont \rmfamily \mdseries \linespread{1} \fontsize{#1}{#2} \selectfont }
\setkomafont{part}{\__luatufte_part_font:nn {24pt}{36pt}}
\setkomafont{partprefix}
  {\__luatufte_part_font:nn {11pt}{15pt}\__luatufte_tracking:n {8}}
\RenewDocumentCommand \partformat { }
  { \MakeUppercase{\partname} \nobreakspace \thepart \autodot }
\RenewDocumentCommand \raggedpart { } { \raggedright }
\RedeclareSectionCommand
  [pagestyle=empty,beforeskip=.24\textheight,innerskip=8pt]{part}
%    \end{macrocode}
%
% A short phrase can introduce a new thought without adding a heading
% to the contents. The vertical skip merges with adjacent space. The
% local font group ends at the closing brace, so the rest of the sentence
% returns to the author's surrounding type.
%    \begin{macrocode}
\newkomafont{thought}{\normalfont\scshape}
\NewDocumentCommand \newthought { m }
  {
    \tuftebreak
    \noindent { \usekomafont{thought} #1 }
  }
\ExplSyntaxOff
\setkomafont{chapter}{\huge\itshape\color{luatufteblue}}
\setkomafont{section}{\Large\itshape}
\setkomafont{subsection}{\large\itshape}
\ExplSyntaxOn
\bool_if:NT \l__luatufte_toc_bool
  {
\setcounter{tocdepth}{0}
\setkomafont{partentry}{\normalfont\Large\itshape}
\setkomafont{chapterentry}{\normalfont\large\itshape}
\DeclareTOCStyleEntries[
  raggedentrytext,raggedpagenumber,linefill=\quad,
  pagenumberbox=\mbox,pagenumberformat=\normalfont
]{tocline}{part,chapter}
\DeclareTOCStyleEntry[indent=1em,beforeskip=.45\baselineskip]{tocline}{chapter}
%    \end{macrocode}
% Figure and table lists have their own files. Give their entries level
% zero so that chapter-only contents still print the two lists. A short
% caption is printed beside its folio using KOMA's TOC entry formatter.
%    \begin{macrocode}
\DeclareTOCStyleEntries[level=0,raggedentrytext,raggedpagenumber,
  linefill=\quad,pagenumberbox=\mbox]{tocline}{figure,table}
  }
\ExplSyntaxOff
\RedeclareSectionCommand[beforeskip=0pt,afterskip=1.1\baselineskip]{chapter}
\setkomafont{caption}{\small}
\setkomafont{captionlabel}{\itshape\color{luatuftepetrol}}
%    \end{macrocode}
%
% \changes{0.0.1}{2026-12-02}{Set chapter-level contents with adjacent folios and alternate the book and chapter in the outer running heads.}
% The contents keep KOMA's number boxes and links. A fixed gap and
% a natural-width page number keep the folio with the end of the title.
% Authors can raise \texttt{tocdepth} to include sections.
%
% Capture the title when it is supplied, since an in-page title can
% release its metadata after printing. Credits and explicit line breaks
% belong on the title page. A long title can supply a short running form.
%    \begin{macrocode}
\RequirePackage{scrlayer-scrpage}
\ExplSyntaxOn
\tl_new:N \g__luatufte_book_title_tl
\tl_new:N \g__luatufte_running_title_tl
\cs_new_eq:NN \__luatufte_untitled: \@title
\AtBeginDocument
  {
    \cs_if_eq:NNF \@title \__luatufte_untitled:
      { \tl_gset_eq:NN \g__luatufte_book_title_tl \@title }
  }
%    \end{macrocode}
% Keep reusable title data outside the title-page group. Remove credit text
% before the metadata reaches running heads or PDF strings.
%    \begin{macrocode}
\cs_new:Npn \thanklesstitle {}
\cs_new:Npn \thanklessauthor {}
\cs_new:Npn \thanklesspublisher {}
\cs_new_eq:NN \plaintitle \thanklesstitle
\cs_new_eq:NN \plainauthor \thanklessauthor
\cs_new_eq:NN \plainpublisher \thanklesspublisher
\cs_new:Npn \thedate {\today}
%    \end{macrocode}
% Capture a credit-free copy for running text while the title renderer
% retains the original fields. Protect author separators and line breaks
% during expansion. An explicit short form takes precedence for metadata.
%    \begin{macrocode}
\cs_new_protected:Npn \__luatufte_without_credits:Nn #1#2
  {
    \group_begin:
      \cs_set_eq:NN \thanks \use_none:n
      \cs_set:Npn \and {\exp_not:N \and}
      \cs_set:Npn \\ {\exp_not:N \\}
      \protected@xdef #1 {#2}
    \group_end:
  }
\cs_new_protected:Npn \__luatufte_metadata:NNnn #1#2#3#4
  {
    \__luatufte_without_credits:Nn #2 {#4}
    \tl_if_blank:nTF {#3}{\cs_gset_eq:NN #1 #2}{\cs_gset:Npn #1 {#3}}
  }
%    \end{macrocode}
% Let KOMA store the display fields and expose the short forms separately.
%    \begin{macrocode}
\NewCommandCopy \__luatufte_title:n \title
\NewCommandCopy \__luatufte_author:n \author
\NewCommandCopy \__luatufte_date:n \date
\NewCommandCopy \__luatufte_publishers:n \publishers
\RenewDocumentCommand \title {O{} m}
  {
    \__luatufte_title:n {#2}
    \tl_gset:Nn \g__luatufte_book_title_tl {#2}
    \__luatufte_metadata:NNnn \plaintitle \thanklesstitle {#1}{#2}
    \tl_if_blank:nF {#1}{\runningtitle{#1}}
    \cs_if_exist:NT \hypersetup {\hypersetup{pdftitle={\plaintitle}}}
  }
\RenewDocumentCommand \author {O{} m}
  {
    \__luatufte_author:n {#2}
    \__luatufte_metadata:NNnn \plainauthor \thanklessauthor {#1}{#2}
    \cs_if_exist:NT \hypersetup {\hypersetup{pdfauthor={\plainauthor}}}
  }
\RenewDocumentCommand \date {m}
  { \__luatufte_date:n {#1} \__luatufte_without_credits:Nn \thedate {#1} }
\NewDocumentCommand \publisher {O{} m}
  {
    \__luatufte_publishers:n {#2}
    \__luatufte_metadata:NNnn \plainpublisher \thanklesspublisher {#1}{#2}
  }
\RenewDocumentCommand \publishers {m}{\publisher{#1}}
\NewDocumentCommand \newlinetospace {m}
  {
    \group_begin:
      \RenewDocumentCommand \\ {s o}{\space}
      \cs_set_eq:NN \newline \space
      #1
    \group_end:
  }
%    \end{macrocode}
% An explicit running title takes priority in the page header.
%    \begin{macrocode}
\NewDocumentCommand \runningtitle { m }
  { \tl_gset:Nn \g__luatufte_running_title_tl {#1} }
\cs_new_protected:Npn \__luatufte_book_head:
  {
    \group_begin:
      \cs_set_eq:NN \thanks \use_none:n
      \RenewDocumentCommand \footnote { o +m } { }
      \cs_set_eq:NN \label \use_none:n
      \RenewDocumentCommand \\ { s o } { \space }
      \cs_set_eq:NN \newline \space
      \tl_if_empty:NTF \g__luatufte_running_title_tl
        { \tl_use:N \g__luatufte_book_title_tl }
        { \tl_use:N \g__luatufte_running_title_tl }
    \group_end:
  }
%    \end{macrocode}
% Extend the header to the trim-side edge of the note column after each
% layout computation. Plain chapter openers show just the outer folio.
% An empty part or title page keeps its own page style.
%    \begin{macrocode}
\clearpairofpagestyles
\automark{chapter}
\cs_new_protected:Npn \__luatufte_head_width:
  {
    \bool_if:NTF \l__luatufte_right_bool
      {\exp_args:Ne \KOMAoptions
        {headwidth=textwithmarginpar\c_colon_str 0pt\c_colon_str 0pt}}
      {\KOMAoptions{headwidth=textwithmarginpar}}
  }
\__luatufte_head_width:
\AfterSettingArea{\__luatufte_head_width:}
\lehead[\pagemark]{\pagemark\if@mainmatter\quad\__luatufte_book_head:\fi}
\rohead[\pagemark]{\if@mainmatter\leftmark\quad\fi\pagemark}
\ExplSyntaxOff
\setkomafont{pageheadfoot}{\normalfont\scshape\small}
\pagestyle{scrheadings}
\raggedbottom
%    \end{macrocode}
%
% \section*{A full title page}
% \changes{0.0.1}{2026-12-02}{Set display and in-page titles on one axis and continue Arabic book folios.}
% The title reads KOMA's stored metadata. Its font elements remain
% configurable with \verb|\setkomafont|. KOMA handles title credits,
% first-as-cover margins and extended front matter (half-title,
% frontispiece, title back or dedication) with its original renderer.
%    \begin{macrocode}
%% Independent LuaTufte title layout. See MANIFEST.md for the design reference.
\ExplSyntaxOn
\newkomafont{displayauthor}{\normalfont\sffamily\LARGE
  \__luatufte_tracking:n {14}\color{luatuftepetrol}}
\newkomafont{displaysubtitle}{\normalfont\Large\itshape}
\newkomafont{displayimprint}{\normalfont\sffamily\large
  \__luatufte_tracking:n {12}}
\newkomafont{displaydate}{\normalfont\small}
\newkomafont{displaytitle}{\normalfont\sffamily\mdseries
  \fontsize{36}{42}\selectfont\__luatufte_tracking:n {12}}
%    \end{macrocode}
%
% A dedication or a title back may occupy additional pages. The dispatcher
% keeps KOMA's original title command for these sequences. Both paths
% receive the optional starting page number. Only the ordinary, separate
% title page goes to the renderer below.
%    \begin{macrocode}

\NewCommandCopy \__luatufte_frontmatter: \frontmatter
\NewCommandCopy \__luatufte_mainmatter: \mainmatter
\RenewDocumentCommand \frontmatter {s O{arabic}}
  { \IfBooleanTF{#1}{\__luatufte_frontmatter:*}{\__luatufte_frontmatter:[#2]} }
\RenewDocumentCommand \mainmatter {s O{}}
  { \IfBooleanTF{#1}{\__luatufte_mainmatter:*}{\__luatufte_mainmatter:[#2]} }
%    \end{macrocode}
% KOMA handles credits, covers and the page transition. Its in-page
% renderer reads the same fields as the display page on a single text axis.
% The sans variant tracks its capitals while keeping credit text in its
% original case.
%    \begin{macrocode}
\cs_new_protected:Npn \__luatufte_short_field:nn #1#2
  {
    \tl_if_empty:NF #2
      { { #1 \bool_if:NTF \l__luatufte_sans_bool
          {\sffamily\allcaps{#2}}{\itshape #2} \par } \smallskip }
  }
\cs_set_protected:Npn \@maketitle
  {
    \par \raggedright \setlength{\parindent}{0pt}
    \cs_set_protected:Npn \and {\par}
    \cs_set_eq:NN \footnote \thanks
    \AddToNoCaseChangeList{\thanks\footnote}
    \__luatufte_short_field:nn {\small} \@titlehead
    \__luatufte_short_field:nn {\large} \@subject
    \__luatufte_short_field:nn {\LARGE} \@title
    \__luatufte_short_field:nn {\large} \@subtitle
    \__luatufte_short_field:nn {\Large} \@author
    \__luatufte_short_field:nn {\large} \@date
    \__luatufte_short_field:nn {\small} \@publishers
    \__luatufte_short_field:nn {\small} \@dedication
    \medskip
  }

\NewDocumentCommand \maketitlepage {}
  { \group_begin: \KOMAoptions{titlepage=true}\maketitle \group_end: }
\NewCommandCopy \__luatufte_koma_maketitle:w \maketitle
\RenewDocumentCommand \maketitle { O{1} }
  {
    \bool_if:nTF
      {
        \legacy_if_p:n { @titlepage } &&
        ! \legacy_if_p:n { @titlepageiscoverpage } &&
        \tl_if_empty_p:N \@extratitle && \tl_if_empty_p:N \@frontispiece &&
        \tl_if_empty_p:N \@uppertitleback && \tl_if_empty_p:N \@lowertitleback &&
        \tl_if_empty_p:N \@dedication
      }
      { \__luatufte_title_page:n {#1} }
      { \__luatufte_koma_maketitle:w [#1] }
  }
%    \end{macrocode}
% The full title page uses both columns. Multiple authors may use \verb|\and|
% or line breaks. Credits inside \verb|\thanks| preserve their original case.
%    \begin{macrocode}
\cs_new_protected:Npn \__luatufte_title_page:n #1
  {
    \begin{titlepage}
      \setcounter{page}{#1} \setcounter{footnote}{0}
      \cs_set:Npn \thefootnote { \fnsymbol{footnote} }
      \cs_set_eq:NN \footnote \thanks
      \AddToNoCaseChangeList{\thanks\footnote}
      \setlength{\parindent}{0pt}
%    \end{macrocode}
%
% The title page extends into the notes by one gutter and one margin
% column. The optional starting folio decides which side receives the
% extension. An explicitly even title therefore lines up with the
% outer left edge of a verso.
%    \begin{macrocode}
      \dim_set:Nn \l_tmpa_dim { -\marginparsep - \marginparwidth }
      \bool_if:nTF { \legacy_if_p:n { @twoside } && ! \l__luatufte_right_bool
          && ! \int_if_odd_p:n {#1} }
        { \begin{addmargin}[\l_tmpa_dim]{0pt} }
        { \begin{addmargin}[0pt]{\l_tmpa_dim} }
        \raggedright
        \tl_if_empty:NF \@titlehead
          { { \usekomafont{titlehead} \@titlehead \par } \medskip }
        { \cs_set_protected:Npn \and { \par }
          \usekomafont{displayauthor} \MakeUppercase{\@author} \par }
        \vspace{.22\textheight}
        \tl_if_empty:NF \@subject
          { { \usekomafont{subject} \@subject \par } \smallskip }
        { \usekomafont{displaytitle} \MakeUppercase{\@title} \par }
        \tl_if_empty:NF \@subtitle
          { \medskip { \usekomafont{displaysubtitle} \@subtitle \par } }
%    \end{macrocode}
%
% The elastic space above the imprint absorbs the remaining page height.
% After the credits are printed, their stored text is cleared. Resetting
% the footnote counter lets the first ordinary note in the book start at one.
%    \begin{macrocode}
        \vfill
        { \usekomafont{displayimprint} \MakeUppercase{\@publishers} \par }
        { \usekomafont{displaydate} \@date \par }
      \end{addmargin}
      \@thanks \tl_gclear:N \@thanks
    \end{titlepage}
    \setcounter{footnote}{0}
  }
\ExplSyntaxOff
%    \end{macrocode}
%
% \section*{Notes, figures and tables in the margin}
% \changes{0.0.1}{2026-12-02}{Add unnumbered marginal text, adjustable note and figure positions, and captioned margin tables.}
% An unnumbered \verb|\marginnote| comes from the marginnote package,
% which also supplies this command to hvfloat. It anchors directly to
% the source line. Numbered notes and captioned objects enter the
% kernel's margin queue, which can move them down to avoid one another.
%    \begin{macrocode}
\RequirePackage{caption,marginnote,placeins}
\ExplSyntaxOn
\NewDocumentCommand \TufteLoadHyperref {}
  { \RequirePackage{hyperref}
    \hypersetup{colorlinks,allcolors=luatufteblue,citecolor=luatuftepetrol} }
\@onlypreamble\TufteLoadHyperref
\bool_if:NT \l__luatufte_hyper_bool {\TufteLoadHyperref}
\ExplSyntaxOff
\newkomafont{marginaltext}{\normalfont\footnotesize}
\newkomafont{sidenote}{\usekomafont{marginaltext}}
\newkomafont{marginnote}{\usekomafont{marginaltext}}
\newkomafont{margincitation}{\usekomafont{sidenote}}
\renewcommand*{\marginfont}{\usekomafont{marginnote}}
\newcounter{sidenote}[chapter]
\ExplSyntaxOn
\cs_new_protected:Npn \__luatufte_margin:nn #1#2
  {
    \marginpar
      {
        \dim_compare:nNnTF {#1} = {0pt}
          { #2 }
          { \noindent \raisebox{\dim_eval:n {0pt - \dim_eval:n {#1}}}
              {\parbox[t]{\marginparwidth}{#2}} }
      }
  }
%    \end{macrocode}
% The first optional argument selects a printed mark for one note.
% Give such a note a fresh hyperlink target without advancing the
% sequence used by automatic notes and bibliography citations.
% The second optional argument moves the margin text vertically. A pair
% of cancelling kerns records the immediately preceding mark without
% changing the text width. Any intervening text or space ends the sequence.
%    \begin{macrocode}
\cs_new_protected:Npn \__luatufte_note_mark:n #1
  { \textsuperscript{\textcolor{luatuftepetrol}{#1}} }
\NewHook{luatufte/sidenote/begin}
\NewDocumentCommand \sidenote { O{} O{0pt} +m }
  {
    \mode_leave_vertical:
    \dim_compare:nNnT {\tex_lastkern:D} = {3sp}
      { \tex_unkern:D \kern3sp \__luatufte_note_mark:n {,} }
    \tl_if_blank:nTF {#1}
      { \refstepcounter{sidenote} }
      { \MakeLinkTarget{} \protected@edef\@currentlabel{#1} }
    \__luatufte_note_mark:n {\@currentlabel}
    \__luatufte_margin:nn {#2}
      { \usekomafont{sidenote} \__luatufte_align:n {sidenote}
        \__luatufte_note_mark:n {\@currentlabel} \enspace
        \UseHook{luatufte/sidenote/begin} #3 \par }
    \kern-3sp\kern3sp
  }
%    \end{macrocode}
% Set the caption type inside the local minipage. The same mechanism
% produces a figure or table number, list entry and reference target.
% Its line width follows the actual outer column at the current paper size.
%    \begin{macrocode}
\cs_new_protected:Npn \__luatufte_margin_object:nnn #1#2#3
  {
    \FloatBarrier
    \__luatufte_margin:nn {#2}
      { \begin{minipage}{\marginparwidth}
          \usekomafont{marginaltext}
          \captionsetup{type=#1,font=footnotesize,
            justification=luatufte,singlelinecheck=false}
          #3
        \end{minipage} }
  }
\NewDocumentEnvironment{marginfigure}{O{0pt} +b}
  { \__luatufte_margin_object:nnn {figure}{#1}{#2} } {}
\NewDocumentEnvironment{margintable}{O{0pt} +b}
  { \__luatufte_margin_object:nnn {table}{#1}{#2} } {}
\ExplSyntaxOff
%    \end{macrocode}
%
% \section*{A caption on the outside of a float}
% \changes{0.0.1}{2026-12-02}{Place side captions through KOMA-Script and preserve ordinary float captions and references.}
% A float can land on the opposite side of the spread from its source.
% The outer-position option delegates the side decision to KOMA at placement.
% The label follows the caption and records its figure number.
%    \begin{macrocode}
\ExplSyntaxOn
\cs_new_protected:Npn \__luatufte_start_beside:n #1
  {
    \bool_if:NTF \l__luatufte_right_bool
      {\begin{captionbeside}{#1}[r]
        [\dimexpr\linewidth+\marginparsep+\marginparwidth\relax][0pt]}
      {\begin{captionbeside}{#1}[o]
        [\dimexpr\linewidth+\marginparsep+\marginparwidth\relax][0pt]*}
  }
\ExplSyntaxOff
\NewDocumentEnvironment{sidecaptionfigure}{O{tbp} m m}{%
  \UseName{__luatufte_figure_start:}[#1]
  \setlength{\columnsep}{\marginparsep}%
  \captionsetup{font=footnotesize,justification=luatufte,
    singlelinecheck=false}
  \UseName{__luatufte_start_beside:n}{#2}%
    \begin{minipage}{\linewidth}\centering
}{%
    \end{minipage}%
  \end{captionbeside}\label{#3}%
  \UseName{__luatufte_figure_end:}
}
%    \end{macrocode}
%
% \section*{A single wide block}
% The saved minipage spans the text, gutter and note column. On a recto
% a left-aligned box lets the extra width extend right. On a verso the
% box aligns on the right, fixing the inner edge. KOMA resolves
% the page side across runs. Boxing also explains why a long table must
% stay outside this environment if its rows need to break across pages.
%    \begin{macrocode}
\newsavebox{\lt@widebox}
\NewDocumentEnvironment{wideblock}{}{%
  \par\begin{lrbox}{\lt@widebox}%
  \begin{minipage}{\dimexpr\linewidth+\marginparsep+\marginparwidth\relax}%
}{%
  \end{minipage}\end{lrbox}%
  \noindent\UseName{__luatufte_outer:nn}%
    {\makebox[\linewidth][l]{\usebox{\lt@widebox}}}%
    {\makebox[\linewidth][r]{\usebox{\lt@widebox}}}\par
}
%    \end{macrocode}
% \section*{A measure that crosses a page boundary}
% \changes{0.0.1}{2026-12-02}{Add breakable full-width text, wide floats and a three-column subject index.}
% The framed package splits the vertical material at available page
% breaks. Its frame callback receives each finished piece separately.
% The page builder has selected a page for each piece. Read its counter
% directly so trial measurements do not create unresolved page labels.
% The ordinary text measure is reserved in the surrounding paragraph.
%    \begin{macrocode}
\RequirePackage{framed,ragged2e}
\ExplSyntaxOn
\cs_new_protected:Npn \__luatufte_outer:nn #1#2
  { \bool_if:nTF {\legacy_if_p:n {@twoside} && ! \l__luatufte_right_bool}
      {\Ifthispageodd{#1}{#2}}{#1} }
%    \end{macrocode}
% The native note accepts alternate verso text and a trailing offset.
% In the Tufte form the leading argument is a dimension. Fixed-right
% notes use the package's one-sided positioning inside a local group.
%    \begin{macrocode}
\NewCommandCopy \__luatufte_native_note: \marginnote
\cs_new_protected:Npn \__luatufte_position_note:nnn #1#2#3
  {
    \group_begin:
    \bool_if:NT \l__luatufte_right_bool {\@twosidefalse}
    \IfNoValueTF{#1}{\__luatufte_native_note:{#2}[#3]}
      {\__luatufte_native_note:[#1]{#2}[#3]}
    \group_end:
  }
\AddToHook{begindocument/before}
  {
    \bool_if:NT \l__luatufte_right_bool {\@mparswitchfalse}
    \str_if_eq:VnTF \l__luatufte_margin_syntax_tl {tufte}
      { \RenewDocumentCommand \marginnote {O{0pt} +m}
          {\__luatufte_position_note:nnn {#2}{#2}{#1}} }
      { \bool_if:NT \l__luatufte_right_bool
          { \RenewDocumentCommand \marginnote {o +m O{0pt}}
              {\__luatufte_position_note:nnn {#1}{#2}{#3}} } }
  }
\NewDocumentEnvironment{fullwidth}{}
  {
    \par
    \cs_set_protected:Npn \FrameCommand ##1
      { \makebox[\textwidth][\bool_if:nTF
          {\legacy_if_p:n {@twoside} && ! \l__luatufte_right_bool
            && ! \int_if_odd_p:n {\c@page}}
          {r}{l}]{##1} }
    \MakeFramed{\advance\hsize\dimexpr\marginparwidth+\marginparsep\relax
      \FrameRestore}
  }
  { \endMakeFramed }
%    \end{macrocode}
% Tables with their own output routine and a multicolumn index need
% ordinary page material. Flush pending floats before changing the page
% width. The enclosing group restores the old margins after the last page.
%    \begin{macrocode}
\NewDocumentEnvironment{fullwidthpages}{}
  {
    \clearpage
    \dim_set:Nn \l_tmpa_dim {\marginparwidth+\marginparsep}
    \dim_add:Nn \textwidth {\l_tmpa_dim}
    \bool_if:NF \l__luatufte_right_bool {\dim_sub:Nn \evensidemargin {\l_tmpa_dim}}
    \dim_set_eq:NN \linewidth \textwidth
    \dim_set_eq:NN \columnwidth \textwidth
    \dim_set_eq:NN \hsize \textwidth
    \dim_zero:N \marginparwidth \dim_zero:N \marginparsep
  }
  { \clearpage }
\ExplSyntaxOff
\RequirePackage[columns=3]{idxlayout}
\AddToHook{env/theindex/before}{\begin{fullwidthpages}}
\AddToHook{env/theindex/after}{\end{fullwidthpages}}
%    \end{macrocode}
% \section*{Marginal type and reading rhythm}
% Alignment can be selected for each kind of marginal material.
% The outer setting uses the final page. The native marginnote package
% already selects the left or right variant at the note's destination.
%    \begin{macrocode}
\ExplSyntaxOn
\cs_new_protected:Npn \__luatufte_align:nn #1#2
  {
    \str_case_e:nn {\tl_use:c {l__luatufte_#1_align_tl}}
      {
        {auto}{\str_if_eq:VnTF \l__luatufte_body_tl {justified}
          {\justifying}{\RaggedRight}}
        {justified}{\justifying}
        {raggedleft}{\RaggedLeft}
        {raggedright}{\RaggedRight}
        {raggedouter}{#2}
      }
  }
\cs_new_protected:Npn \__luatufte_align:n #1
  { \__luatufte_align:nn {#1}{\__luatufte_outer:nn {\RaggedRight}{\RaggedLeft}} }
\RenewDocumentCommand \raggedleftmarginnote { }
  { \__luatufte_align:nn {marginnote}{\RaggedLeft} }
\RenewDocumentCommand \raggedrightmarginnote { }
  { \__luatufte_align:nn {marginnote}{\RaggedRight} }
\DeclareCaptionJustification{luatufte}{\__luatufte_align:n {caption}}
\captionsetup{format=plain,indention=0pt,parindent=0pt,
  justification=luatufte,singlelinecheck=false}
%    \end{macrocode}
% Tabularray sets its own captions. Its simple templates keep the
% label and text in one paragraph on every page of the table.
% The hook applies only when the manuscript loads that package.
%    \begin{macrocode}
\AddToHook{package/tabularray/after}
  {
    \SetTblrTemplate{caption}{simple}
    \SetTblrTemplate{capcont}{simple}
    \SetTblrStyle{caption}{halign=l,indent=0pt,hang=0pt}
  }
%    \end{macrocode}
% Marginal objects inherit KOMA font elements. A manuscript can change
% the citation face independently of the adjacent explanatory notes.
% The diagnostic prints the dimensions after typearea has applied them.
%    \begin{macrocode}
\NewDocumentCommand \setsidenotefont {m}{\setkomafont{sidenote}{#1}}
\NewDocumentCommand \setmarginnotefont {m}{\setkomafont{marginnote}{#1}}
\NewDocumentCommand \setcitationfont {m}{\setkomafont{margincitation}{#1}}
\NewDocumentCommand \setcaptionfont {m}{\setkomafont{caption}{#1}}
\NewDocumentCommand \PrintTufteSettings {}
  { \iow_term:e {LuaTufte:~text=\the\textwidth,~margin=\the\marginparwidth,
      ~gap=\the\marginparsep,~chapters=\l__luatufte_chapter_tl,
      ~captions=\l__luatufte_floats_tl,~notes=\l__luatufte_notes_tl} }
\NewDocumentCommand \morefloats {} {\extrafloats{26}}
\NewDocumentCommand \TufteRecalculate {} {\LuaTufteSetup{}}
%    \end{macrocode}
% OpenType tracking belongs to the local group. Changing case and
% adding space between letters are separate operations, allowing the
% author to preserve an acronym's existing capitalisation.
%    \begin{macrocode}
\NewDocumentCommand \allcapsspacing {m} { {\__luatufte_tracking:n {12}#1} }
\NewDocumentCommand \smallcapsspacing {m} { {\__luatufte_tracking:n {5}#1} }
\NewDocumentCommand \allcaps {m}
  { \allcapsspacing{\MakeUppercase{#1}} }
\NewDocumentCommand \smallcaps {m}
  { \smallcapsspacing{\scshape\MakeLowercase{#1}} }
\cs_new_protected:Npn \__luatufte_tracking:n #1
  { \bool_if:NT \l__luatufte_tracking_bool {\addfontfeatures{LetterSpace=#1}} }
\newlength{\tufteskipamount}
\setlength{\tufteskipamount}{\medskipamount}
\NewDocumentCommand \tuftebreak {} {\par\addvspace{\tufteskipamount}}
\NewDocumentCommand \tufteskip {} {\vspace{\tufteskipamount}}
\newkomafont{extract}{\normalfont\small}
\clist_map_inline:nn {quote,quotation,verse}
  { \AddToHook{env/#1/begin}{\usekomafont{extract}} }
\setkomafont{descriptionlabel}{\normalfont\itshape}
\ExplSyntaxOff
%    \end{macrocode}
% \section*{Wide chapter openings and footnotes}
% KOMA formats the number, title and short mark. Wrap its heading line
% in the same mirrored box used by a wide illustration. Explicit section
% numbering remains available through the standard depth counter.
%    \begin{macrocode}
\ExplSyntaxOn
\NewCommandCopy \__luatufte_chapter_line:nnn \chapterlinesformat
\NewCommandCopy \__luatufte_prefix_line:nnn \chapterlineswithprefixformat
\cs_new_protected:Npn \__luatufte_wide_chapters:
  {
    \RedeclareSectionCommand[beforeskip=50pt,afterskip=40pt]{chapter}
    \RenewDocumentCommand \chapterlinesformat {m m m}
      {\begin{wideblock}
         \tl_if_blank:nF {##2}{##2\par\nobreak}
         \__luatufte_chapter_line:nnn{##1}{}{##3}
       \end{wideblock}}
    \RenewDocumentCommand \chapterlineswithprefixformat {m m m}
      {\begin{wideblock}\__luatufte_prefix_line:nnn{##1}{##2}{##3}\end{wideblock}}
  }
\AddToHook{begindocument/before}
  {
    \setkomafont{paragraph}{\normalfont\itshape}
    \str_if_eq:VnT \l__luatufte_numbers_tl {unnumbered}{\setcounter{secnumdepth}{-1}}
    \str_if_eq:VnT \l__luatufte_chapter_tl {wide}{\__luatufte_wide_chapters:}
    \bool_if:NT \l__luatufte_sans_bool {\addtokomafont{marginaltext}{\sffamily}}
  }
\cs_new_protected:Npn \__luatufte_margin_footnotes:
  {
    \NewCommandCopy \__luatufte_bottom_note: \footnote
    \RenewDocumentCommand \footnote {o O{0pt} +m}
      {
        \str_if_eq:eeTF {\@mpfn}{footnote}
          {\IfNoValueTF{##1}{\sidenote[][##2]{##3}}{\sidenote[##1][##2]{##3}}}
          {\IfNoValueTF{##1}{\__luatufte_bottom_note:{##3}}
            {\__luatufte_bottom_note:[##1]{##3}}}
      }
  }
\AddToHook{begindocument/end}
  {
    \str_if_eq:VnT \l__luatufte_body_tl {raggedright}{\RaggedRight}
    \str_if_eq:VnT \l__luatufte_notes_tl {margin}{\__luatufte_margin_footnotes:}
  }
\ExplSyntaxOff
%    \end{macrocode}
% \section*{Floats across the gutter}
% The starred environments retain normal caption, counter and list
% handling. In one-column books only their contents widen. In a true
% two-column document the standard double-column float owns placement.
%    \begin{macrocode}
\ExplSyntaxOn
\box_new:N \g__luatufte_caption_box
\box_new:N \l__luatufte_object_box
\dim_new:N \g__luatufte_caption_offset_dim
\tl_new:N \g__luatufte_float_align_tl
\tl_new:N \g__luatufte_float_side_tl
%    \end{macrocode}
% Capture the formatted caption at its declared width. Multiple captions
% append in source order. The caption package still owns the optional
% title, counter, list entry and reference anchor.
%    \begin{macrocode}
\dim_new:N \l__luatufte_legend_width_dim
\dim_new:N \l__luatufte_caption_shift_dim
%    \end{macrocode}
% Only class-managed floats extend the caption parser. Hand the actual
% caption back to the active package for counters, links and list entries.
% An empty short form followed by an offset uses the full text in the list.
%    \begin{macrocode}
%    \end{macrocode}
% Within a float, parse the optional displacement before delegating the
% short entry, numbering and hyperlink destination to the native caption.
%    \begin{macrocode}
\NewDocumentCommand \__luatufte_offset_caption: {s o o +m}
  {
    \dim_zero:N \l__luatufte_caption_shift_dim
    \IfValueT{#3}
      {\tl_if_blank:nF {#3}
         {\dim_set:Nn \l__luatufte_caption_shift_dim {#3}}}
    \IfBooleanTF{#1}{\__luatufte_native_caption:*{#4}}
      {
        \IfNoValueTF{#2}{\__luatufte_native_caption:{#4}}
          {\bool_if:nTF {\tl_if_blank_p:n {#2} && ! \tl_if_novalue_p:n {#3}}
             {\__luatufte_native_caption:{#4}}
             {\__luatufte_native_caption:[{#2}]{#4}}}
      }
  }
\cs_new_protected:Npn \__luatufte_caption_syntax:
  {
    \cs_set_eq:NN \__luatufte_native_caption: \caption
    \cs_set_eq:NN \caption \__luatufte_offset_caption:
  }
%    \end{macrocode}
% A source-ordered legend takes up vertical space in the float. A marginal
% legend can move relative to its object while retaining its alignment box.
%    \begin{macrocode}
\DeclareCaptionBox{luatufteflow}
  {\dim_compare:nNnF {\l__luatufte_caption_shift_dim} = {0pt}
     {\vspace*{\l__luatufte_caption_shift_dim}}#2}
\box_new:N \l__luatufte_shifted_caption_box
\DeclareCaptionBox{luatufteouter}
  { \vbox_gset:Nn \g__luatufte_caption_box
      { \box_use_drop:N \g__luatufte_caption_box
        \hsize=\l__luatufte_legend_width_dim \linewidth=\hsize
        \dim_compare:nNnTF {\l__luatufte_caption_shift_dim} = {0pt}
          {#2\par}
          {\vbox_set:Nn \l__luatufte_shifted_caption_box {#2\par}
           \hbox{\raisebox{-\l__luatufte_caption_shift_dim}[\height][\depth]
             {\box_use_drop:N \l__luatufte_shifted_caption_box}}} } }
\NewDocumentCommand \setcaptionoffset {m}
  { \dim_gset:Nn \g__luatufte_caption_offset_dim {#1} }
\NewDocumentCommand \setfloatalignment {m}
  { \str_case:nnF {#1}
      {{t}{}{c}{}{b}{}}
      {\ClassError{luatufte}{Use~t,~c~or~b~for~float~alignment}{}}
    \tl_gset:Nn \g__luatufte_float_align_tl {#1} }
\NewDocumentCommand \forcerectofloat {} {\tl_gset:Nn \g__luatufte_float_side_tl {r}}
\NewDocumentCommand \forceversofloat {} {\tl_gset:Nn \g__luatufte_float_side_tl {v}}
\cs_new_protected:Npn \__luatufte_float_box:N #1
  { \raisebox{\str_case:Vn \g__luatufte_float_align_tl
      {{t}{-\height}{c}{\dim_eval:n {(\depth-\height)/2}}{b}{\depth}}}{\box_use:N #1} }
\cs_new_protected:Npn \__luatufte_caption_position:
  { \raisebox{-\g__luatufte_caption_offset_dim}
      {\__luatufte_float_box:N \g__luatufte_caption_box} }
\cs_new_protected:Npn \__luatufte_float_row:n #1
  {
    \str_if_eq:nnTF {#1}{r}
      {\makebox[\linewidth][l]{\__luatufte_float_box:N \l__luatufte_object_box
         \hspace{\marginparsep}\__luatufte_caption_position:}}
      {\makebox[\linewidth][r]{\__luatufte_caption_position:
         \hspace{\marginparsep}\__luatufte_float_box:N \l__luatufte_object_box}}
  }
%    \end{macrocode}
% Save the body separately so the marginal caption can align with its
% top, centre or bottom, even when the caption precedes the illustration.
% KOMA records the eventual page side across runs.
%    \begin{macrocode}
\cs_new_protected:Npn \__luatufte_reset_float:
  {
    \dim_gzero:N \g__luatufte_caption_offset_dim
    \box_gclear:N \g__luatufte_caption_box
    \tl_gset:Nn \g__luatufte_float_align_tl {t}
    \tl_gclear:N \g__luatufte_float_side_tl
    \dim_set_eq:NN \l__luatufte_legend_width_dim \marginparwidth
    \dim_zero:N \l__luatufte_caption_shift_dim
  }
\cs_new_protected:Npn \__luatufte_float_begin:
  {
    \__luatufte_reset_float:
    \hbox_set:Nw \l__luatufte_object_box
    \begin{minipage}{\linewidth}
    \__luatufte_caption_syntax:
    \captionsetup{box=luatufteouter,width=\marginparwidth,
      justification=luatufte,singlelinecheck=false,skip=0pt}
  }
\cs_new_protected:Npn \__luatufte_float_end:
  {
    \end{minipage}\hbox_set_end:
    \noindent
    \tl_if_empty:NTF \g__luatufte_float_side_tl
      {\__luatufte_outer:nn {\__luatufte_float_row:n {r}}{\__luatufte_float_row:n {v}}}
      {\exp_args:NV \__luatufte_float_row:n \g__luatufte_float_side_tl}
    \par
  }
%    \end{macrocode}
% Standard figures and tables use their native placement specifiers.
% For a starred float the object spans both columns. Asymmetric caption
% margins reserve the body and gutter on the appropriate side. Source
% order determines whether the legend sits above or below the object.
%    \begin{macrocode}
\cs_new_protected:Npn \__luatufte_wide_caption:
  {
    \str_if_eq:VnT \l__luatufte_wide_caption_tl {margin}
      { \dim_compare:nNnT {\marginparwidth} > {0pt}
          {
            \dim_set:Nn \l_tmpa_dim {\linewidth-\marginparwidth}
            \__luatufte_outer:nn
              {\captionsetup{twoside=false,margin={\l_tmpa_dim,0pt}}}
              {\captionsetup{twoside=false,margin={0pt,\l_tmpa_dim}}}
          } }
  }
%    \end{macrocode}
% In alignment mode collect the caption separately. At the end of the
% float both boxes know their height. Stacking them in the chosen order
% leaves room for a long legend on either side of the spread.
%    \begin{macrocode}
\cs_new_protected:Npn \__luatufte_start_wide:n #1
  {
    \begin{wideblock}
    \__luatufte_reset_float:
    \__luatufte_caption_syntax:
    \str_if_eq:VnTF \l__luatufte_wide_order_tl {alignment}
      {
        \str_if_eq:nnT {#1}{b}{\setfloatalignment{b}}
        \str_if_eq:VnT \l__luatufte_wide_caption_tl {full}
          {\dim_set_eq:NN \l__luatufte_legend_width_dim \linewidth}
        \dim_compare:nNnT {\marginparwidth} = {0pt}
          {\dim_set_eq:NN \l__luatufte_legend_width_dim \linewidth}
        \vbox_set:Nw \l__luatufte_object_box
        \captionsetup{box=luatufteouter,width=\l__luatufte_legend_width_dim,
          singlelinecheck=false,skip=0pt}
      }
      {\captionsetup{box=luatufteflow}\__luatufte_wide_caption:}
  }
%    \end{macrocode}
% KOMA resolves the outer edge on the final float page. Keep the two
% boxes in reading order when an explicit alignment selects their order.
%    \begin{macrocode}
\cs_new_protected:Npn \__luatufte_place_wide_legend:
  {
    \noindent\makebox[\linewidth]
      [\tl_if_empty:NTF \g__luatufte_float_side_tl
        {\l__luatufte_wide_edge_tl}
        {\str_if_eq:VnTF \g__luatufte_float_side_tl {r}{r}{l}}]
      {\raisebox{-\g__luatufte_caption_offset_dim}
        {\box_use:N \g__luatufte_caption_box}}\par
  }
\tl_new:N \l__luatufte_wide_edge_tl
\cs_new_protected:Npn \__luatufte_end_wide:
  {
    \str_if_eq:VnT \l__luatufte_wide_order_tl {alignment}
      {
        \par\vbox_set_end:
        \__luatufte_outer:nn
          {\tl_set:Nn \l__luatufte_wide_edge_tl {r}}
          {\tl_set:Nn \l__luatufte_wide_edge_tl {l}}
        \box_if_empty:NTF \g__luatufte_caption_box
          {\box_use:N \l__luatufte_object_box}
          {\str_if_eq:VnTF \g__luatufte_float_align_tl {b}
             {\__luatufte_place_wide_legend: \smallskip
              \box_use:N \l__luatufte_object_box}
             {\box_use:N \l__luatufte_object_box \smallskip
              \__luatufte_place_wide_legend:}}
      }
    \end{wideblock}
  }
%    \end{macrocode}
% Save the native float entry and exit points. The float package installs
% its own closing command for a fixed-position object.
%    \begin{macrocode}
\clist_map_inline:nn {figure,table}
  {
    \cs_new_eq:cc {__luatufte_#1_start:}{#1}
    \cs_new_eq:cc {__luatufte_#1_end:}{end#1}
    \cs_new_eq:cc {__luatufte_#1_double:}{#1*}
    \cs_new_eq:cc {__luatufte_#1_enddouble:}{end#1*}
    \RenewDocumentEnvironment{#1}{o}
      {
        \IfNoValueTF{##1}{\use:c {__luatufte_#1_start:}}
          {\use:c {__luatufte_#1_start:}[##1]}
        \str_if_eq:VnTF \l__luatufte_floats_tl {outer}
          {
            \str_if_eq:nnT {##1}{H}
              {\cs_if_exist:NT \float@endH
                 {\cs_set_protected:cpn {end#1}
                    {\__luatufte_float_end: \float@endH}}}
            \__luatufte_float_begin:
          }
          {\__luatufte_caption_syntax: \captionsetup{box=luatufteflow}}
      }
      { \str_if_eq:VnT \l__luatufte_floats_tl {outer}
          {\__luatufte_float_end:}
        \use:c {__luatufte_#1_end:} }
    \RenewDocumentEnvironment{#1*}{O{tbp}}
      { \if@twocolumn \use:c {__luatufte_#1_double:}[##1]
        \else \use:c {__luatufte_#1_start:}[##1]
          \cs_set_eq:Nc \__luatufte_close_wide: {__luatufte_#1_end:}
          \str_if_eq:nnT {##1}{H}
            {\cs_if_exist:NT \float@endH
               {\cs_set_eq:NN \__luatufte_close_wide: \float@endH}}
          \__luatufte_start_wide:n {##1}\fi }
      { \if@twocolumn \use:c {__luatufte_#1_enddouble:}
        \else \__luatufte_end_wide: \__luatufte_close_wide:\fi }
  }
%    \end{macrocode}
% The float package resolves a named style at the start of each object.
% Retain its native frame and rules around the body. Assemble the
% caption beside that decorated box before float ships it. Include the
% package's caption box to preserve deferred writes and link targets.
%    \begin{macrocode}
\cs_new_protected:Npn \__luatufte_styled_row:n #1
  {
    \vbox_set:Nn \l__luatufte_object_box
      {
        \use:c {fs@#1}
        \@fs@pre \vbox_unpack_drop:N \@currbox \@fs@post
      }
    \vbox_unpack_drop:N \@floatcapt
    \box_clear:N \@currbox
    \noindent\__luatufte_outer:nn
      {\__luatufte_float_row:n {r}}{\__luatufte_float_row:n {v}}\par
  }
\AddToHook{package/float/after}
  {
    \clist_map_inline:nn {plain,plaintop,ruled,boxed}
      {
        \DeclareCaptionStyle{tufte#1}
          {box=luatufteouter,width=\marginparwidth,font=footnotesize,
           justification=luatufte,singlelinecheck=false,skip=0pt}
        \cs_new_protected:cpn {fs@tufte#1}
          {
            \use:c {fs@#1}
            \__luatufte_reset_float:
            \cs_set_protected:Npn \@fs@pre {\__luatufte_styled_row:n {#1}}
            \cs_set_eq:NN \@fs@mid \prg_do_nothing:
            \cs_set_eq:NN \@fs@post \prg_do_nothing:
          }
      }
  }
%    \end{macrocode}
% The algorithm package selects a float style while loading. Preserve its
% choice of frame and restore the active style for later declarations.
% Its list uses level one even in a book with chapter-only contents.
%    \begin{macrocode}
\AddToHook{package/algorithm/after}
  {
    \str_if_eq:VnT \l__luatufte_floats_tl {outer}
      {
        \cs_set_eq:NN \__luatufte_previous_style: \float@style
        \floatstyle{tufte\ALG@floatstyle}
        \restylefloat{algorithm}
        \cs_set_eq:NN \float@style \__luatufte_previous_style:
      }
    \NewCommandCopy \__luatufte_list_algorithms: \listofalgorithms
    \RenewDocumentCommand \listofalgorithms {}
      {\group_begin:
         \int_set:Nn \c@tocdepth {\int_max:nn {1}{\c@tocdepth}}
         \__luatufte_list_algorithms:
       \group_end:}
  }
\ExplSyntaxOff
%</class>
%    \end{macrocode}
%
% \section*{Citations and Biber}
% \changes{0.0.1}{2026-12-02}{Share the sidenote counter with foot citations and offer full marginal citations.}
% The package forwards options to biblatex. Its note wrapper selects
% the placement while the citation style supplies the text and punctuation.
%    \begin{macrocode}
%<*biblio>
\NeedsTeXFormat{LaTeX2e}[2022-06-01]
\ProvidesPackage{luatufte-biblio}[2026/12/02 v0.0.1 Margin citations derived from kaobook]
\ExplSyntaxOn
\bool_new:N \l__luatufte_margin_cite_bool
\DeclareOption{cite=margin}{\bool_set_true:N \l__luatufte_margin_cite_bool}
\DeclareOption{cite=inline}{\bool_set_false:N \l__luatufte_margin_cite_bool}
\ExplSyntaxOff
\DeclareOption*{\PassOptionsToPackage{\CurrentOption}{biblatex}}
\ProcessOptions\relax
\RequirePackage[backend=biber]{biblatex}
%    \end{macrocode}
%
% Biblatex still formats the citation and tracks its first occurrence.
% While it builds an ordinary footnote citation, the local substitution
% sends the result to the sidenote counter. In a minipage the active
% counter is different, so the citation stays with that box. The counter
% name inside the margin note lets a repeated verbose citation point back
% to the original note. Ordinary body footnotes keep their own sequence.
%    \begin{macrocode}
\NewCommandCopy{\lt@bibfootnote}{\mkbibfootnote}
\renewcommand*{\mkbibfootnote}[1]{%
  \begingroup
  \ifdefstring{\@mpfn}{footnote}{\let\footnote\lt@bibmargin}{}%
  \lt@bibfootnote{#1}%
  \endgroup}
\ExplSyntaxOn
\bool_if:NT \l__luatufte_margin_cite_bool
  {
    \NewCommandCopy \__luatufte_inline_cite: \cite
    \RenewDocumentCommand \cite {s}
      { \IfBooleanTF{#1}{\__luatufte_inline_cite:*}{\footfullcite} }
    \AddToHook{luatufte/sidenote/begin}{\cs_set_eq:NN \cite \fullcite}
  }
\cs_new_protected:Npn \lt@bibmargin #1
  { \sidenote{\usekomafont{margincitation}
      \__luatufte_align:n {citation} \def\@mpfn{sidenote}#1\par} }
\ExplSyntaxOff
%</biblio>
%    \end{macrocode}
%
% \endgroup
% \clearpage
% \begingroup
% \RenewCommandCopy{\chapterlinesformat}{\manualbodychapterlines}
% \RedeclareSectionCommand[beforeskip=0pt,afterskip=\baselineskip]{chapter}
% \addchap{Changelog}\label{manual:changes}
% The page numbers identify where each change is documented.
% \par\medskip
% \PrintChanges
% \endgroup
% \Finale
%
% \iffalse
% Live float calls shared by the manual and the checkout example.
%<*offset>
\hvFloat[wide,capPos=outer,capVPos=top,
         floatPos=htbp,floatCapSep=\marginparsep]
  {figure}
  {\makebox[\linewidth][c]{\Large \(19.26 - 0.30 = 18.96\)}}
  {The offset changes the working value. All readings here
   are demonstration data.}
  {fig:offset}
%</offset>
%<*readings>
\hvFloat[wide,capPos=outer,capVPos=top,
         floatPos=htbp,floatCapSep=\marginparsep]
  {table}
  {\begin{tabular*}{\linewidth}{@{}l@{\extracolsep{\fill}}rr@{}}
     \toprule
     Record & Input & Adjusted \\
     \midrule
     M01 & 19.26 & 18.96 \\
     M02 & 19.40 & 19.10 \\
     \bottomrule
   \end{tabular*}}
  {Two constructed records in degrees Celsius, before and after
   the adjustment.}
  {tab:readings}
%</readings>
%
% Extract main.tex verbatim, including its listing range markers.
%<*specimenmain>
%<<END-SPECIMEN-FILE
%<*booksetup>
\documentclass[
  a4paper,
  titlepage,
  twoside,
  open=any,
  sections=numbered,
  fontsize=11pt
]{luatufte}
%</booksetup>

\input{language.tex}
\usepackage[
  backend=biber,
  style=authoryear,
  sorting=nyt,
  maxcitenames=2,
  maxbibnames=99,
  giveninits=true,
  uniquename=init,
  isbn=false
]{luatufte-biblio}
\input{preamble.tex}

\newenvironment{specimenwidetable}{\begin{table*}[tbp]}{\end{table*}}
\newenvironment{specimenwidefigure}{\begin{figure*}[tbp]}{\end{figure*}}
\newenvironment{specimenwidecode}{\begin{fullwidth}}{\end{fullwidth}}
\input{book.tex}
%END-SPECIMEN-FILE
%</specimenmain>
%
% Extract language.tex verbatim, including its listing range markers.
%<*specimenlanguage>
%<<END-SPECIMEN-FILE
\usepackage[english]{babel}
\usepackage{csquotes}
%END-SPECIMEN-FILE
%</specimenlanguage>
%
% Extract preamble.tex verbatim, including its listing range markers.
%<*specimenpreamble>
%<<END-SPECIMEN-FILE
\usepackage{makeidx}
\makeindex
\KOMAoptions{numbers=noenddot}
\usepackage{siunitx}
\usepackage{tabularray}
\UseTblrLibrary{booktabs,siunitx}
\usepackage{tikz}
\usetikzlibrary{arrows.meta,positioning,calc}
\usepackage{listings}
\usepackage[nostfloats]{hvfloat}

\providecolor{luatufteblue}{HTML}{185277}
\providecolor{luatuftepetrol}{HTML}{006D77}
\definecolor{luatuftegray}{HTML}{52616B}

\sisetup{locale=US,per-mode=symbol}
\lstdefinestyle{specimen}{
  basicstyle=\small\ttfamily,
  keywordstyle=\color{luatufteblue}\bfseries,
  commentstyle=\color{luatuftegray}\itshape,
  stringstyle=\color{luatuftepetrol},
  numbers=left,
  numberstyle=\scriptsize\color{luatuftegray},
  numbersep=8pt,
  xleftmargin=14pt,
  frame=none,
  breaklines=true,
  breakatwhitespace=false,
  columns=fullflexible,
  keepspaces=true,
  showstringspaces=false,
  tabsize=2,
  aboveskip=\baselineskip,
  belowskip=\baselineskip
}
\lstset{style=specimen}
\hypersetup{
  colorlinks=true,
  linkcolor=luatufteblue,
  citecolor=luatuftepetrol,
  urlcolor=luatufteblue,
  pdftitle={The Measurement Record},
  pdfsubject={A worked example of a reproducible measurement workflow}
}

% Access dates remain access dates in author-year citations.
\DeclareLabeldate{\field{date}\field{year}\literal{nodate}}
\addbibresource{references.bib}

\newtheorem{specimenrule}{Proposition}[chapter]
\newtheorem{specimencorollary}[specimenrule]{Corollary}
%END-SPECIMEN-FILE
%</specimenpreamble>
%
% Extract book.tex verbatim, including its listing range markers.
%<*specimenbook>
%<<END-SPECIMEN-FILE
\title{The Measurement Record}
\subtitle{From measurements to reproducible results}
\author{LuaTufte project}
\date{2 December 2026}
\publishers{LuaTufte scientific books}

\begin{document}
\frontmatter
\maketitle
\tableofcontents
\vfill
\noindent\begin{tikzpicture}[x=11mm,y=8mm]
  \draw[luatuftepetrol,thick] (0,0) -- (1,.45) -- (2,.9) -- (3,1.35) -- (4,1.8);
  \foreach \x/\y in {0/0,1/.45,2/.9,4/1.8}
    \fill[luatuftepetrol] (\x,\y) circle (1.7pt);
  \draw[luatuftepetrol,fill=white,thick] (3,1.35) circle (2.7pt);
  \node[anchor=north west,font=\footnotesize,inner sep=0pt] at (0,-.2) {35 min};
  \node[anchor=south west,font=\footnotesize] at (4,1.8) {39 min};
\end{tikzpicture}\par\medskip
\noindent Forty synthetic readings, one per minute. The open point
marks the reading withheld in the final audit. Its two neighbours
preserve enough information to reconstruct it.\par\medskip
\noindent{\footnotesize Text, demonstration data, code and drawings:
\href{https://www.latex-project.org/lppl/lppl-1-3c/}{LPPL 1.3c or later}.}

\mainmatter
\input{chapter.tex}
\printindex
\end{document}
%END-SPECIMEN-FILE
%</specimenbook>
%
% Extract chapter.tex verbatim, including its listing range markers.
%<*specimenchapter>
%<<END-SPECIMEN-FILE
\part{The measurement study}
\chapter{From measurements to reproducible results}
\label{chap:measurements}

\textsc{A lab notebook} records a mean of \num{19.59}. How could a colleague
recover that number six months later? The unit is a start. The colleague
also needs the observations that went into the mean, the rule applied to
each observation and a way to tell whether the calculation included the
whole series. An extra digit of precision answers none of those questions.

We can work through the problem with a series small enough to print in
full. Imagine forty readings taken at one-minute intervals. \textbf{All
values in this chapter are synthetic demonstration data.} A generator
stands in for an instrument. The offset of \qty{0.30}{\celsius} is part
of the exercise. No calibration experiment underlies it. Anyone with
the generator can reconstruct the first reading, the fortieth and every
value in between.

By the end of the exercise we will have a table of inputs, a second table
with an adjusted value alongside each input, and a short report of the
result. The same record identifiers appear in both tables. This lets a
reader follow an individual reading through the calculation and trace a
summary back to the rows that contributed to it.%
\sidenote{A constructed series gives us an answer we can derive in advance.
It can test a calculation but tells us nothing about the performance of a
physical sensor.}

\section{Record the question before computing the answer}
\index{research question}
\label{sec:question}

What mean will we obtain if we subtract the same fixed amount from all
forty readings? We also want to see how the values vary over time. The
first question calls for one number. The second requires us to preserve
the order of the observations. A table sorted by temperature would still
give the same mean, yet its plot would tell a different story.

We decide in advance that every row counts once. The series has no missing
values. There is no exclusion rule and no window to select after seeing
the graph. The identifiers \texttt{M01} through \texttt{M40} survive every
processing step. If somebody later sorts the working table, row position
can change while the identification of a reading stays intact.

\begin{marginfigure}
  \centering
  \begin{tikzpicture}[x=1cm,y=1cm]
    \node[draw,rounded corners=2pt,text width=27mm,align=center,
      inner sep=3pt,font=\footnotesize] (question) at (0,0) {State the question};
    \node[draw,rounded corners=2pt,text width=27mm,align=center,
      inner sep=3pt,font=\footnotesize] (rule) at (0,-1.05) {Write the rule};
    \node[draw,rounded corners=2pt,text width=27mm,align=center,
      inner sep=3pt,font=\footnotesize] (check) at (0,-2.10) {Check the result};
    \draw[->] (question) -- (rule);
    \draw[->] (rule) -- (check);
  \end{tikzpicture}
  \caption{Three decisions in the design of the check.}
  \label{fig:design}
\end{marginfigure}

\subsection[Write down the working rule]{Why a small table with apparently self-explanatory columns still needs a written working rule}

Even a short instruction leaves room for reasonable differences of
interpretation. Should we round before applying the offset? Should the
adjusted value replace the original? Does the unit in the file name apply
to the time column as well? For this exercise we apply the offset to the
generated decimal value, keep the input column and express both sets of
readings in degrees Celsius. Elapsed time has its own unit, minutes.

A larger study might keep these decisions in a data dictionary. Here
they fit in the chapter itself. If the agreed offset changes, the
description and the calculation must change together. Otherwise a
second analyst can follow the written instruction exactly and still
obtain a different answer from the one in the report.

\section{Generate a table with known properties}
\index{demonstration data}
\label{sec:generator}

The generator combines a steady increase with a five-step pattern.
For the reading with index \(i=1,\ldots,40\), the input value is
\[
  \begin{aligned}
    x_i = \Bigl[&19.50 + 0.02(i-1)\\
                &{}+0.12\bigl(((i-1)\bmod 5)-2\bigr)\Bigr]
                \,\unit{\celsius}.
  \end{aligned}
\]
Elapsed time is \(t_i=i-1\) minutes. The remainder on division by five
takes values from zero to four. Subtracting two centres those five
integers on zero. The first cycle therefore contributes offsets of
\(-0.24\), \(-0.12\), zero, \(0.12\) and \(0.24\) to the rising base
value. The teeth visible in the plot come from this deliberate choice.

Save Listing~\ref{lst:generate} as \texttt{generate.py}. The script writes
only the input values. Constructing each \texttt{Decimal} from a string
keeps the decimal constants in the equation visible in the program.
The file uses a period for the decimal point and a comma between fields.
The header gives both numerical columns a unit.%
\sidenote{The last record has ID \texttt{M40} and time 39. The identifiers
start at one, while elapsed time starts at zero. This pair catches a
one-step shift that a row count would miss.}

\begin{lstlisting}[language=Python,caption={Generate the synthetic input table.},label={lst:generate}]
import csv
from decimal import Decimal

path = "readings_raw.csv"
with open(path, "w", newline="") as stream:
    writer = csv.writer(stream,
                        lineterminator="\n")
    columns = ["id", "time_min", "temperature_C"]
    writer.writerow(columns)
    for k in range(40):
        value = (Decimal("19.50")
                 + Decimal("0.02") * k
                 + Decimal("0.12") * (k % 5 - 2))
        row = [f"M{k+1:02d}", k, f"{value:.2f}"]
        writer.writerow(row)
\end{lstlisting}

\marginnote{Source: the generator in Listing~\ref{lst:generate}.}
Three checks are available before we compute an adjusted value. There
must be forty data rows, forty distinct identifiers and one record for
each integer time from zero to thirty-nine. These expectations follow
from the construction rule. Reading them back from the finished table
would make it much harder to discover an error in the generator itself.

\section{Keep the input and derive a working value}
\index{calibration}
\label{sec:adjustment}

We add one column to the input table. If a reader questions a value in
the new column, the original is still on the same row. With the agreed
offset \(\delta\), the relation is
\begin{equation}
  y_i=x_i-\delta,
  \qquad \delta=\qty{0.30}{\celsius},
  \qquad i=1,\ldots,40.
  \label{eq:offset}
\end{equation}
For the first record the arithmetic is
\(\qty{19.26}{\celsius}-\qty{0.30}{\celsius}=\qty{18.96}{\celsius}\).
Figure~\ref{fig:transformation} follows that record from left to right.
The identifier stays with the record even though the value used for the
report changes.

\begin{sidecaptionfigure}{Applying the agreed offset to record \texttt{M01}.}{fig:transformation}
  \begin{tikzpicture}[x=1cm,y=1cm]
    \node[draw,rounded corners=2pt,text width=22mm,align=center,
      inner sep=4pt,font=\small] (raw) at (0,0)
      {Input\\\(19.26\)};
    \node[draw,rounded corners=2pt,text width=22mm,align=center,
      inner sep=4pt,font=\small] (rule) at (3.0,0)
      {Offset\\\(-0.30\)};
    \node[draw,rounded corners=2pt,text width=22mm,align=center,
      inner sep=4pt,font=\small] (adjusted) at (6.0,0)
      {Adjusted\\\(18.96\)};
    \draw[->] (raw) -- (rule);
    \draw[->] (rule) -- (adjusted);
    \node[font=\footnotesize,align=center] at (3.0,-0.95)
      {All values in degrees Celsius.};
  \end{tikzpicture}
\end{sidecaptionfigure}

\begin{specimenrule}\label{rule:translation}
Subtracting a constant preserves every pairwise difference. For two
records \(i\) and \(j\),
\[
    y_i-y_j=(x_i-\delta)-(x_j-\delta)=x_i-x_j.
\]
\end{specimenrule}
Proposition~\ref{rule:translation} gives us a check independent of the
mean. Take the difference between the warmest and coolest input, then
repeat with the adjusted column. A change in that range reveals that at
least one operation besides the fixed shift affected the data.%
\sidenote{The term \enquote{adjusted} identifies a processing step.
The offset carries no claim of greater measurement accuracy.}

\subsection{Derive the mean independently}

The mean of the forty integers \(i-1\) is \num{19.5}. Each of the five
deviations appears eight times and the five sum to zero. The mean input
is therefore \(19.50+0.02\times19.5=19.89\). This derivation uses the
definition of the series and does not require the CSV file.
\begin{specimencorollary}
By Equation~\ref{eq:offset}, the mean of the adjusted column is
\qty{19.59}{\celsius}.
\end{specimencorollary}
We now have a value against which to check a row-by-row computation.
Table~\ref{tab:summary} also records the two endpoints of the range.
Both move by precisely the same amount as the mean.

\begin{table}[tbp]
  \caption{Summary of the demonstration data. All quantities except the count are in degrees Celsius.}
  \label{tab:summary}
  \begin{tblr}{
    width=\linewidth,
    colspec={X[2,l] X[r] X[r]},
    row{1}={font=\bfseries},
    hline{1,2,Z}={0.4pt},
  }
    Statistic & Input & Adjusted \\
    Count & 40 & 40 \\
    Mean & 19.89 & 19.59 \\
    Minimum & 19.26 & 18.96 \\
    Maximum & 20.52 & 20.22 \\
  \end{tblr}
\end{table}

\section{Turn the calculation into a repeatable workflow}
\index{workflow}
\label{sec:workflow}

The commands in Listing~\ref{lst:process} start with the generator. The
first \texttt{awk} invocation copies the input fields and appends the
adjusted value. The second reads that new column, counts the data rows
and prints the mean. An unexpected count returns a nonzero exit status
before a result can be reported. The long final command occupies one
source line and wraps on the printed page.

\begin{specimenwidecode}
\begin{lstlisting}[language=bash,caption={Derive the working table and report its mean.},label={lst:process}]
python3 generate.py

LC_ALL=C awk -F, '
  BEGIN { OFS="," }
  NR==1 { print $0,"adjusted_C"; next }
  { print $1,$2,$3,sprintf("%.2f",$3-0.30) }
' readings_raw.csv > readings_work.csv

LC_ALL=C awk -F, 'NR>1 {sum+=$4; count++} END {if(count!=40) exit 2; printf "n=%d; mean_adjusted_C=%.2f\n",count,sum/count}' readings_work.csv
\end{lstlisting}
\end{specimenwidecode}

For the defined input, the report reads
\begin{quote}
\ttfamily n=40; mean\_adjusted\_C=19.59
\end{quote}
\paragraph{Check the sequence.} A row count detects a single omission. If one record is lost and another
is duplicated, the same count can still pass. Comparing the identifiers
and time sequence against their expected values detects that case. A
matching mean is a useful check on arithmetic, but by itself it cannot
establish which records entered the calculation.

The commands rely on the narrow CSV format written by the generator.
All fields contain identifiers or numbers, so splitting at each comma
is sufficient here. A later addition such as a quoted instrument
description containing a comma would require a CSV-aware reader.
\sidenote{Record format assumptions alongside the command that uses
them. A future change to a column is easier to assess when its consumers
are identifiable.}

Table~\ref{tab:files} lists the files in the order another analyst would
encounter them. The last column specifies an observation the analyst
can make after each step. This makes it possible to locate a discrepancy
before rerunning the whole calculation.

\begin{specimenwidetable}
  \caption{Files and checks for a repeat run.}
  \label{tab:files}
  \begin{tblr}{
    width=\linewidth,
    colspec={X[1.7,l] X[1.15,l] X[1.45,l] X[1.3,l]},
    row{1}={font=\bfseries},
    hline{1,2,Z}={0.4pt},
  }
    File & Purpose & Expected result & Check \\
    \texttt{generate.py} & Generate the input & Same construction rule & Source and revision \\
    \texttt{readings\_raw.csv} & Retain input values & 40 distinct record IDs & Count, order and IDs \\
    \texttt{readings\_work.csv} & Add adjusted values & Input column preserved & Difference of 0.30 in each row \\
    Run log & Record the result & Adjusted mean of 19.59 & Independent derivation \\
  \end{tblr}
\end{specimenwidetable}

\subsection{Trace an unexpected result to a single step}

Suppose the last command counts thirty-nine records. Compare the observed
identifiers with the expected sequence first. If \texttt{M17} is absent
from the working table, look for it in the input file. Its presence there
narrows the search to the transformation. Its absence sends us back to
the generator or to the copy of the input used for this run.

If the count agrees but the mean comes out at \qty{19.29}{\celsius}, the
discrepancy is exactly one more offset. Applying the transformation twice
would produce that result. Compare the two columns in record \texttt{M01}.
An adjusted value of \qty{18.66}{\celsius} beside an input of
\qty{19.26}{\celsius} supports the explanation. Checking the remaining
rows establishes whether the same mistake affected the entire file.

\section{Preserve time order and the origin of each result}
\index{provenance}
\label{sec:provenance}

Table~\ref{tab:summary} answers the question about the mean. It cannot
show where a low reading occurs in the sequence. Figure~\ref{fig:series}
restores the time dimension. Follow the first five points up the base
slope and then watch the pattern start again. The two lines have the
same shape throughout. Their vertical separation equals the offset in
Equation~\ref{eq:offset}.

\begin{specimenwidefigure}
  \centering
  \begin{tikzpicture}[x=0.28cm,y=1.6cm]
    \foreach \yy/\lab in {0/18.5,0.5/19.0,1/19.5,1.5/20.0,2/20.5} {
      \draw[gray!18] (0,\yy) -- (39,\yy);
      \node[anchor=east,font=\footnotesize] at (-0.6,\yy) {\lab};
    }
    \draw[->] (0,0) -- (40.2,0);
    \draw[->] (0,0) -- (0,2.25);
    \foreach \xx in {0,10,20,30,39} {
      \draw (\xx,0) -- (\xx,-0.035);
      \node[anchor=north,font=\footnotesize] at (\xx,-0.06) {\xx};
    }
    \node[anchor=north,font=\small] at (20,-0.31) {Time in minutes};
    \node[rotate=90,font=\small] at (-4.2,1.1) {Value in degrees Celsius};
    \draw[dashed,black!65,line width=0.7pt] plot coordinates {
      (0,0.76) (1,0.90) (2,1.04) (3,1.18) (4,1.32)
      (5,0.86) (6,1.00) (7,1.14) (8,1.28) (9,1.42)
      (10,0.96) (11,1.10) (12,1.24) (13,1.38) (14,1.52)
      (15,1.06) (16,1.20) (17,1.34) (18,1.48) (19,1.62)
      (20,1.16) (21,1.30) (22,1.44) (23,1.58) (24,1.72)
      (25,1.26) (26,1.40) (27,1.54) (28,1.68) (29,1.82)
      (30,1.36) (31,1.50) (32,1.64) (33,1.78) (34,1.92)
      (35,1.46) (36,1.60) (37,1.74) (38,1.88) (39,2.02)
    };
    \draw[luatufteblue,line width=0.85pt] plot coordinates {
      (0,0.46) (1,0.60) (2,0.74) (3,0.88) (4,1.02)
      (5,0.56) (6,0.70) (7,0.84) (8,0.98) (9,1.12)
      (10,0.66) (11,0.80) (12,0.94) (13,1.08) (14,1.22)
      (15,0.76) (16,0.90) (17,1.04) (18,1.18) (19,1.32)
      (20,0.86) (21,1.00) (22,1.14) (23,1.28) (24,1.42)
      (25,0.96) (26,1.10) (27,1.24) (28,1.38) (29,1.52)
      (30,1.06) (31,1.20) (32,1.34) (33,1.48) (34,1.62)
      (35,1.16) (36,1.30) (37,1.44) (38,1.58) (39,1.72)
    };
    \node[anchor=west,font=\footnotesize] at (39.5,2.02) {Input};
    \node[anchor=west,font=\footnotesize,text=luatufteblue] at (39.5,1.72) {Adjusted};
  \end{tikzpicture}
  \caption{All forty synthetic readings in time order. Lines connect successive records. The generator produces one value per minute.}
  \label{fig:series}
\end{specimenwidefigure}

A result also has a history. For this exercise we keep the generator,
input file, offset and report together. Changing the offset creates a
new working table and a new figure from the same input. A brief revision
note should identify the old and new offsets and link each report to
the rule used for its calculation. A file name alone does not capture
that relationship.

\begin{marginfigure}
  \centering
  \begin{tikzpicture}[x=1cm,y=1cm]
    \node[draw,rounded corners=2pt,align=center,inner sep=3pt,
      font=\footnotesize] (revision) at (0,0) {Revision};
    \node[draw,rounded corners=2pt,align=center,inner sep=3pt,
      font=\footnotesize] (data) at (-0.92,-1.05) {Data};
    \node[draw,rounded corners=2pt,align=center,inner sep=3pt,
      font=\footnotesize] (rule) at (0.92,-1.05) {Rule};
    \node[draw,rounded corners=2pt,align=center,inner sep=3pt,
      font=\footnotesize] (result) at (0,-2.10) {Result};
    \draw[->] (revision) -- (data);
    \draw[->] (revision) -- (rule);
    \draw[->] (data) -- (result);
    \draw[->] (rule) -- (result);
  \end{tikzpicture}
  \caption{A result can be traced to its data and the rule applied.}
  \label{fig:provenance}
\end{marginfigure}

\subsection{Use the complete series as a reference}

Table~\ref{tab:series} gives every expected record for comparison.
Read across a row to check its adjustment, or follow a column down to
check the shape of the series. The header repeats when the table moves
to the next page. A reader opening the book at the continuation can
still distinguish the input from the adjusted value.%
\sidenote{In a printed continuation, units belong beside the repeated
column labels. A unit mentioned only in the opening paragraph would be
several page turns away.}

\begin{longtblr}[
  caption={Complete demonstration series with the derived working column.},
  label={tab:series},
]{
  width=\linewidth,
  colspec={X[l] X[r] X[r] X[r]},
  rowhead=1,
  row{1}={font=\bfseries},
  rows={rowsep=2pt},
  hline{1,2,Z}={0.4pt},
}
  ID & Time / min & \(x_i\) / \unit{\celsius} & \(y_i\) / \unit{\celsius} \\
  M01 & 0 & 19.26 & 18.96 \\
  M02 & 1 & 19.40 & 19.10 \\
  M03 & 2 & 19.54 & 19.24 \\
  M04 & 3 & 19.68 & 19.38 \\
  M05 & 4 & 19.82 & 19.52 \\
  M06 & 5 & 19.36 & 19.06 \\
  M07 & 6 & 19.50 & 19.20 \\
  M08 & 7 & 19.64 & 19.34 \\
  M09 & 8 & 19.78 & 19.48 \\
  M10 & 9 & 19.92 & 19.62 \\
  M11 & 10 & 19.46 & 19.16 \\
  M12 & 11 & 19.60 & 19.30 \\
  M13 & 12 & 19.74 & 19.44 \\
  M14 & 13 & 19.88 & 19.58 \\
  M15 & 14 & 20.02 & 19.72 \\
  M16 & 15 & 19.56 & 19.26 \\
  M17 & 16 & 19.70 & 19.40 \\
  M18 & 17 & 19.84 & 19.54 \\
  M19 & 18 & 19.98 & 19.68 \\
  M20 & 19 & 20.12 & 19.82 \\
  M21 & 20 & 19.66 & 19.36 \\
  M22 & 21 & 19.80 & 19.50 \\
  M23 & 22 & 19.94 & 19.64 \\
  M24 & 23 & 20.08 & 19.78 \\
  M25 & 24 & 20.22 & 19.92 \\
  M26 & 25 & 19.76 & 19.46 \\
  M27 & 26 & 19.90 & 19.60 \\
  M28 & 27 & 20.04 & 19.74 \\
  M29 & 28 & 20.18 & 19.88 \\
  M30 & 29 & 20.32 & 20.02 \\
  M31 & 30 & 19.86 & 19.56 \\
  M32 & 31 & 20.00 & 19.70 \\
  M33 & 32 & 20.14 & 19.84 \\
  M34 & 33 & 20.28 & 19.98 \\
  M35 & 34 & 20.42 & 20.12 \\
  M36 & 35 & 19.96 & 19.66 \\
  M37 & 36 & 20.10 & 19.80 \\
  M38 & 37 & 20.24 & 19.94 \\
  M39 & 38 & 20.38 & 20.08 \\
  M40 & 39 & 20.52 & 20.22 \\
\end{longtblr}

\section{Interpret the result within the limits of the example}
\index{uncertainty}
\label{sec:interpretation}

The reported mean describes forty constructed values. Their digits follow
from the generating rule. Estimating a room temperature or the accuracy
of a sensor would require observations from a physical instrument.

%<*auditcite>
A correction compensates for an estimated systematic effect.%
\footcite[entry~2.53]{vim}
%</auditcite>
Here the shift is stipulated by the generator. To apply it to a real
instrument we would first need an independent estimate of its bias.

A mean also depends on which observations enter the sum. In the definition
used by \textcite{nist-location}, each observation contributes once.
Removing one row changes both the numerator and the denominator. The audit
in Appendix~\ref{chap:missing} measures the effect of just such a loss.

\section{Read the calculation across its three representations}
\label{sec:review}

Start with the adjusted mean in Table~\ref{tab:summary}. Then choose a
record from Table~\ref{tab:series} and check its offset by hand. Finally,
run Listing~\ref{lst:process} to recover the mean from the working file.
If the three checks disagree, the input, the transformation and the report
are available separately for inspection.

\newthought{To repeat the study}, begin with the decision recorded at the bench.
Figure~\ref{fig:design} starts with the question we can answer before
there is a file. Figure~\ref{fig:provenance} connects the result to the
inputs needed to recover it. To repeat the demonstration in
Chapter~\ref{chap:measurements}, use Table~\ref{tab:files} to match
each generated file to its expected properties.

\printbibliography[heading=subbibintoc,title={Sources}]

\part{Checking the evidence}
\appendix
\chapter[One missing record]{Auditing a copy with one missing record}
\label{chap:missing}

Suppose a colleague sends a copy of the working table with one line
missing. The surviving values still look plausible. We can find the gap
from the identifiers, then work out exactly how much the omission changes
the reported mean. This exercise uses a copy of the same demonstration
data as Chapter~\ref{chap:measurements}.%
\sidenote[][3pt]{Keep the forty-row working file as the reference. All values in
this appendix are synthetic.}

\section*{Locate the gap before averaging}
\index{missing records}

The last four identifiers in Table~\ref{tab:series} correspond to minutes
36 through 39. In the copy, minute 37 is immediately followed by minute
39. Figure~\ref{fig:missing-minute} gives each minute its own position,
including the minute for which the copy has no value.

\hvFloat[wide,capPos=outer,capVPos=top,
         floatPos=htbp,floatCapSep=\marginparsep]
  {figure}
  {\makebox[\linewidth][c]{\begin{tikzpicture}[x=15mm,y=8mm,font=\small]
    \node[anchor=east] at (-0.4,1) {Reference};
    \node[anchor=east] at (-0.4,0) {Copy};
    \foreach \x/\minute in {0/36,1/37,2/38,3/39}{
      \fill[luatufteblue] (\x,1) circle (2.5pt);
      \node at (\x,-0.75) {\minute};
    }
    \foreach \x in {0,1,3}
      \fill[luatufteblue] (\x,0) circle (2.5pt);
    \draw[luatuftepetrol] (2,0) circle (3.3pt);
    \node[anchor=east] at (-0.4,-0.75) {Minute};
  \end{tikzpicture}}}
  {The last four minutes of the series. The open circle marks the
   missing record \texttt{M39}.}
  {fig:missing-minute}

\section*{Account for the change in the report}
\index{rounding}

The complete table contains forty adjusted readings with mean
\qty{19.59}{\celsius}. The omitted reading is
\qty{20.08}{\celsius}. Using the numerical values in degrees Celsius,
we can reconstruct the new mean directly from the old sum.
Table~\ref{tab:audit-neighbours} identifies the two surviving neighbours.
\begin{margintable}[3pt]
  \begin{tabular*}{\linewidth}{@{}l@{\extracolsep{\fill}}rr@{}}
    \toprule
    Record & Minute & \textdegree{}C \\
    \midrule
    M38 & 37 & 19.94 \\
    M40 & 39 & 20.22 \\
    \bottomrule
  \end{tabular*}
  \caption{Adjusted readings beside the gap in the audit copy.}
  \label{tab:audit-neighbours}
\end{margintable}
\begin{equation}
  \begin{aligned}
    S_{40} &= 40 \times 19.59 = 783.60, \\
    S_{39} &= 783.60 - 20.08 = 763.52, \\
    \bar y_{39} &= 763.52 / 39 \approx 19.5774 .
  \end{aligned}
  \label{eq:missing-mean}
\end{equation}
At the report's two decimal places, the copy gives
\qty{19.58}{\celsius}. A single line accounts for the change of
\qty{0.01}{\celsius} in the printed result. The gap in
Figure~\ref{fig:missing-minute} also tells us why rounding the mean
to one decimal place would hide this particular omission.

\clearpage
\section*{Reconstruct the missing minute}
\index{interpolation}
\index{missing records}

There are two different quantities we might want to recover. The
first is the mean of the file that actually arrived. The second is
the reading at minute 38. Substituting either answer for the other
would obscure what was lost.

%<*auditnote>
Keep the denominator with the result.%
\sidenote{Only 39 of the 40 readings survive.}
%</auditnote>
The same file supports two reproducible statements: its sum is
\qty{763.52}{\celsius} and its rounded mean is \qty{19.58}{\celsius}.
Table~\ref{tab:audit-width} places them beside the complete record.

%<*meanrows>
\newcommand*{\auditmeans}{%
  \begin{tabular*}{\linewidth}{@{}l@{\extracolsep{\fill}}rrr@{}}
    \toprule
    Working copy & Rows & Sum (\textdegree{}C) & Mean (\textdegree{}C) \\
    \midrule
    All constructed readings & 40 & 783.60 & 19.59 \\
    Record M39 omitted       & 39 & 763.52 & 19.58 \\
    \bottomrule
  \end{tabular*}}
%</meanrows>
%<*auditwidth>
\begin{table*}[htbp]
  \caption{Checking the two reported means.}
  \label{tab:audit-width}
  \auditmeans
\end{table*}
%</auditwidth>

The readings bracketing the gap are one minute away on either side.
Their midpoint gives a local estimate,
\[
  \widehat y_{39}=\frac{19.94+20.22}{2}
                    =20.08\,\unit{\celsius}.
\]
In this segment the constructed series advances in equal steps.
The midpoint therefore recovers the held-out reading exactly.
Across one of the five-minute resets that assumption would fail.

%<*estimaterows>
\newcommand*{\auditestimates}{%
  \begin{tabular*}{\linewidth}{@{}l@{\extracolsep{\fill}}rr@{}}
    \toprule
    Rule & Estimate (\textdegree{}C) & Error (\textdegree{}C) \\
    \midrule
    Midpoint & 20.08 & 0.00 \\
    Mean of surviving records & 19.58 & $-0.50$ \\
    \bottomrule
  \end{tabular*}}
%</estimaterows>
%<*hvtablecall>
\hvFloat[wide,capPos=outer,capVPos=top,
         floatPos=htbp,floatCapSep=\marginparsep]
  {table}{\auditestimates}
  {M39 errors are estimate minus reference.}
  {tab:audit-estimates}
%</hvtablecall>

The two estimates in Table~\ref{tab:audit-estimates} use the same
surviving records. Only the midpoint uses their order. A report of
the repaired series should retain the gap in the input file, record
the rule beside the replacement, and distinguish the estimated value
from the 39 values that survived.
%END-SPECIMEN-FILE
%</specimenchapter>
%
% Extract references.bib verbatim, including its listing range markers.
%<*specimenreferences>
%<<END-SPECIMEN-FILE
@online{kaobook,
  author       = {Marotta, Federico},
  title        = {{kaobook}: A {LaTeX} class for books, reports or theses},
  url          = {https://github.com/fmarotta/kaobook},
  urldate      = {2026-12-02},
  organization = {kaobook project},
  langid       = {english}
}

@online{lppl,
  author       = {{The LaTeX Project}},
  date         = {2008-05-04},
  title        = {The {LaTeX} Project Public License, Version 1.3c},
  url          = {https://www.latex-project.org/lppl/lppl-1-3c/},
  urldate      = {2026-12-02},
  organization = {The LaTeX Project},
  langid       = {english}
}

@online{vim,
  author = {{Joint Committee for Guides in Metrology}},
  shortauthor = {{JCGM}},
  date = {2012},
  title = {International Vocabulary of Metrology},
  subtitle = {Entry 2.53: Correction},
  url = {https://jcgm.bipm.org/vim/en/2.53.html},
  urldate = {2026-12-02}
}

@online{nist-location,
  author = {{National Institute of Standards and Technology}},
  shortauthor = {{NIST}},
  title = {Measures of Location},
  organization = {{NIST/SEMATECH} e-Handbook of Statistical Methods},
  url = {https://www.itl.nist.gov/div898/handbook/eda/section3/eda351.htm},
  urldate = {2026-12-02}
}
%END-SPECIMEN-FILE
%</specimenreferences>
% \fi
