\NeedsTeXFormat{LaTeX2e}
\ProvidesExplPackage{PrimeTeX/packages/Marginalia}{2025-09-12}{1.0}{
	Marginalia commands.
}

\marginaliasetup{
	width	= {\marginparwidth},
	xsep	= {\marginparsep},
	ysep	= {\parskip},
	ysep~page~bottom = {
		- 1in	% Top gutter
		+ \paperheight
		- \voffset
		- \topmargin
		- \headheight
		- \headsep
		- \textheight
	},
	yshift	= {7pt},	% Just a magic number that lines up margin notes with their reference.
	style~recto~outer = {\RaggedRight\small\color{marginTextColor}},
	style~verso~outer = {\RaggedLeft\small\color{marginTextColor}},
}

\NewDocumentCommand{\MarginHyperSetup}{}{
	\bool_if:NTF \g_electronic_bool {
		\hypersetup{allcolors = linkColor}
	}{
		\hypersetup{allcolors = marginTextColor}
	}
}

% Put a glossary definition in a margin paragraph.
\NewDocumentCommand{\@MarginDef}{O{} m m}{%
	\index{\glsentryname{#2}}% Add a reference to this in the index.
	\strong{#3{#2}}% This is the text that appears on the page.
	\marginalia[#1]{%
		\MarginHyperSetup%
		\strong{\Glsentryname{#2}:}% Create the title of the margin note.
		\enspace\glsdesc*{#2}% Create the text of the margin note.
	}%
}
\NewDocumentCommand{\MarginDef}{O{} m}{%
	\@MarginDef[#1]{#2}{\gls}%
}
\NewDocumentCommand{\MarginDefCap}{O{} m}{%
	\@MarginDef[#1]{#2}{\Gls}%
}
\NewDocumentCommand{\MarginDefPl}{O{} m}{%
	\@MarginDef[#1]{#2}{\glspl}%
}
\NewDocumentCommand{\MarginDefCapPl}{O{} m}{%
	\@MarginDef[#1]{#2}{\Glspl}%
}

% Put a footnote in a margin paragraph.
\NewDocumentCommand{\MarginNote}{O{} +m}{%
	\footnotemark%
	\marginalia[#1]{%
		\MarginHyperSetup%
		\footnotemark[\value{footnote}]#2%
	}%
}

% Wrapper for \marginalia with some improvements.
\NewDocumentCommand{\Marginalia}{
	% #1: Options passed to \marginalia.
	O{}
	% #2: Contents.
	+m
}{
	% This mbox ensures that the margin paragraph is counted as part of the
	% following paragraph and is vertically aligned with it.
	\mbox{
		\marginalia[#1]{
			\MarginHyperSetup
			#2
		}
	}
}

\NewDocumentCommand{\MarginFig}{
	% #1: Options passed to \marginalia via \Marginalia.
	O{}
	% #2: Graphic file name.
	m
	% #3: Options passed to \includegraphics.
	O{}
	% #4: Label.
	>{\TrimSpaces}m
	% #5: Caption.
	>{\TrimSpaces}+m
}{
	\Marginalia{
		\begin{MyCaption}[
			format={\RaggedOutside\small\color{captionColor}}
		]{fig:#4}{#5}
			\Centering\includegraphics[keepaspectratio,#3]{#2}
		\end{MyCaption}
	}
}