% \iffalse meta-comment
%
% Copyright (C) 2019-2023 by Jan Hajer
% -----------------------------------
%
% This file may be distributed and/or modified under the
% conditions of the LaTeX Project Public License, either version 1.3c
% of this license or (at your option) any later version.
% The latest version of this license is in:
%
% http://www.latex-project.org/lppl.txt
%
% and version 1.3c or later is part of all distributions of LaTeX
% version 2005/12/01 or later.
%
% \fi
%
% \iffalse

%<package>\NeedsTeXFormat{LaTeX2e}[2021-11-15]
%<package>\ProvidesPackage{hep-math}[2026/11/13 v1.6 Math macros for operators, derivatives, delimiters, bra-ket notation and expectation values]
%<documentation>\ProvidesFile{hep-math-documentation.tex}[2026/11/13 v1.6 hep-math documentation]
%
%<*documentation>
\RequirePackage[l2tabu, orthodox]{nag}
\documentclass{ltxdoc}

\renewcommand*\theCodelineNo{\rmfamily\tstyle\footnotesize\arabic{CodelineNo}}
\AtBeginEnvironment{macrocode}{\renewcommand*{\ttdefault}{clmt}}
\renewcommand*{\MacroFont}{\codestyle}
\AtBeginDocument{\DeleteShortVerb{\|}}
\AtBeginDocument{\MakeShortVerb{\"}}
\EnableCrossrefs
\CodelineIndex
\RecordChanges

\usepackage{hologo}

\usepackage[parskip,oldstyle,font=10pt]{hep-paper}
\bibliography{bibliography}

\setlength{\fboxsep}{1pt}
\newenvironment{columns}[1][.5]{%
  \par\vspace{-\bigskipamount}%
  \begin{minipage}[t]{\linewidth}%
  \begin{minipage}[t]{#1\linewidth}%
  \def\column{%
    \end{minipage}%
    \begin{minipage}[t]{\linewidth-#1\linewidth}%
  }%
}{\end{minipage}\end{minipage}\par}
%</documentation>

%<*driver>
\expandafter\newif\csname ifshort\endcsname
\shortfalse
\begin{document}
\DocInput{hep-math-implementation.dtx}
\end{document}
%</driver>
%
% \fi
%
% \CheckSum{1098}
%
% \CharacterTable
%  {Upper-case    \A\B\C\D\E\F\G\H\I\J\K\L\M\N\O\P\Q\R\S\T\U\V\W\X\Y\Z
%   Lower-case    \a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p\q\r\s\t\u\v\w\x\y\z
%   Digits        \0\1\2\3\4\5\6\7\8\9
%   Exclamation   \!     Double quote  \"     Hash (number) \#
%   Dollar        \$     Percent       \%     Ampersand     \&
%   Acute accent  \'     Left paren    \(     Right paren   \)
%   Asterisk      \*     Plus          \+     Comma         \,
%   Minus         \-     Point         \.     Solidus       \/
%   Colon         \:     Semicolon     \;     Less than     \<
%   Equals        \=     Greater than  \>     Question mark \?
%   Commercial at \@     Left bracket  \[     Backslash     \\
%   Right bracket \]     Circumflex    \^     Underscore    \_
%   Grave accent  \`     Left brace    \{     Vertical bar  \|
%   Right brace   \}     Tilde         \~}
%
% \changes{v1.0}{2021/09/01}{First release on CTAN: \cs{mathdef}, overlines, accents, operators, fractions, units, differentials, delimiters, probabilities, brackets, bra-ket notation, matrix elements, and vectors.}
% \changes{v1.1}{2022/11/01}{Added optional defaults to \cs{mathdef}, \cs{widebar}, centred colons, and separate bra-ket spacing, loaded amssymb, and improved flat fractions and slashed symbols.}
% \changes{v1.2}{2023/07/01}{Added \cs{imaginaryunit}, \cs{unit} and \cs{unitfrac} in math mode, optional integral placement, \cs{floor} and \cs{ceil}, and refined the spacing of differentials and flat fractions.}
% \changes{v1.3}{2024/11/01}{Switched underlining from soulutf8 to soul, stopped redefining \cs{int}, added \cs{slashedpartialdifferential} and \cs{spd}, and defined \cs{row} and \cs{column} with \cs{mathdef}.}
% \changes{v1.4}{2025/09/01}{Applied starred command definitions consistently.}
% \changes{v1.5}{2026/08/01}{Raised the LaTeX format requirement and expanded the documentation, README, and examples.}
% \changes{v1.6}{2026/11/13}{Removed the patch of nfssext-cfr, which ran before nfssext-cfr defined its macros. The hep-font package now keeps nfssext-cfr from overwriting \cs{set}. Fixed \cs{mathdef} macros, \cs{trans}, and \cs{slashed} in bookmarks and moving arguments, added PDF-string versions of operators, units, inverses, and fractions, gave all trigonometric functions the height of \cs{sin}, removed spurious spaces from \cs{unitfrac}, avoided the clash of amssymb with unicode-math when loaded after hep-math-font, and let the derivatives follow the math style, with \cs{tfrac} for the second star.}
%
% \ifshort
%<*documentation>
% \fi
%
\GetFileInfo{hep-math.sty}

\title{The \software{hep-math} package\thanks{This document corresponds to \software{hep-math}~\fileversion.}}
\subtitle{Math macros for operators, derivatives, delimiters, bra-ket notation and expectation values}
\author{Jan Hajer \email{jan.hajer@tecnico.ulisboa.pt}}
\date{\filedate}

% \ifshort
\begin{document}
% \fi

\newgeometry{vscale=.8, vmarginratio=3:4, includeheadfoot, left=11em, marginparwidth=4.6cm, marginparsep=3mm, right=7em}

\maketitle

\begin{abstract}
The \software{hep-math} package extends \software{mathtools} and \software{amsmath} with HEP-oriented math notation.
It provides math-only command definitions, improved overlines and arrow accents, operator names, fractions and unit helpers, differentials and derivative builders, paired delimiters, probabilities, brackets, quantum-mechanical bra-ket notation, matrix elements, and expectation values.
\end{abstract}

To use the package place "\usepackage{hep-math}" in the preamble.

The \software{mathtools} \cite{mathtools} package is loaded, which in turn loads the \hologo{AmSLaTeX} \software{amsmath} \cite{amsmath} package.
Horizontal spacing in inline equations and page breaks in block equations are marginally adjusted.
\DescribeMacro{\left}
\DescribeMacro{\right}
Spacing around "\left" and "\right" is fixed with the \software{mleftright} package \cite{mleftright}.

\section{Macros}

\DescribeMacro{\mathdef}
The "\mathdef"\marg{name}\oarg{arguments}\marg{code} macro \prefix{re}{defines} macros only within math mode without changing the text mode definition.

\DescribeMacro{\i}
\DescribeMacro{\d}
The imaginary unit "\i" and the differential "\d" are defined using this functionality.
Their math definitions are set at the beginning of the document, unless they have been defined with "\mathdef" in the preamble, \eg via "\mathdef{\d}{\mathrm d}".
Repeated uses of "\mathdef" for the same macro replace its math definition and keep its text definition.

\DescribeMacro{\overline}
The "\overline" macro is adjusted to \overline{work also outside} of math mode using the \software{soul} \cite{soul} package.
Text containing macros unknown to \software{soul}, such as "\ref"\marg{key}, is overlined as a whole without line breaks.

\DescribeMacro{\oset}
\DescribeMacro{\overleft}
\DescribeMacro{\overright}
\DescribeMacro{\overleftright}
A better looking over left right arrow is defined \ie $\overleftright{\partial}$ using a new "\oset"\marg{over}\marg{math} functionality.

\DescribeMacro{\diag}
\DescribeMacro{\sgn}
Diagonal matrix "\diag", signum "\sgn", trace "\tr", "\Tr", and "\rank" operators are defined.

% \DescribeMacro{\Re}
% \DescribeMacro{\Im}
% The real and imaginary projectors are redefined to look like ordinary operators.

\DescribeMacro{\arccsc}
"\arccsc" and other inverse trigonometric functions are defined, including the short forms "\asin", "\acos", and so on.

\DescribeMacro{\sin}
\DescribeMacro{\cos}
\DescribeMacro{\tan}
"\cos", "\tan", and all other trigonometric functions and their inverses are adjusted to have the same height as "\sin".

\subsection{Fractions and units}

\DescribeMacro{\unit}
\DescribeMacro{\inv}
The correct spacing for units is provided by the macro "\unit"\oarg{value}\marg{unit} from the \software{siunitx} package \cite{siunitx} which can also be used in text mode.
The macro "\inv"\oarg{power}\marg{text} allows to avoid math mode also for inverse units such as \unit[5]{\inv{fb}} typeset via "\unit[5]{\inv{fb}}".

\DescribeMacro{\nicefrac}
\DescribeMacro{\flatfrac}
\DescribeMacro{\textfrac}
The "\frac"\marg{number}\marg{number} macro is accompanied by "\nicefrac"\linebreak[1]\marg{number}\linebreak[1]\marg{number}, "\textfrac"\marg{number}\marg{number}, and "\flatfrac"\marg{number}\marg{number} leading to $\frac12$, $\nicefrac12$, \textfrac12, and $\flatfrac12$.
The "\textfrac" macro is mostly intended if a font with oldstyle numerals is used.

Some macros of the \software{physics} package \cite{physics} are reimplemented with a more conventional typesetting in mind.
Finer details about mathematical typesetting can be found in \cite{gregorio:2020}.

\subsection{Differentials and derivatives}

\DescribeMacro{\differential}
\DescribeMacro{\newderivative}
\DescribeMacro{\newpartialderivative}
The three macros "\differential"\marg{symbol}, "\newderivative" "{\name}"\marg{symbol}, and "\newpartialderivative" "{\name}"\marg{symbol} allow to define a differential with correct spacing, a derivative using this differential, and if necessary a partial derivative that can handle three dimensional derivatives.

\DescribeMacro{\d}
\DescribeMacro{\dv}
These macros are used for the usual differential and derivative, producing $\d x$ via "\d x" and
\begin{center}
\begin{tabular}{*4c}
"\dv[f]x" & "\dv*[f]x^n" & "\dv[f]x*^n" & "\dv*[f]x*^n" \\
$\dv[f]x$ & $\dv*[f]x^n$ & $\dv[f]x*^n$ & $\dv*[f]x*^n$ \\
"\dv xf" & "\dv*xf" & "\dv x*f" & "\dv*x*f" \\
$\dv xf$ & $\dv*xf$ & $\dv x*f$ & $\dv*x*f$
\end{tabular}
\end{center}
via "\dv*"\oarg{f}\marg{x}"*""^"\marg{n}.
The fraction follows the math style, like "\frac".
The first star selects the flat fraction "\flatfrac" and the second star the small fractions "\tfrac" and "\nicefrac", respectively.
Upright differential can be produced via "\renewcommand""{\diffsymbol}" "{\mathrm d}".
The differential takes care of the correct spacing as long as it is placed at the end of the integral $\int f(x)\d x$.
In order to archive correct spacing when it is placed at the beginning of the integral it is advisable to place the whole expression in a "\mathop{\int\d x} f(x)"  such that $\mathop{\int\d x} f(x)$.

\DescribeMacro{\pd}
\DescribeMacro{\pdv}
Similarly a partial differential and derivative are defined that can be used according to "\pdv*"\oarg{f}\marg{x}"*""^"\marg{a}\oarg{y}"^"\marg{b}\oarg{z}"^"\marg{c}.
\begin{center}
\begin{tabular}{*4c}
"\pdv[f]x" & "\pdv[f]x[y]" & "\pdv[f]x^3" & "\pdv[f]x^2[y]" \\
$\pdv[f]x$ & $\pdv[f]x[y]$ & $\pdv[f]x^3$ & $\pdv[f]x^2[y]$ \\
"\pdv[f]x^2[y]^3" & "\pdv[f]x[y]^3" & "\pdv x[y]f"\\
$\pdv[f]x^2[y]^3$ & $\pdv[f]x[y]^3$ & $\pdv x[y]f$
\end{tabular}
\end{center}
Integer orders are summed in the numerator, while other orders are added, as in $\pdv[f]x^n[y]$ typeset via "\pdv[f]x^n[y]".

\DescribeMacro{\var}
\DescribeMacro{\fdv}
Similarly a functional variation and functional derivative are defined.

\DescribeMacro{\cancel}
\DescribeMacro{\slashed}
The "\cancel"\marg{characters} macro from the \software{cancel} package \cite{cancel} and the "\slashed" \marg{character} macro from the \software{slashed} package \cite{slashed} allow to $\cancel{\text{cancel}}$ math and use the Dirac slash notation \ie $\slashed \pd$, respectively.

\subsection{Paired delimiters}

\DescribeMacro{\abs}
\DescribeMacro{\norm}
\begin{center}
\begin{tabular}{*8r}
"\abs x" & "\norm x" & "\norm[2]x" & "\norm*[2]x" \\
$\abs x$ & $\norm x$ & $\norm[2]x$ & $\norm*[2]x$
\end{tabular}
\end{center}

\DescribeMacro{\eval}
\DescribeMacro{\order}
\begin{center}
\begin{tabular}{*8r}
"\order x" & "\eval x_0^\infty" & "\eval* x_0^\infty" \\
$\order x$ & $\eval x_0^\infty$ & $\eval* x_0^\infty$
\end{tabular}
\end{center}

\DescribeMacro{\newpair}
\DescribeMacro{\comm}
\DescribeMacro{\acomm}
The "\newpair"\marg{name}\marg{left delim} \marg{right delim}"_"\marg{subscript}"^"\marg{superscript} macro is defined and used for the definition of \prefix{anti}{commutators} and Poisson brackets.
\begin{center}
\begin{tabular}{*8r}
"\pb xy" & "\comm xy" & "\acomm xy" \\
$\pb xy$ & $\comm xy$ & $\acomm xy$
\end{tabular}
\end{center}
They can easily be redefined using \eg "\newpair\comm\lbrack\rbrack_-".

\DescribeMacro{\bra}
\DescribeMacro{\ket}
\DescribeMacro{\braket}
\DescribeMacro{\ketbra}
\DescribeMacro{\mel}
\DescribeMacro{\ev}
\DescribeMacro{\vev}
Macros for the bra-ket notation are introduced.
\begin{center}
\begin{tabular}{*4c}
"\bra x" & "\ket x" & "\braket xy" & "\ketbra xy" \\
$\bra x$ & $\ket x$ & $\braket xy$ & $\ketbra xy$ \\
"\mel xyz" & "\ev x" & "\ev[\Omega] x" & "\vev x" \\
$\mel xyz$ & $\ev x$ & $\ev[\Omega] x$ & $\vev x$
\end{tabular}
\end{center}

\DescribeMacro{\column}
\DescribeMacro{\row}
Macros for row and column vectors are introduced together with a symbol for transpose vectors.
\begin{center}
\begin{tabular}{*4c}
"\column{x,y,z}" & "\row{x,y,z}^\trans" \\
$\column{x,y,z}$ & $\row{x,y,z}^\trans$ \\
\end{tabular}
\end{center}

\subsection{PDF strings}

If the \software{hyperref} package \cite{hyperref} is loaded, the macros also work in moving arguments that end up in PDF strings such as bookmarks.
There "\i" and "\d" become i and d, overlines and slashes keep their argument, operators such as "\cos" keep their name, "\unit[5]{GeV}" becomes 5 GeV, "\inv{fb}" becomes fb\textasciicircum-1, "^\trans" becomes \textasciicircum T, and fractions become flat as in 1/2.
Other macros such as derivatives and paired delimiters keep only their arguments.

\section{Environments}

\DescribeMacro{eqnarray}
The "eqnarray" environment is depreciated, the "split", "multline", "align", "multlined", "aligned", "alignedat", and "cases" environments of the \software{amsmath} and \software{mathtools} packages should be used instead.

\DescribeMacro{equation}
Use the "equation" environment for short equations.
\begin{columns}
\begin{verbatim}
\begin{equation}
  left = right \ .
\end{equation}
\end{verbatim}
\column
\begin{equation}
\framebox[2em]{left\strut} = \framebox[7em]{right\strut} \ .
\end{equation}
\end{columns}

\DescribeMacro{multline}
Use the "multline" environment for longer equations.
\begin{columns}
\begin{verbatim}
\begin{multline}
  left = right 1 \\
  + right 2 \ .
\end{multline}
\end{verbatim}
\column
\begin{multline}
\framebox[2em]{left\strut} = \framebox[7em]{right 1\strut} \\
\framebox[7em]{+ right 2\strut} \ .
\end{multline}
\end{columns}

\DescribeMacro{split}
Use the "split" sub environment for equations in which multiple equal signs should be aligned.
\begin{columns}
\begin{verbatim}
\begin{equation} \begin{split}
  left &= right 1 \\
  &= right 2 \ .
\end{split} \end{equation}
\end{verbatim}
\column
\begin{equation}
\begin{split}
\framebox[2em]{left\strut} &= \framebox[7em]{right 1\strut} \\
&= \framebox[7em]{right 2\strut} \ .
\end{split}
\end{equation}
\end{columns}

\DescribeMacro{align}
Use the "align" environment for the vertical alignment and horizontal distribution of multiple equations.
\begin{columns}
\begin{verbatim}
\begin{subequations} \begin{align}
  left &= right \ , &
  left &= right \ , \\
  left &= right \ , &
  left &= right \ .
\end{align} \end{subequations}
\end{verbatim}
\column
\begin{subequations}
\begin{align}
\framebox[2em]{left\strut} &= \framebox[3em]{right\strut} \ , &
\framebox[2em]{left\strut} &= \framebox[3em]{right\strut} \ , \\
\framebox[2em]{left\strut} &= \framebox[3em]{right\strut} \ , &
\framebox[2em]{left\strut} &= \framebox[3em]{right\strut} \ .
\end{align}
\end{subequations}
\end{columns}

\DescribeMacro{aligned}
Use the "aligned" environment within a "equation" environment if the aligned equations should be labeled with a single equation number.

\DescribeMacro{multlined}
Use the "multlined" environment if either "split" or "align" contain very long lines.
\begin{columns}
\begin{verbatim}
\begin{equation} \begin{split}
  left &= right 1 \\ &=
  \begin{multlined}[t]
     right 2 \\ + right 3 \ .
  \end{multlined}
\end{split} \end{equation}
\end{verbatim}
\column
\begin{equation}
\begin{split}
\framebox[2em]{left\strut} &= \framebox[7em]{right 1\strut} \\ &=
 \begin{multlined}[t]
  \framebox[7em]{right 2\strut} \\
  \framebox[7em]{+ right 3\strut} \ .
\end{multlined}
\end{split}
\end{equation}
\end{columns}

\DescribeMacro{alignat}
Use the "alignat" environment together with the "\mathllap" macro for the alignment of multiple equations with vastly different lengths.
\begin{columns}
\begin{verbatim}
\begin{subequations}
\begin{alignat}{2}
  left &= long right && \ , \\
  le. 2 &= ri. 2 \ , &
  \mathllap{le. 3 = ri. 3} & \ .
\end{alignat}
\end{subequations}
\end{verbatim}
\column
\begin{subequations}
\begin{alignat}{2}
\framebox[2em]{left\strut} &=
\framebox[11em]{long right\strut} && \ , \\
\framebox[2em]{le.\ 2\strut}
&= \framebox[2.5em]{ri.\ 2\strut} \ , &
\mathllap{\framebox[2em]{le.\ 3\strut}
= \framebox[2.5em]{ri.\ 3\strut}} & \ .
\end{alignat}
\end{subequations}
\end{columns}

As a rule of thumb if you have to use "\notag", "\nonumber", or perform manual spacing via "\quad" you are probably using the wrong environment.

% \ifshort
\printbibliography

\end{document}
%
%</documentation>
% \fi
%
% \StopEventually{
% \printbibliography
% \PrintChanges
% }
%
% \appendix
%
% \section{Implementation}
%
%<*package>
%
% Load the \software{mathtools} package \cite{mathtools} which loads the \software{amsmath} package \cite{amsmath}.
% Allow page breaks within equations if necessary.
% Adjust the thick and med mu skips slightly.
%    \begin{macrocode}
\RequirePackage{mathtools}
\mathtoolsset{centercolon}
\numberwithin{equation}{section}
\allowdisplaybreaks[1]
\thickmuskip=5mu plus 3mu minus 1mu
\medmuskip=4mu plus 2mu minus 3mu
%    \end{macrocode}
%
% \begin{macro}{\mathdef}
% Define the "\mathdef"\marg{name}\oarg{arguments}\marg{macro} macro which \prefix{re}{defines} macros in math mode only.
% This macro is implemented using the \software{xparse} package \cite{xparse}.
% The dispatch between the two definitions is expandable, so that the macro also works in PDF strings, where a "\let" would be dropped.
% The text definition is copied with "\DeclareCommandCopy", which also copies robust commands correctly.
% If the macro is still the dispatcher of an earlier "\mathdef", only the math definition is replaced, so that the original text definition is kept and the dispatcher does not call itself.
% The dispatcher is recorded in "\hep@mathdef"\meta{name} for this test.
%    \begin{macrocode}
\RequirePackage{xparse}
\DeclareDocumentCommand{\mathdef}{mO{0}om}{%
  \hep@if@mathdef#1{}{%
    \ifdefined#1%
      \expandafter\DeclareCommandCopy\csname hep@text\string#1\endcsname#1%
    \else
      \expandafter\let\csname hep@text\string#1\endcsname=#1%
    \fi
  }%
  \expandafter\let\csname hep@math\string#1\endcsname\relax
  \expandafter\newcommand\expandafter*\csname hep@math\string#1%
  \IfNoValueTF{#3}{\endcsname[#2]}{\endcsname[#2][#3]}{#4}%
  \DeclareRobustCommand#1{%
    \csname hep@\ifmmode math\else text\fi\string#1\endcsname
  }%
  \expandafter\let\csname hep@mathdef\string#1\endcsname#1%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\hep@if@mathdef}
% Test whether the macro is the dispatcher of an earlier "\mathdef".
%    \begin{macrocode}
\newcommand*{\hep@if@mathdef}[1]{%
  \ifcsname hep@mathdef\string#1\endcsname
    \expandafter\ifx\csname hep@mathdef\string#1\endcsname#1%
      \expandafter\expandafter\expandafter\@firstoftwo
    \else
      \expandafter\expandafter\expandafter\@secondoftwo
    \fi
  \else
    \expandafter\@secondoftwo
  \fi
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\hep@mathdef@default}
% Define the default math meaning of a macro at the beginning of the document, unless the preamble already defined one with "\mathdef".
%    \begin{macrocode}
\newcommand*{\hep@mathdef@default}[2]{%
  \AtBeginDocument{\hep@if@mathdef#1{}{\mathdef{#1}{#2}}}%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\i}
% Provide an upright imaginary unit in math mode.
%    \begin{macrocode}
\newcommand*{\imaginaryunit}{i}
\hep@mathdef@default{\i}{\imaginaryunit}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\hep@soul@if@safe}
% Test whether the \software{soul} package \cite{soul} can process a text.
% This is the case if every macro in the text, outside of inline math, is known to \software{soul}: registered with "\soulregister", such as font commands and accents, or handled by \software{soul} itself, such as "\\" and "\mbox".
% Other macros may take arguments, which \software{soul} would separate from the macro, or look ahead, as "\xspace" does.
% The same test is defined by the \software{hep-text} package for "\underline", so it is only defined if it does not exist yet.
% "\hep@soul@if@safe" is the \hologo{LaTeXe} name of the conditional "\hep_soul_if_safe:nTF".
%    \begin{macrocode}
\ExplSyntaxOn
\cs_if_exist:NF \hep_soul_if_safe:nTF {
  \seq_new:N \l__hep_soul_seq
  \tl_new:N \l__hep_soul_tl
  \tl_new:N \l__hep_soul_known_tl
  \bool_new:N \l__hep_soul_bool
  \regex_const:Nn \c__hep_soul_math_regex { \cM\$ .*? \cM\$ }
  \regex_const:Nn \c__hep_soul_cs_regex { \c{.*} }
  \tl_const:Nn \c__hep_soul_known_tl {
    \\0\\ \\0\slash \\0\mbox \\0\hbox \\0\soulomit
    \\0\break \\0\linebreak \\0\- \\0\par
  }
  \prg_new_protected_conditional:Npnn \hep_soul_if_safe:n #1 { TF } {
    \group_begin:
    \cs_set:Npn \\ ##1 ##2 { \token_to_str:N ##2 , }
    \tl_set:No \l__hep_soul_known_tl { \the \SOUL@cmds }
    \tl_set:Ne \l__hep_soul_known_tl
      { , \l__hep_soul_known_tl \c__hep_soul_known_tl }
    \tl_set:Nn \l__hep_soul_tl {#1}
    \regex_replace_all:NnN \c__hep_soul_math_regex { } \l__hep_soul_tl
    \regex_extract_all:NVN \c__hep_soul_cs_regex
      \l__hep_soul_tl \l__hep_soul_seq
    \bool_set_true:N \l__hep_soul_bool
    \seq_map_inline:Nn \l__hep_soul_seq {
      \token_if_macro:NT ##1 {
        \exp_args:NNe \tl_if_in:NnF \l__hep_soul_known_tl
          { , \token_to_str:N ##1 , }
          { \bool_set_false:N \l__hep_soul_bool \seq_map_break: }
      }
    }
    \bool_if:NTF \l__hep_soul_bool
      { \group_end: \prg_return_true: }
      { \group_end: \prg_return_false: }
  }
  \cs_new_eq:NN \hep@soul@if@safe \hep_soul_if_safe:nTF
}
\ExplSyntaxOff
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\overline}
% Redefine "\overline" to be a text macro using the \software{soul} package \cite{soul}.
% Extend it as a math macro with the original definition from the \software{amsmath} package \cite{amsmath}.
% The \software{soul} package can only process text whose macros it knows, so text containing other macros, such as "\ref"\marg{key} or "\enquote"\marg{text}, is overlined as a whole with the \TeX\ primitive instead.
%    \begin{macrocode}
\RequirePackage{soul}
% \def\overline#1{{\renewcommand*{\ULdepth}{-1.9ex}{}\uline{#1}}}
\newcommand*\textoverline[1]{%
  \hep@soul@if@safe{#1}{%
    {\setul{-1.9ex}{}\ul{#1}}%
  }{%
    \ensuremath{\m@th\@@overline{\hbox{#1}}}%
  }%
}
\let\overline\textoverline
\DeclareRobustCommand{\over@line}[1]{\@@overline{#1}}
\mathdef{\overline}{\over@line}
\newcommand*\hep@widebar[1]{%
  \mkern2.5mu\overline{\mkern-2.5mu#1\mkern-.5mu}\mkern.5mu%
}
\newcommand*\widebar[1]{%
  \settowidth{\dimen0}{\ensuremath{#1}}%
  \ifdim\dimen0>.475em\hep@widebar{#1}\else\bar{#1}\fi%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\oset}
% Define a new overset macro "\oset"\oarg{offset}\marg{over}\marg{base}
%    \begin{macrocode}
\newcommand*{\oset}[3][-1pt]{%
  \text{\raisebox{.2ex}{$\mathop{#3}\limits^{%
    \vbox to#1{\kern-2\ex@\hbox{$\scriptscriptstyle#2$}\vss}%
  }$}}%
}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\overleftright}
% Define a over left right arrow "\overleftright"\marg{base}.
%    \begin{macrocode}
\newcommand*{\overleft}[1]{\oset{\leftarrow}{#1}}
\newcommand*{\overright}[1]{\oset{\rightarrow}{#1}}
\newcommand*{\overleftright}[1]{\oset{\leftrightarrow}{#1}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{eqnarray}
% Undefine the "eqnarray" environment if not prevented by package option.
%    \begin{macrocode}
% \newif\ifhep@eqnarray\hep@eqnarraytrue
% \ifhep@eqnarray\else
%   \let\eqnarray\@undefined
%   \let\endeqnarray\@undefined
% \fi
%    \end{macrocode}
% \end{macro}
%
% \subsection{Operators}
%
% \begin{macro}{\tr}
% \begin{macro}{\Tr}
% \begin{macro}{\rank}
% \begin{macro}{\erf}
% \begin{macro}{\Res}
% \begin{macro}{\sgn}
% \begin{macro}{\sgn}
% \begin{macro}{\diag}
% Provide the "\diag", "\sgn", and some other operators.
%    \begin{macrocode}
\DeclareMathOperator{\tr}{tr}
\DeclareMathOperator{\Tr}{Tr}
\DeclareMathOperator{\rank}{rank}
\DeclareMathOperator{\erf}{erf}
\DeclareMathOperator{\Res}{Res}
\DeclareMathOperator{\sgn}{sgn}
\DeclareMathOperator{\diag}{diag}
\let\det\relax\DeclareMathOperator{\det}{det}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}

% \begin{macro}{\Re}
% \begin{macro}{\Im}
% Redefine the real and imaginary projectors.
%    \begin{macrocode}
\let\hep@Re\Re\let\Re\relax\DeclareMathOperator{\Re}{\hep@Re}
\let\hep@Im\Im\let\Im\relax\DeclareMathOperator{\Im}{\hep@Im}
%    \end{macrocode}
% \end{macro}
% \end{macro}

% \begin{macro}{\transpose}
% \begin{macro}{\trans}
% Define a robust transpose symbol.
% \software{unicode-math} \cite{unicode-math} already provides "\intercal" and clashes with \software{amssymb} \cite{amssymb} if that is loaded after it.
%    \begin{macrocode}
\@ifpackageloaded{unicode-math}{}{\RequirePackage{amssymb}}
\newcommand*{\hep@transpose}[2]{\raisebox{\depth}{$\m@th#1\intercal$}}
\DeclareRobustCommand*{\transpose}{{\mathpalette\hep@transpose{}}}
\let\trans\transpose
%    \end{macrocode}
% \end{macro}
% \end{macro}



% \subsubsection{Trigonometric functions}
%
% \begin{macro}{\hep@trig@strut}
% \begin{macro}{\cos}
% \begin{macro}{\tan}
% \begin{macro}{\cot}
% \begin{macro}{\sec}
% \begin{macro}{\csc}
% \begin{macro}{\arccos}
% \begin{macro}{\arctan}
% Adjust the height of the trigonometric functions to be equal to sin.
% The phantom i is typeset in the operator font, since a plain "\vphantom{i}" measures the math italic i.
%    \begin{macrocode}
\newcommand*{\hep@trig@strut}{\vphantom{\operator@font i}}
\let\cos\undefined\DeclareMathOperator{\cos}{cos\hep@trig@strut}
\let\tan\undefined\DeclareMathOperator{\tan}{tan\hep@trig@strut}
\let\cot\undefined\DeclareMathOperator{\cot}{cot\hep@trig@strut}
\let\sec\undefined\DeclareMathOperator{\sec}{sec\hep@trig@strut}
\let\csc\undefined\DeclareMathOperator{\csc}{csc\hep@trig@strut}
\let\arccos\undefined
\DeclareMathOperator{\arccos}{arccos\hep@trig@strut}
\let\arctan\undefined
\DeclareMathOperator{\arctan}{arctan\hep@trig@strut}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \begin{macro}{\arccsc}
% \begin{macro}{\arcsec}
% \begin{macro}{\arccot}
% Define arc operators.
%    \begin{macrocode}
\DeclareMathOperator{\arccsc}{arccsc\hep@trig@strut}
\DeclareMathOperator{\arcsec}{arcsec\hep@trig@strut}
\DeclareMathOperator{\arccot}{arccot\hep@trig@strut}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \begin{macro}{\asin}
% \begin{macro}{\acos}
% \begin{macro}{\atan}
% \begin{macro}{\acsc}
% \begin{macro}{\asec}
% \begin{macro}{\acot}
% Define shorthand for arc operators.
%    \begin{macrocode}
\DeclareMathOperator{\asin}{asin}
\DeclareMathOperator{\acos}{acos\hep@trig@strut}
\DeclareMathOperator{\atan}{atan\hep@trig@strut}
\DeclareMathOperator{\acsc}{acsc\hep@trig@strut}
\DeclareMathOperator{\asec}{asec\hep@trig@strut}
\DeclareMathOperator{\acot}{acot\hep@trig@strut}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \begin{macro}{\csch}
% \begin{macro}{\sech}
% Define csch and sech operators.
%    \begin{macrocode}
\DeclareMathOperator{\csch}{csch}
\DeclareMathOperator{\sech}{sech}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \subsection{Units and fractions}
%
% \begin{macro}{\nicefrac}
% Define the "\nicefrac" macro using the \software{xfrac} package \cite{xfrac}.
%    \begin{macrocode}
\RequirePackage{xfrac}
\let\nicefrac\sfrac
%    \end{macrocode}
% \end{macro}
%
% Load the \software{siunitx} package \cite{siunitx}.
%    \begin{macrocode}
\RequirePackage{siunitx}
\providecommand*{\hep@lining@style}{\ifdefined\lstyle\lstyle\fi}
\sisetup{
  reset-math-version=false,
  reset-text-family=false,
  reset-text-series=false,
  uncertainty-mode=separate,
  exponent-product=\cdot,
  unit-mode=text,
  text-font-command=\hep@lining@style,
}
%    \end{macrocode}
% Provide a compatibility macro for older installations.
%    \begin{macrocode}
\ExplSyntaxOn
\cs_if_exist:NF \siunitx_declare_prefix:Nne
{
  \cs_generate_variant:Nn
  \siunitx_declare_prefix:Nnn
  { Nne }
}
\ExplSyntaxOff
%    \end{macrocode}
% \begin{macro}{\unit}
% \begin{macro}{\unitfrac}
% Ensure that its macros are compatible with the definitions used in the depreciated \software{unit} package.
%    \begin{macrocode}
\NewCommandCopy{\hep@unit}{\unit}
\ExplSyntaxOn
  \siunitx_declare_prefix:Nne\mu{-6}{\__siunitx_unit_non_latin:n{"03BC}}
  \prg_new_conditional:Npnn\hep_if_keyval:n#1{TF}{
    \tl_if_in:nnTF{#1}{=}{\prg_return_true:}{\prg_return_false:}
  }
  \cs_new_protected:Npn\hep_unit:nn#1#2{
    \hep_if_keyval:nTF{#1}{\hep@unit[#1]{#2}}
      {\qty[parse-numbers=false]{#1}{#2}}
  }
  \RenewDocumentCommand{\unit}{om}{
    \IfNoValueTF{#1}{\hep@unit{#2}}{\hep_unit:nn{#1}{#2}}
  }
\ExplSyntaxOff
\NewDocumentCommand{\unitfrac}{omm}{%
  \IfNoValueTF{#1}{\hep@unit{#2\per#3}}{\qty{#1}{#2\per#3}}%
}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\inv}
% Provide a macro for the inverse, useful in combination with the unit macro in text mode.
%    \begin{macrocode}
\newcommand*{\inv}[2][1]{#2\ensuremath{^{-#1}}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\textfrac}
% Provide the "\textfrac" macro useful in combination with a font using lining numerals.
%    \begin{macrocode}
\newcommand*{\textfrac}[2]{\ensuremath{\nicefrac{\text{#1}}{\text{#2}}}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\flatfrac}
% Provide a flat fraction.
%    \begin{macrocode}
\DeclarePairedDelimiterX{\hep@flatfrac}[2]{.}{.}{%
  \kern-\nulldelimiterspace#1\delimsize/%
  \hep@left@delim#2\kern-\nulldelimiterspace%
}
\NewDocumentCommand{\flatfrac}{somm}{%
  \mathinner{%
    \IfBooleanTF{#1}{%
      \hep@flatfrac*{#3}{#4}%
    }{%
      \IfNoValueTF{#2}{\hep@left@delim#3/\hep@left@delim#4%
      }{%
       \hep@flatfrac[#2]{#3}{#4}%
      }%
    }%
  }%
}
%    \end{macrocode}
% \end{macro}
%
% \subsubsection{Differentials and derivatives}
%
% \begin{macro}{\int}
% Redefine "\int".
%    \begin{macrocode}
% \let\hep@int\int
% \RenewDocumentCommand{\int}{oe{_^}}{%
%   \def\temp{\hep@int_{\IfValueT{#2}{#2}}^{\IfValueT{#3}{#3}}}%
%   \IfValueTF{#1}{\mathop{\temp#1}}{\temp}%
% }
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\differential}
% Define a generic differential "\differential".
%    \begin{macrocode}
\newcommand*{\differential}[1]{\mathop{}\!#1}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\newderivative}
% Define a generic derivative.
%    \begin{macrocode}
\newcommand*\newderivative[2]{
  \NewDocumentCommand{#1}{somse{^}}{%
    \IfBooleanTF{##4}{%
      \IfBooleanTF{##1}{\nicefrac}{\tfrac}%
    }{%
      \IfBooleanTF{##1}{\flatfrac}{\frac}%
    }{%
      \differential#2\IfValueT{##5}{^{##5\!}}\IfValueT{##2}{##2}%
    }{%
      \differential#2{{}##3}\IfValueT{##5}{^{##5}}%
    }%
  }
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\hep@order@clear}
% \begin{macro}{\hep@order@add}
% \begin{macro}{\hep@order@power}
% \begin{macro}{\hep@power}
% Collect the order of a partial derivative.
% Integer exponents are summed, other exponents are added symbolically in front of the sum of the integers, so that \eg the exponents $n$, $1$, and $2$ give $n+3$.
% "\hep@order@power" prints the total order as superscript and "\hep@power"\marg{exponent} a single exponent, both only if they differ from one.
%    \begin{macrocode}
\ExplSyntaxOn
\tl_new:N \l__hep_order_tl
\int_new:N \l__hep_order_int
\regex_const:Nn \c__hep_integer_regex { \A \s* [\+\-]? \s* \d+ \s* \Z }
\cs_new_protected:Npn \hep@order@clear {
  \tl_clear:N \l__hep_order_tl
  \int_zero:N \l__hep_order_int
}
\cs_new_protected:Npn \hep@order@add #1 {
  \regex_match:NnTF \c__hep_integer_regex {#1} {
    \int_add:Nn \l__hep_order_int {#1}
  } {
    \tl_if_empty:NF \l__hep_order_tl
      { \tl_put_right:Nn \l__hep_order_tl { + } }
    \tl_put_right:Nn \l__hep_order_tl {#1}
  }
}
\cs_new_protected:Npn \hep@order@power {
  \tl_if_empty:NTF \l__hep_order_tl {
    \int_compare:nNnF \l__hep_order_int = 1
      { { ^ { \int_use:N \l__hep_order_int \! } } }
  } {
    { ^ {
      \l__hep_order_tl
      \int_compare:nNnT \l__hep_order_int > 0 { + }
      \int_compare:nNnF \l__hep_order_int = 0
        { \int_use:N \l__hep_order_int }
      \!
    } }
  }
}
\cs_new_protected:Npn \hep@power #1 {
  \regex_match:NnTF \c__hep_integer_regex {#1} {
    \int_compare:nNnF {#1} = 1 { { ^ {#1} } }
  } {
    { ^ {#1} }
  }
}
\ExplSyntaxOff
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\newpartialderivative}
% Define a generic partial derivative
%    \begin{macrocode}
\newcommand*\newpartialderivative[2]{%
  \NewDocumentCommand{#1}{somsE{^}{1}oE{^}{1}oE{^}{1}}{%
    \hep@order@clear
    \hep@order@add{##5}%
    \IfValueT{##6}{\hep@order@add{##7}}%
    \IfValueT{##8}{\hep@order@add{##9}}%
    \IfBooleanTF{##4}{%
      \IfBooleanTF{##1}{\nicefrac}{\tfrac}%
    }{%
      \IfBooleanTF{##1}{\flatfrac}{\frac}%
    }{%
      \differential#2\hep@order@power
      \IfValueT{##2}{##2}%
    }{%
      \differential#2{{}##3}\hep@power{##5}%
      \IfValueT{##6}{#2##6\hep@power{##7}}%
      \IfValueT{##8}{#2##8\hep@power{##9}}%
    }%
  }%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\diffsymbol}
% \begin{macro}{\diff}
% \begin{macro}{\d}
% \begin{macro}{\derivative}
% \begin{macro}{\dv}
% Define the differential "\d" and the usual derivative.
%    \begin{macrocode}
\providecommand*{\diffsymbol}{d}
\newcommand*{\diff}{\differential\diffsymbol}
\hep@mathdef@default{\d}{\diff}
\newderivative{\derivative}{\diffsymbol}
\newcommand*\dv{\derivative}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\partialdifferential}
% \begin{macro}{\pd}
% \begin{macro}{\partialderivative}
% \begin{macro}{\pdv}
% Define the partial differential and derivative.
%    \begin{macrocode}
\newcommand*\partialdifferential{\differential\partial}
\newcommand*\slashedpartialdifferential{\differential{\slashed\partial}}
\newcommand*\spd{\slashedpartialdifferential}
\newcommand*\pd{\partialdifferential}
\newpartialderivative{\partialderivative}{\partial}
\newcommand*\pdv{\partialderivative}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\gaugediffsymbol}
% \begin{macro}{\gaugediff}
% \begin{macro}{\D}
% Define the gauge covariant differential "\D".
%    \begin{macrocode}
\providecommand*{\gaugediffsymbol}{D}
\newcommand*{\gaugediff}{\differential\gaugediffsymbol}
\newcommand*{\D}{\gaugediff}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\covariantdiff}
% \begin{macro}{\cd}
% Define the covariant differential "\cd".
%    \begin{macrocode}
\newcommand*{\covariantdiff}{\differential\nabla}
\newcommand*{\cd}{\covariantdiff}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\variation}
% \begin{macro}{\var}
% \begin{macro}{\functionalderivative}
% \begin{macro}{\fdv}
% Define the functional variation and derivative.
%    \begin{macrocode}
\newcommand*\variation{\differential\delta}
\newcommand*\var{\variation}
\newpartialderivative{\functionalderivative}{\delta}
\newcommand*\fdv{\functionalderivative}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\cancel}
% \begin{macro}{\slashed}
% Load the \software{cancel} \cite{cancel} and \software{slashed} \cite{slashed} packages which provide the "\cancel" and "\slashed" macros.
% Make "\slashed" robust, so that it can be used in moving arguments.
%    \begin{macrocode}
\RequirePackage{cancel}
\RequirePackage{slashed}
\MakeRobust{\slashed}
\declareslashed{}{/}{.14}{0}{L}
\declareslashed{}{/}{.055}{0}{\partial}
\declareslashed{}{/}{.06}{0}{\gaugediff}
\declareslashed{}{/}{.055}{0}{\partialdifferential}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \subsection{Paired delimiters}
%
% \begin{macro}{\left}
% \begin{macro}{\right}
% Load the \software{mleftright} package \cite{mleftright} and adjust the spacing around "\left" and "\right".
%    \begin{macrocode}
\RequirePackage{mleftright}
\mleftright
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\noargumentsymbol}
% \begin{macro}{\optionalargument}
% Allow for macros to have an empty argument using the \software{etoolbox} package \cite{etoolbox}.
%    \begin{macrocode}
\RequirePackage{etoolbox}
\newcommand*{\noargumentsymbol}{\:\cdot\:}
\newcommand*{\optionalargument}[1]{\ifblank{#1}{\noargumentsymbol}{#1}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\abs}
% \begin{macro}{\norm}
% Absolute value and norm.
%    \begin{macrocode}
\DeclarePairedDelimiterX\abs[1]\lvert\rvert{\optionalargument{#1}}
\DeclarePairedDelimiterX\hep@norm[1]\lVert\rVert{\optionalargument{#1}}
\DeclarePairedDelimiterXPP\hep@pnorm[2]{}\lVert\rVert{_{#1}}{#2}
\NewDocumentCommand{\norm}{som}{%
  \IfValueTF{#2}{%
    \IfBooleanTF{#1}{\hep@pnorm*}{\hep@pnorm}{#2}%
  }{%
    \IfBooleanTF{#1}{\hep@norm*}{\hep@norm}%
  }{\optionalargument{#3}}%
}
%    \end{macrocode}
% \end{macro}
% \end{macro}

% \begin{macro}{\floor}
% \begin{macro}{\ceil}
% Floor and ceiling paired delimiters.
%    \begin{macrocode}
\DeclarePairedDelimiter\ceil{\lceil}{\rceil}
\DeclarePairedDelimiter\floor{\lfloor}{\rfloor}
%    \end{macrocode}
% \end{macro}
% \end{macro}

% \begin{macro}{\ordersymbol}
% \begin{macro}{\order}
% Order symbol and macro.
%    \begin{macrocode}
\providecommand*{\ordersymbol}{\mathcal{O}}
\DeclarePairedDelimiterXPP\order[1]{\ordersymbol}(){}{#1}
%    \end{macrocode}
% \end{macro}
% \end{macro}

% \begin{macro}{\evaluated}
% \begin{macro}{\eval}
% Vertical evaluation bar
%    \begin{macrocode}
\DeclarePairedDelimiter{\hep@evaluated}{.}{\rvert}
\NewDocumentCommand{\evaluated}{som}{%
  \IfBooleanTF{#1}{%
    \hep@evaluated*{#3}%
  }{%
    \IfNoValueTF{#2}{#3\rvert}{\hep@evaluated[#2]{#3}}%
  }%
}
\newcommand*\eval{\evaluated}
%    \end{macrocode}
% \end{macro}
% \end{macro}

% \begin{macro}{\row}
% \begin{macro}{\column}
% Shortcuts for rows and columns
%    \begin{macrocode}
\newcommand*{\rowseperator}{,\,}
\ExplSyntaxOn
\seq_new:N \hep@seq
\newcommand*{\hep@row}[1]{
 \seq_set_split:Nnn\hep@seq{,}{#1}
 \begin{matrix}\seq_use:Nn\hep@seq{\rowseperator}\end{matrix}
}
\newcommand*{\hep@column}[1]{%
 \seq_set_split:Nnn\hep@seq{,}{#1}%
 \begin{matrix}\seq_use:Nn\hep@seq{\\}\end{matrix}%
}
\ExplSyntaxOff
\DeclarePairedDelimiterX{\hep@row@}[1]{(}{)}{\hep@row{#1}}
\NewDocumentCommand{\hep@column@}{me{^}e{_}}{%
  \left(\hep@column{#1}\right)%
  \IfValueT{#2}{^{\!\!\!#2}}\IfValueT{#3}{_{\!\!\!#3}}%
}
\providecommand*{\column}{}
\mathdef{\column}{\hep@column@}
\providecommand*{\row}{}
\mathdef{\row}{\hep@row@}
%    \end{macrocode}
% \end{macro}
% \end{macro}

% \subsubsection{Set and Probability}
%
% \begin{macro}{\midbar}
% Define a generic midbar.
%    \begin{macrocode}
\newcommand*\hep@left@delim{\mathopen{}}
\providecommand*{\midbar}[1][]{%
  \nonscript\:#1\vert\allowbreak\nonscript\:\hep@left@delim%
}
%    \end{macrocode}
% \end{macro}

% \begin{macro}{\suchthat}
% \begin{macro}{\set}
% Define a "\set" macro that allows a midbar via "\suchthat".
%    \begin{macrocode}
\providecommand*\suchthat{\midbar}
\DeclarePairedDelimiterX\set[1]\{\}{%
  \renewcommand*\suchthat{\midbar[\delimsize]}#1%
}
%    \end{macrocode}
% \end{macro}
% \end{macro}

% \begin{macro}{\probabilitysymbol}
% \begin{macro}{\given}
% \begin{macro}{\Pr}
% Redefine the "\Pr" macro to a macro that takes a "\given" macro and generates a midbar.
%    \begin{macrocode}
\providecommand*{\probabilitysymbol}{\operatorname{Pr}}
\providecommand*\given{\midbar}
\DeclarePairedDelimiterXPP\hep@Pr[1]{%
  \probabilitysymbol}(){}{%
  \renewcommand*\given{\midbar[\delimsize]}#1%
}
\let\Pr\relax
\NewDocumentCommand{\Pr}{so}{%
  \IfValueTF{#2}{%
    \IfBooleanTF{#1}{\hep@Pr*}{\hep@Pr}{#2}%
  }{%
    \probabilitysymbol%
  }%
}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}

% \subsubsection{Commutators}
%
% \begin{macro}{\newpair}
% Define the "\newpair" macro that generates pairs surrounded by brackets.
%    \begin{macrocode}
\NewDocumentCommand{\newpair}{mmme{_}e{^}}{%
  \IfNoValueTF{#4}{%
    \IfNoValueTF{#5}{%
      \DeclarePairedDelimiterX{#1}[2]{#2}{#3}%
    }{%
      \DeclarePairedDelimiterXPP{#1}[2]{}{#2}{#3}{^{#5}}%
    }%
  }{%
    \DeclarePairedDelimiterXPP{#1}[2]{}{#2}{#3}{_{#4}}%
  }{%
    \optionalargument{##1},\optionalargument{##2}%
  }%
}
%    \end{macrocode}
%\end{macro}
%
% \begin{macro}{\innerproduct}
% \begin{macro}{\poissonbracket}
% \begin{macro}{\pb}
% \begin{macro}{\commutator}
% \begin{macro}{\comm}
% \begin{macro}{\acomm}
% Poissonbracket, commutator and anti-commutator.
%    \begin{macrocode}
\newpair\innerproduct\langle\rangle
\newpair\poissonbracket\lbrace\rbrace
\newpair\commutator\lbrack\rbrack
\newcommand*\pb{\poissonbracket}
\newcommand*\comm{\commutator}
\newcommand*\acomm{\poissonbracket}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \subsubsection{Bra-ket notation}
%
% \begin{macro}{\braketspace}
% Define the space within braket notation.
%    \begin{macrocode}
% \providecommand*\braketspace{\mskip1mu}
\providecommand*\braketouterspace{\mskip1mu}
\providecommand*\braketinnerspace{\mskip2mu}
\newcommand*\hep@midvert{%
  \braketinnerspace\delimsize\vert\braketinnerspace\hep@left@delim%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\braket}
% Define the braket macro.
%    \begin{macrocode}
\DeclarePairedDelimiterX\braket[2]{\langle}{\rangle}{%
  \braketouterspace#1\hep@midvert#2\braketouterspace%
}
%    \end{macrocode}
% \end{macro}

% \begin{macro}{\bra}
% Define the bra macro.
%    \begin{macrocode}
\DeclarePairedDelimiterXPP\hep@bra[1]{%
  }{\langle}{\rvert}{\braketinnerspace%
  }{\braketouterspace#1\braketinnerspace%
}
\NewDocumentCommand{\bra}{smt\ket sgt\ketbra sgg}{%
  \IfBooleanTF{#6}{%
    \IfBooleanTF{#1}{\braket*{#2}{#8}}{\braket{#2}{#8}}%
    \IfBooleanTF{#7}{\bra*{#9}}{\bra{#9}}%
  }{
    \IfBooleanTF{#3}{%
      \IfBooleanTF{#1}{\braket*}{%
        \IfBooleanTF{#4}{\braket*}{\braket}}{#2}{#5%
      }%
    }{%
      \IfBooleanTF{#1}{\hep@bra*}{\hep@bra}{#2}%
    }%
  }%
}
%    \end{macrocode}
% \end{macro}

% \begin{macro}{\ket}
% Define the ket macro.
%    \begin{macrocode}
\DeclarePairedDelimiterXPP\ket[1]{%
  \braketinnerspace}{\lvert}{\rangle}{%
}{%
  \braketinnerspace\hep@left@delim#1\braketouterspace%
}
%    \end{macrocode}
% \end{macro}

% \begin{macro}{\ketbra}
% Define the ketbra macro.
%    \begin{macrocode}
\NewDocumentCommand{\ketbra}{smm}{%
  \IfBooleanTF{#1}{%
    \ket*{#2}\bra*{#3}%
  }{%
    \ket{#2}\bra{#3}%
  }%
}
%    \end{macrocode}
% \end{macro}

% \begin{macro}{\matrixelement}
% \begin{macro}{\mel}
% Define the matrixelement macro.
%    \begin{macrocode}
\DeclarePairedDelimiterX\matrixelement[3]{%
  \langle}{\rangle
}{%
  \braketouterspace#1\hep@midvert#2\hep@midvert#3\braketouterspace%
}
\newcommand*\matrixel{\matrixelement}
\newcommand*\mel{\matrixelement}
%    \end{macrocode}
% \end{macro}
% \end{macro}

% \begin{macro}{\expectationvalue}
% \begin{macro}{\ev}
% \begin{macro}{\vev}
% Define the expectationvalue and vev macros.
%    \begin{macrocode}
\DeclarePairedDelimiterX\hep@expvalue[1]{\langle}{\rangle}{%
  \braketouterspace#1\braketouterspace%
}
\NewDocumentCommand{\expectationvalue}{som}{%
  \IfNoValueTF{#2}{%
    \IfBooleanTF{#1}{\hep@expvalue*}{\hep@expvalue}{#3}%
  }{%
    \IfBooleanTF{#1}{\matrixelement*}{\matrixelement}{#2}{#3}{#2}%
  }%
}
\newcommand*\ev{\expectationvalue}
\newcommand*\vev[1]{\expectationvalue[0]{#1}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \subsection{PDF strings}
%
% \begin{macro}{\hep@mathpdf@ifkeyval}
% Expandable test whether the optional argument of "\unit" is a key--value list.
%    \begin{macrocode}
\newcommand*{\hep@mathpdf@ifkeyval}[1]{%
  \hep@mathpdf@@ifkeyval#1=\hep@mathpdf@stop
}
\def\hep@mathpdf@@ifkeyval#1=#2\hep@mathpdf@stop{%
  \if\relax\detokenize{#2}\relax
    \expandafter\@secondoftwo
  \else
    \expandafter\@firstoftwo
  \fi
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\hep@mathpdf@unprotect}
% The operators of \software{amsmath} are protected, so that they would vanish from PDF strings.
% Replace them by unprotected copies, if they still are operators.
%    \begin{macrocode}
\newcommand*{\hep@mathpdf@unprotect}[1]{%
  \expandafter\hep@mathpdf@@unprotect#1\hep@mathpdf@stop#1%
}
\def\hep@mathpdf@@unprotect#1#2\hep@mathpdf@stop#3{%
  \ifx\qopname#1\def#3{#1#2}\fi
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\hep@mathpdf@definitions}
% Define the PDF-string versions of the macros, \eg for bookmarks.
% The imaginary unit and the differential become i and d, overlines, slashes, and arrow accents keep only their base, and vectors are written as parentheses.
% Operators keep their name followed by a space, the probability "\Pr" keeps its brackets, transposes and inverses become a circumflex, fractions become flat, and "\unit"\oarg{value}\marg{unit} keeps its value.
% The PDF-string version of "\unit" from \software{siunitx} is copied at each use, since \software{siunitx} registers it at the beginning of the document.
%    \begin{macrocode}
\newcommand*{\hep@mathpdf@definitions}{%
  \@tfor\hep@mathpdf@op:=\arcsin\arg\cosh\coth\deg\dim\exp\gcd\hom\inf
    \ker\lg\lim\ln\log\max\min\sin\sinh\sup\tanh
    \do{\expandafter\hep@mathpdf@unprotect\hep@mathpdf@op}%
  \def\liminf{lim inf }%
  \def\limsup{lim sup }%
  \def\i{i}%
  \def\d{d}%
  \let\overline\@firstofone
  \let\widebar\@firstofone
  \let\slashed\@firstofone
  \RenewExpandableDocumentCommand{\oset}{omm}{##3}%
  \def\column##1{(##1)}%
  \def\row##1{(##1)}%
  \def\transpose{\textasciicircum T}%
  \let\trans\transpose
  \def\qopname##1##2##3{##3 }%
  \RenewExpandableDocumentCommand{\operatorname}{sm}{##2}%
  \let\hep@trig@strut\@empty
  \def\Pr{Pr}%
  \def\given{|}%
  \def\hep@Re{Re}%
  \def\hep@Im{Im}%
  \RenewExpandableDocumentCommand{\inv}{O{1}m}{%
    ##2\textasciicircum-##1%
  }%
  \RenewExpandableDocumentCommand{\nicefrac}{omom}{##2/##4}%
  \def\textfrac##1##2{##1/##2}%
  \RenewExpandableDocumentCommand{\flatfrac}{somm}{##3/##4}%
  \DeclareCommandCopy{\hep@mathpdf@unit}{\unit}%
  \DeclareCommandCopy{\hep@mathpdf@qty}{\qty}%
  \RenewExpandableDocumentCommand{\unit}{om}{%
    \IfNoValueTF{##1}{\hep@mathpdf@unit{##2}}{%
      \hep@mathpdf@ifkeyval{##1}%
        {\hep@mathpdf@unit[##1]{##2}}{\hep@mathpdf@qty{##1}{##2}}%
    }%
  }%
  \RenewExpandableDocumentCommand{\unitfrac}{omm}{%
    \IfNoValueTF{##1}%
      {\hep@mathpdf@unit{##2\per##3}}{\hep@mathpdf@qty{##1}{##2\per##3}}%
  }%
}
%    \end{macrocode}
% \end{macro}
%
% Register the PDF-string definitions if \software{hyperref} is loaded, before or after this package.
% This happens at the end of "\begin{document}", after \software{siunitx} has registered its own definitions.
%    \begin{macrocode}
\AddToHook{begindocument/end}{%
  \@ifpackageloaded{hyperref}{%
    \pdfstringdefDisableCommands{\hep@mathpdf@definitions}%
  }{}%
}
%    \end{macrocode}
%
%</package>
%
% \section{Test}
%
%<*test>
%
%    \begin{macrocode}
\documentclass{article}

\usepackage{hep-math}

\begin{document}

\begin{gather}
  \bra{x}\ket{y}
  \braket*{x}{y}\\
  \dv[f]{x}^3
  \pdv[f]{x}[y]^2[z]^3
  \fdv[f]{x}^3[y]\\
  \set{x \suchthat x \in X}
\end{gather}

\end{document}

%    \end{macrocode}
%</test>
%
% \section{Readme}
%
%<*readme>
%
%    \begin{macrocode}
# The `hep-math` package

Math macros for operators, derivatives, delimiters, bra-ket notation
and expectation values

## Introduction

The `hep-math` package extends `mathtools` and `amsmath` with
HEP-oriented math notation. It provides math-only command definitions,
improved overlines and arrow accents, operator names, fractions and unit
helpers, differentials and derivative builders, paired delimiters,
probabilities, brackets, quantum-mechanical bra-ket notation, matrix
elements, and expectation values.

To use the package place `\usepackage{hep-math}` in the preamble.

## Author

Jan Hajer

## License

This file may be distributed and/or modified under the conditions of the
`LaTeX` Project Public License, either version 1.3c of this license or
(at your option) any later version. The latest version of this license is
in `http://www.latex-project.org/lppl.txt` and version 1.3c or later is
part of all distributions of LaTeX version 2005/12/01 or later.
%    \end{macrocode}
%
%</readme>
%
% \Finale

\endinput

% \PrintIndex
% makeindex -s gglo.ist -o hep-math-implementation.gls hep-math-implementation.glo
% makeindex -s gglo.ist -o hep-math-implementation.ind hep-math-implementation.idx
