\BLOCK{ if ts_extra_packages }
\BLOCK{- set ns = namespace(has_tabularx=False, has_marginnote=False) }
\BLOCK{ for name, options in ts_extra_packages }
\BLOCK{- if name == "tabularx" -}
\BLOCK{- set ns.has_tabularx = True -}
\BLOCK{- endif }
\BLOCK{- if name == "marginnote" -}
\BLOCK{- set ns.has_marginnote = True -}
\BLOCK{- endif }
\usepackage\BLOCK{ if options }[\VAR{options}]\BLOCK{ endif }{\VAR{name}}
\BLOCK{ endfor }
\BLOCK{- if ns.has_tabularx }
\newcolumntype{Y}{>{\centering\arraybackslash}X}
\newcolumntype{Z}{>{\raggedleft\arraybackslash}X}
\BLOCK{- endif }
\BLOCK{- if ns.has_marginnote }
% Default margin-note styling. Notes are typeset at ``\footnotesize`` so they
% fit narrow margins, and ``\sloppy`` + a generous ``\emergencystretch`` plus
% lowered hyphenation penalties let the line breaker stretch / hyphenate
% rather than overshoot the box: a long technical word (URL, German compound,
% French ``anticonstitutionnellement``…) hyphenates instead of poking past
% the page edge. Override with ``\renewcommand*{\marginfont}{…}`` in a
% custom preamble snippet to disable any of these.
\renewcommand*{\marginfont}{%
  \footnotesize
  \sloppy
  \emergencystretch=1em
  \hyphenpenalty=50
  \exhyphenpenalty=50
}
% Clamp ``\marginparwidth`` so margin notes never overflow the page edge,
% even when the user's geometry reserves less horizontal space than LaTeX's
% default ``\marginparwidth`` (~3.9 cm). We compute the space actually
% available on each side (recto / verso) at ``\AtBeginDocument`` time —
% once ``geometry`` has finalised ``\textwidth`` / ``\oddsidemargin`` /
% ``\evensidemargin`` — and keep the smaller of the two so the note fits on
% both sides in twoside documents. A 6 pt safety buffer is subtracted on top
% of ``\marginparsep`` so a slightly-too-long internal line still has room
% before clipping the page edge.
\newlength{\tsmarginparavail}
\newlength{\tsmarginparalt}
\newlength{\tsmarginparbuf}
\setlength{\tsmarginparbuf}{6mm}
\makeatletter
\AtBeginDocument{%
  \setlength{\tsmarginparavail}{\dimexpr\paperwidth-\textwidth-1in-\oddsidemargin-\marginparsep-\tsmarginparbuf\relax}%
  \ifdim\tsmarginparavail<\z@\setlength{\tsmarginparavail}{\z@}\fi
  \if@twoside
    \setlength{\tsmarginparalt}{\dimexpr1in+\evensidemargin-\marginparsep-\tsmarginparbuf\relax}%
    \ifdim\tsmarginparalt<\z@\setlength{\tsmarginparalt}{\z@}\fi
    \ifdim\tsmarginparalt<\tsmarginparavail
      \setlength{\tsmarginparavail}{\tsmarginparalt}%
    \fi
  \fi
  \ifdim\tsmarginparavail<\marginparwidth
    \setlength{\marginparwidth}{\tsmarginparavail}%
  \fi
}
\makeatother
\BLOCK{- endif }
\BLOCK{ endif }
