% !TeX TXS-program:compile = txs:///arara/[-v]
% arara: lualatex: { synctex:yes, interaction:nonstopmode }
% arara: makeindex
% arara: lualatex: { synctex:yes, interaction:nonstopmode } if found('log', 'Rerun to get')
\RequirePackage{pdfmanagement}
\SetKeys[document/metadata]{lang=en-US}
\PassOptionsToPackage{hyperindex}{hyperref}
\PassOptionsToPackage{dvipsnames}{xcolor}
\documentclass{ltxdoc}
\usepackage{geometry}
\geometry{margin=1.5in}
\usepackage{tcolorbox}
\PassOptionsToPackage{cachedir=keythms-doc-minted}{minted}
\tcbuselibrary{documentation,minted,breakable,hooks}

\usepackage{fontspec}
\setmainfont{NewCM10-Book.otf}[
  IgnoreFontspecFile,
    % Copied from NewCM-Book.fontspec
    % Needed to change BoldFont to LM demibold
    UprightFont={NewCM10-Book.otf},%
    UprightFeatures={%
      SizeFeatures={%
        {%
          Size={-8},%
          Font={NewCM08-Book.otf}%
        },%
        {%
          Size={8-},%
          Font={NewCM10-Book.otf}%
        }%
      }%
    },%
    ItalicFont={NewCM10-BookItalic.otf},%
    ItalicFeatures={%
      SizeFeatures={%
        {%
          Size={-8},%
          Font={NewCM08-BookItalic.otf}%
        },%
        {%
          Size={8-},%
          Font={NewCM10-BookItalic.otf}%
        }%
      }%
    },%
    BoldFont={lmromandemi10-regular.otf},%
    BoldFeatures={%
      SizeFeatures={%
        {%
          Size={0-},%
          Font={lmromandemi10-regular.otf}%
        }%
      }%
    },%
    BoldItalicFont={NewCM10-BoldItalic.otf},%
    BoldItalicFeatures={%
      SizeFeatures={%
        {%
          Size={0-},%
          Font={NewCM10-BoldItalic.otf}%
        }%
      }%
    },%
    SlantedFont={NewCM10-Book.otf},%
    SlantedFeatures={%
      SizeFeatures={%
        {%
          Size={-8},%
          Font={NewCM08-Book.otf}%
        },%
        {%
          Size={8-},%
          Font={NewCM10-Book.otf}%
        }%
      }%
    },%
    BoldSlantedFont={lmromandemi10-oblique.otf},%
    BoldSlantedFeatures={%
      SizeFeatures={%
        {%
          Size={0-},%
          Font={lmromandemi10-oblique.otf}%
        }%
      }%
    },%
    SwashFont={NewCM10-Book.otf},%
    SwashFeatures={%
      SizeFeatures={%
        {%
          Size={-8},%
          Font={NewCM08-Book.otf}%
        },%
        {%
          Size={8-},%
          Font={NewCM10-Book.otf}%
        }%
      }%
    },%
    BoldSwashFont={NewCM10-Bold.otf},%
    BoldSwashFeatures={%
      SizeFeatures={%
        {%
          Size={0-},%
          Font={NewCM10-Bold.otf}%
        }%
      }%
    }%
  ]
\setsansfont{NewCMSans10-Book.otf}
\setmonofont{NewCMMono10-Book.otf}
\usepackage{lum-newcomputermodern}

\usetikzlibrary{cd}
\usepackage{fontawesome5}
\usepackage{longtable}
\usepackage{booktabs}
\usepackage{keytheorems}
\usepackage{zref-clever}
\zcsetup{nameinlink=false}

\makeatletter
\newcommand\keythmsversion{\@keythms@version}
\makeatother

\title{%
  The \pkg{keytheorems} package \\[1ex]
  \large version \keythmsversion \\[1ex]
  \href{https://github.com/mbertucci47/keytheorems}
    {\texttt{github.com/mbertucci47/keytheorems}}
  }
\author{Matthew Bertucci}

\hypersetup{
  pdftitle={keytheorems package},
  pdfauthor={Matthew Bertucci},
  }

\counterwithin{equation}{section}
\keytheoremset{restate-counters={section}}

\newkeytheoremstyle{breaksty}{break}
\newkeytheorem{theorem}
\newkeytheorem{mythm}[name=Some Name]
\newkeytheorem{theorem*}[name=Theorem,numbered=false]
\newkeytheorem{conjecture}[parent=section]
\newkeytheorem{lemma}[sibling=theorem]
\newkeytheorem{test}[
  preheadhook=PREHEAD,
  postheadhook=POSTHEAD,
  prefoothook=PREFOOT,
  postfoothook=POSTFOOT
]
\newkeytheorem{prop}[
  name=Proposition,
  refname={proposition,propositions},
  Refname={Proposition,Propositions}
  ]
\newkeytheorem{example}[qed]
\newkeytheorem{solution}[qed=$\clubsuit$]
\newkeytheorem{remark}[style=remark]
\tcbset{
  defstyle/.style={arc=0mm,colback=blue!5!white,colframe=blue!75!black},
  thmstyle/.style={colback=green!5,colframe=green!35!black},
  }
\newkeytheoremstyle{tcb-standard}{
  tcolorbox=thmstyle,
  headpunct={},
  notebraces={}{},
  noteseparator={: },
  notefont=\bfseries,
  bodyfont=\normalfont,
  }
\newkeytheorem{mytheo}[name=Theorem,style=tcb-standard]
\newkeytheorem{corollary}[tcolorbox]
\newkeytheorem{definition}[
  style=definition,
  tcolorbox={defstyle}
  ]
\newkeytheorem{boxcor}[
  tcolorbox-no-titlebar={colback=red!10},
  name=Corollary,
  sibling=corollary,
  ]
\newkeytheorem{observation}[style=breaksty]
\newkeytheorem{quotethm}[name=Quote Theorem,margin=1cm]
\newkeytheorem{indentedthm}[name=Indented Theorem,leftmargin=1cm]
\newkeytheorem{mainthm}[
  name=Theorem,
  counter-format=\Alph*,
  ]
\newkeytheoremstyle{marginstyle}{headformat=margin}
\newkeytheoremstyle{swapnumberstyle}{headformat=swapnumber}
\newkeytheorem{marginthm}[name=Margin Theorem,style=marginstyle]
\newkeytheorem{swapnumberthm}[name=Swapnumber Theorem,style=swapnumberstyle]

\MakeShortVerb{\|}
\newcommand{\env}{\texttt}
\newcommand{\hook}{\texttt}
\NewCommandCopy{\braces}{\brackets}
\newcommand{\bracks}[1]{\texttt{[#1]}}
\newcommand{\ttbraces}[1]{\braces{\texttt{#1}}}
%\tcbset{index gather commands=false}
\usepackage{xcolor-solarized}
\colorlet{ExampleBack}{solarized-base3!50}
\colorlet{ExampleBackLower}{solarized-base3}
\tcbset{
  color command=BrickRed,
  color key=Fuchsia,
  color value=teal,
  before doc body={%
    \setlength{\parindent}{15pt}
    \noindent
    },
  docexample/.append style={boxrule=0pt,arc=0pt,after app={\noindent}}
  }
  
\makeatletter % code from muzimuzhi (https://github.com/T-F-S/tcolorbox/issues/298)
\tcbset{
  before verbatim write app/.code={%
    \appto\tcb@verbatim@begin@hook{\tcb@iow@write{#1}}},
  % provided for symmetry, but not used
  after verbatim write pre/.code={%
    \preto\tcb@verbatim@end@hook{\tcb@iow@write{#1}}},
}
\tcbset{
  mark preamble/.style={
    before verbatim write app={\@percentchar\space preamble},
  },
  mark document/.style={
    before verbatim write app={\@percentchar\space document},
  },
}
\tcbset{
  listing engine=minted,
  minted language=latex,
  withpreamble/.style = {
    mark document,
    before upper = {%
      % affects both the \tcbsettemplisting and the original upper
      \setminted{listparameters={\topsep=0pt \partopsep=0pt}}%
      \tcbusetemplisting
      \vspace{5pt}%
    }
  }
}
\NewDocumentEnvironment{codepreamble}{}{%
  \tcbset{mark preamble}%
  \tcbwritetemp
}{%
  \endtcbwritetemp
}
\makeatother

\NewTCBListing{keythmscode}{ !O{} }
  {
    colback=ExampleBack,
    arc=0pt,
    boxrule=0pt,
    skin=bicolor,
    colbacklower=ExampleBackLower,
    breakable,
    parbox=false, % so examples match document with indent, etc.
    minted options app={breaksymbolleft={}},
    #1
  }
\newtcolorbox{notebox}[1][]{enhanced,
  before skip balanced=2mm,after skip balanced=4mm,
  boxrule=0.4pt,left=5mm,right=2mm,top=1mm,bottom=1mm,
  colback=red!20,
  colframe=red!40!black,
  sharp corners,rounded corners=southeast,arc is angular,arc=3mm,
  underlay={%
    \path[fill=tcbcolback!80!black] ([yshift=3mm]interior.south east)--++(-0.4,-0.1)--++(0.1,-0.2);
    \path[draw=tcbcolframe,shorten <=-0.05mm,shorten >=-0.05mm] ([yshift=3mm]interior.south east)--++(-0.4,-0.1)--++(0.1,-0.2);
    \path[fill=red!40!black,draw=none] (interior.south west) rectangle node[white]{\LARGE\bfseries !} ([xshift=4mm]interior.north west);
    },
  drop fuzzy shadow,#1}
\makeatletter
% allow for optional argument specifying printed text, mostly for starred keys
\RenewDocumentCommand\tcb@ref@doc{msom}{%
  \hyperref[{#1:#4}]{%
  \IfValueTF{#3}{\texttt{#3}}{\texttt{\ref*{#1:#4}}}%
  \IfBooleanTF{#2}{}{%
    \ifnum\getpagerefnumber{#1:#4}=\thepage\relax%
    \else%
      \kvtcb@doc@format@page{{\fontfamily{pzd}\fontencoding{U}\fontseries{m}\fontshape{n}\selectfont\char213}%
      \,\kvtcb@text@pageshort\,\pageref*{#1:#4}}%
    \fi}}%
}
\newcommand{\TCBdescnewline}{%
  \def\tcb@doc@do@description{%
    \ifx\kvtcb@doc@description\@empty\else\tcblower\raggedleft\strut
    \\[1ex]% added
    (\kvtcb@doc@description)\strut\fi%
  }%
}
\makeatother
\makeindex

\begin{document}

\maketitle

\begin{abstract}
An \pkg{expl3}-implementation of a key-value interface to \pkg{amsthm}, implementing most of the functionality provided by \pkg{thmtools}.
Several issues encountered with \pkg{thmtools} are avoided (see the README for a list) and a few new features are added.
\end{abstract}

\begingroup
\hypersetup{linkcolor=black}
\tableofcontents
\endgroup

\section{Dependencies}

The package depends on the \pkg{amsthm}, \pkg{refcount}, and \pkg{translations} packages.
The \refKey{tcolorbox} and \refKey{tcolorbox-no-titlebar} keys require \pkg{tcolorbox}, and the \refKey[numbered=unless-unique]{numbered} key requires the \pkg{unique} package.
A \LaTeX{} kernel no older than 2025-06-01 is required.
    
\section{Global options}

\begin{docCommand}{keytheoremset}
  {\marg{options}}
Every key in this section can be given as an option to \cs{usepackage} or in \cs{keytheoremset}, with the exception that \refKey{continues-code} can only be used in the latter.
\end{docCommand}

\subsection{Compatibility options}

\begin{docKey}{overload}
  {}
  {initially unset}
Redefines \cs{newtheorem} to internally use the \pkg{keytheorems} machinery.
The syntax remains the same.
This is automatically set by \refKey{thmtools-compat}.
\end{docKey}

\begin{docKey}{thmtools-compat}
  {}
  {initially unset}
For compatibility with \pkg{thmtools} syntax.
For most documents,
\begin{dispListing}
\usepackage[thmtools-compat]{keytheorems}
\end{dispListing}
should be a drop-in replacement for \cs{usepackage}\ttbraces{amsthm,thmtools}.
The option defines the commands in the left column below.
The right column lists the corresponding \pkg{keytheorems} replacement that should be used in new documents.
\begin{longtable}{rcl}
\multicolumn{1}{c}{\pkg{thmtools} command} & & \multicolumn{1}{c}{\pkg{keytheorems} replacement} \\
\toprule
\docAuxCommand*{declaretheorem} & \textrightarrow & \refCom{newkeytheorem} \\
\docAuxCommand*{declaretheoremstyle} & \textrightarrow & \refCom{newkeytheoremstyle} \\
\docAuxCommand*{listoftheorems} & \textrightarrow & \refCom{listofkeytheorems} \\
\docAuxCommand*{listtheoremname} & \textrightarrow & \refKey{title} key \\
\begin{tabular}{r@{}}
\docAuxCommand*{addtotheorempreheadhook}\\
\docAuxCommand*{addtotheorempostheadhook}\\
\docAuxCommand*{addtotheoremprefoothook}\\
\docAuxCommand*{addtotheorempostfoothook}\\
\end{tabular} & \textrightarrow & \refCom{addtotheoremhook} \\
\docAuxEnvironment*{restatable} environment & \textrightarrow & \refKey{store} key \\
\docAuxEnvironment*{restatable*} environment & \textrightarrow & \refKey[store*]{store} key
\end{longtable}
Also defined are the \docAuxKey*{shaded} and \docAuxKey*{thmbox} keys, implemented internally with \pkg{tcolorbox} rather than the \pkg{shadethm} and \pkg{thmbox} packages, respectively.
\end{docKey}

\subsection{Other global options}

\begin{docKey}{auto-translate}
  {\colOpt{=true\textbar false}}
  {default |true|, initially |true|}
If |false|, \pkg{keytheorems} does not automatically translate the title text used for \refCom{listofkeytheorems} and the note produced by the \refKey{continues} key.
These texts can be manually customized with the \refKey{title} and \refKey{continues-code} keys, respectively.
\end{docKey}

\begin{docKey}[][before upper=\TCBdescnewline]{continues-code}
  {=\meta{code with \textup{\texttt{\#1}}}}
  {initially \cs{GetTranslation}\ttbraces{keythms\string_continues}\cs{pageref}\ttbraces{\#1}}
The code used to typeset the note produced by the \refKey{continues} key.
If English or an unknown language is used, defaults to \texttt{continuing from p.}\cs{,}\cs{pageref}\ttbraces{\#1}.
Currently (likely inaccurate!) translations exist for several European languages.
\end{docKey}

\begin{docKey}{predefined}
  {\colOpt{=\marg{options}}}
  {initially unset}
This is a convenience key, similar to \pkg{ntheorem}'s |standard| option, that predefines a set of theorems that, unless \refKey{auto-translate} is set to |false|, are translated into the current language if translations exist.
The predefined theorems are
\begin{itemize}
  \item |plain| style: \docAuxEnvironment{conjecture}, \docAuxEnvironment{corollary}, \docAuxEnvironment{lemma}, \docAuxEnvironment{proposition}, \docAuxEnvironment{theorem};
  \item |definition| style: \docAuxEnvironment{axiom}, \docAuxEnvironment{definition}, \docAuxEnvironment{example};
  \item |remark| style: \docAuxEnvironment{remark}.
\end{itemize}
If your language does not have translations, please feel free to open a GitHub pull request.

These theorems are provided at the end of the preamble (specifically, in the \hook{begindocument} hook) with \refCom{providekeytheorem} so will not overwrite user-defined environments with the same name.
By default, the predefined theorems share a counter and do not have a parent counter.
These settings can be changed by calling |siblings=false| (alias |sharenumbers=false|) and/or |parent=|\meta{counter}, respectively, in \meta{options}.

\begin{dispListing}
\usepackage[
  predefined={parent=section}
  ]{keytheorems}
  
% or equivalently
\usepackage{keytheorems}
\keytheoremset{predefined={parent=section}}
\end{dispListing}
\end{docKey}

\begin{docKey}{qed-symbol}
  {=\meta{symbol}}
  {initially \cs{openbox}}
Redefines \cs{qedsymbol} to be \meta{symbol}.
\end{docKey}

\begin{docKey}{restate-counters}
  {=\marg{comma-list of counters}}
  {initially \ttbraces{equation}}
Additional counters whose values are preserved when a theorem is restated.
This key does not reset the list, so you don't need to include |equation| in \meta{comma-list}.
\end{docKey}

\begin{docKey}{store-all}
  {}
  {initially unset}
Tells \pkg{keytheorems} to grab the body of each theorem so it can later be printed with the \refKey{print-body} option of \refCom{listofkeytheorems}.
Note that this means a theorem body \emph{cannot} contain verbatim material.
\end{docKey}

\begin{docKey}{store-sets-label}
  {}
  {initially unset}
Defines the \refKey{store} key to also set \refKey{label}, i.e., it makes |store=|\meta{tag} equivalent to |store=|\meta{tag}|,label=|\meta{tag}.
Similarly for \refKey[store*]{store}.
\end{docKey}

\section{Defining theorems}

\begin{docCommand}{newkeytheorem}
  {\marg{env name}\oarg{options}}
Defines a theorem environment \meta{env name} which itself takes a few options (see \autoref{in-doc-keys}).
You can also declare multiple theorems at once by replacing \meta{env name} with a comma-list of names, e.g.,
\begin{center}
\cs{newkeytheorem}\ttbraces{theorem,lemma,proposition}\bracks{\meta{options}}.
\end{center}

By default, the theorem's printed name is a title-cased \meta{env name}.
This can be changed with the \refKey{thm/name} key.
All \meta{options} are described in subsections \ref{thm-thmtools-keys} and \ref{thm-added-keys}.

\begin{codepreamble}
\newkeytheorem{theorem}
\end{codepreamble}

\begin{keythmscode}[withpreamble]
\begin{theorem}
There are infinitely many prime numbers.
\end{theorem}
\end{keythmscode}

\end{docCommand}

\begin{docCommands}[
  doc parameter=\marg{env name}\oarg{options}
  ]
  {
    {doc name = renewkeytheorem},
    {doc name = providekeytheorem},
    {doc name = declarekeytheorem},
  }
Sometimes a package or class defines theorems that need to be overwritten by the user.
For this case, \pkg{keytheorems} provides \cs{renewkeytheorem} which redefines \meta{env name} or errors if it is not defined.
For completeness, also provided are \cs{providekeytheorem} and \cs{declarekeytheorem}.
The former only defines \meta{env name} if it is not already defined; the latter always overwrites \meta{env name}.
\end{docCommands}

\subsection{Keys available to theorem environments} \label{in-doc-keys}

As in \pkg{amsthm}, theorems can take an optional argument that contains a note or heading.

\begin{keythmscode}
\begin{theorem}[Bertrand's postulate]
For every $n\geq 1$, there is a prime number $p$ with $n<p\leq 2n$.
\end{theorem}
\end{keythmscode}

Alternatively, the optional argument may contain any of the following keys.

\begin{docKey}{note}
  {=\meta{text}}
  {initially unset}
Alias \docAuxKey[][doc label=thmuse/name]{name}.
This is the key-value equivalent of the optional argument described above.
This syntax, however, allows the argument to contain other keys.

\begin{keythmscode}
\begin{theorem}[note=Legendre's formula]
The number $n!$ contains the prime factor $p$ exactly
  \[ \sum_{k\geq 1} \Bigl\lfloor\frac{n}{p^k}\Bigr\rfloor \]
times.
\end{theorem}
\end{keythmscode}

\end{docKey}

\begin{docKey}{short-note}
  {=\meta{text}}
  {initially unset}
Alias \docAuxKey{short-name}.
This replaces the value of \refKey{note} when displayed in the list of theorems (\refCom{listofkeytheorems}).
\end{docKey}

\begin{docKey}{label}
  {=\meta{label name}}
  {initially unset}
This is the key-value equivalent of |\begin{theorem}| \cs{label}\marg{label name}.

\begin{keythmscode}
\begin{theorem}[label=bezout,note=Bézout's identity]
Let $a$ and $b$ be integers. Then there exist integers $x$ and $y$ such that $ax+by=\gcd(a,b)$.
\end{theorem}
See \zcref{bezout}.
\end{keythmscode}

\end{docKey}

\begin{docKey}{manual-num}
  {=\meta{text}}
  {initially unset}
Use this to override the printed number of a theorem.
It is useful for making ``starred'' versions of other theorems, perhaps to represent a reformulated or more difficult version.

\begin{keythmscode}
\begin{theorem}[manual-num=\ref*{bezout}*]
Let $a_1,\dots,a_n$ be integers. Then there exist integers $x_1,\dots,x_n$ such that $a_1x_1+\dots+a_nx_n=\gcd(a_1,\dots,a_n)$.
\end{theorem}
\begin{theorem}[manual-num=\faRocket] % requires fontawesome5
Don't confuse your readers by changing the numbering without good reason.
\end{theorem}
\end{keythmscode}

\end{docKey}
\begin{docKey}{continues}
  {\sarg=\meta{label name}}
  {initially unset}
Pick up a theorem where you left off.
The theorem number remains the same.
The printed text can be customized with the \refKey{continues-code} option.
The starred version also copies the theorem \refKey{note} and \refKey{short-note} if they are nonempty.

\begin{keythmscode}
\begin{theorem}[continues=bezout]
Moreover, the integers of the form $az+bt$ are exactly the multiples of $\gcd(a,b)$.
\end{theorem}
\begin{theorem}[continues*=bezout]
Moreover, the integers of the form $az+bt$ are exactly the multiples of $\gcd(a,b)$.
\end{theorem}
\end{keythmscode}

\end{docKey}

\begin{docKey}{store}
  {\sarg=\meta{tag}}
  {initially unset}
Alias \docAuxKey{restate}\sarg.
Stores the the theorem to be restated at any point in the document with \refCom{getkeytheorem}.
With the starred version, counters and labels are taken from the copy called with \cs{getkeytheorem}, so in this case can only be restated once.
This allows you, for example, to write all theorems and proofs in the appendix and call \cs{getkeytheorem} at the appropriate time mid-document.
For the numbering to be correct, the unstarred key will need at most two runs and the starred key at most three runs.

\begin{keythmscode}
\begin{theorem}[store=blub]
A theorem worth restating.
\end{theorem}
More brilliant mathematics.
\getkeytheorem{blub}
\end{keythmscode}

A theorem given this key \emph{cannot} contain verbatim material or other unexpected catcodes such as a \pkg{tikz-cd} diagram.
The latter issue can be averted with the \texttt{ampersand-replacement} key.

\begin{codepreamble}
\usepackage{tikz}
\usetikzlibrary{cd}
\end{codepreamble}

\begin{keythmscode}[withpreamble]
\begin{lemma}[store=fiberprod]
For any $S$-schemes $X$ and $Y$, there exists a scheme $X\times_S Y$ with morphisms to $X$ and $Y$ such that the diagram
\[\begin{tikzcd}[ampersand replacement=\&]
    X\times_S Y \ar[r] \ar[d] \& X \ar[d] \\
    Y \ar[r] \& S
  \end{tikzcd}\]
commutes and is universal with respect to this property.
\end{lemma}
\dots
\getkeytheorem{fiberprod}
\end{keythmscode}

\end{docKey}

\begin{docKey}{restate-keys}
  {=\marg{list of keys}}
  {initially unset}
Allows passing different keys to the restated theorem.
At the moment this is only useful with the \refKey{note} key.

\begin{keythmscode}
\begin{theorem}[
  store=rktest,
  note=Original,
  restate-keys={note=Restated},
  ]
Wow, yet another theorem.
\end{theorem}
\getkeytheorem{rktest}
\end{keythmscode}

\end{docKey}

\begin{docKey}{listhack}
  {=\docValue*{true}\textbar\docValue*{false}}
  {initially |false|}
Meant only to be used with the \refKey{break} style key for a theorem starting with a list.
Compare:

\begin{codepreamble}
\newkeytheoremstyle{breaksty}{break}
\newkeytheorem{observation}[style=breaksty]
\end{codepreamble}

\begin{keythmscode}[withpreamble]
\begin{observation}
\begin{enumerate}
\item First item
\item Second item
\end{enumerate}
\end{observation}

\begin{observation}[listhack=true]
\begin{enumerate}
\item First item
\item Second item
\end{enumerate}
\end{observation}
\end{keythmscode}

Note that the value |true| must be explicitly set so that |listhack| is not interpreted as the note text.
\end{docKey}

\begin{docKey}[][doc label=thmuse/seq]{seq}
  {=\meta{name}}
  {initially unset}
Adds the theorem to a custom sequence \meta{name} that can then be listed with \cs{listofkeytheorems}\bracks{seq=\meta{name}}.
See \refKey{listof/seq} for more details.
\end{docKey}

\begin{docKey}{tcb-append}
  {=\marg{list of \pkg{tcolorbox} keys}}
  {initially unset}
Appends the given \pkg{tcolorbox} keys to the |keythms_tcb_|\meta{env name} style for theorems defined with the \refKey{tcolorbox} or \refKey{tcolorbox-no-titlebar} keys.
Note that it is not recommended to frequently change the appearance of theorems throughout a document so use this key sparingly.
\end{docKey}

\begin{docKey}[][doc label=thmuse/ignore]{ignore}
  {=\docValue*{true}\textbar\docValue*{false}}
  {initially |false|}
If set to |true|, the theorem is completely ignored.

\begin{keythmscode}
Some text.
\begin{theorem}[ignore=true]
A theorem I want to ignore.
\end{theorem}
Some more text.
\end{keythmscode}

\end{docKey}

\subsection{Keys also defined in \pkg{thmtools}} \label{thm-thmtools-keys}

These are the \oarg{options} available to \cs{newkeytheorem}.
Except for \refKey{thm/name} and \refKey{style}, each key below can also be used in \refCom{newkeytheoremstyle}.
For more description, see the \href{https://ctan.org/pkg/thmtools}{\pkg{thmtools}} package.

\begin{docKey}[][doc label=thm/name]{name}
  {=\meta{display name}}
  {initially title-cased \meta{env name}}
Aliases \docAuxKey{heading} and \docAuxKey{title}.
Sets the displayed name of the theorem.

\begin{codepreamble}
\newkeytheorem{mythm}[name=Some Name]
\end{codepreamble}

\begin{keythmscode}[withpreamble]
\begin{mythm}
Some text
\end{mythm}
\end{keythmscode}

\end{docKey}

\begin{docKey}{numbered}
  {=\docValue*{true}\textbar\docValue*{false}\textbar \docValue{unless-unique}}
  {default |true|, initially |true|}
Determines if the theorem is numbered.
With the value |unless-unique|, there are two cases.
If no \refKey{parent} is given, a theorem is not numbered if it is the only theorem of its type and numbered otherwise.
If a \refKey{parent} is given, the same is true but considered within a single value of the parent counter.

For compatibility with \pkg{thmtools}, |numbered| also accepts the values \docValue*{yes}, \docValue*{no}, and \docValue*{unless unique}.

\begin{codepreamble}
\newkeytheorem{theorem*}[name=Theorem,numbered=false]
\end{codepreamble}

\begin{keythmscode}[withpreamble]
\begin{theorem*}
An unnumbered theorem.
\end{theorem*}
\end{keythmscode}

\end{docKey}

\begin{docKey}{parent}
  {=\meta{counter}}
  {initially unset}
Aliases \docAuxKey{numberwithin} and \docAuxKey{within}.
Sets the parent counter for the theorem counter, i.e., the displayed theorem number is of the form \meta{parent counter}\textbf{.}\meta{theorem counter} and the theorem counter is reset to 1 whenever the parent counter is incremented.

\begin{codepreamble}
\newkeytheorem{conjecture}[parent=section]
\end{codepreamble}

\begin{keythmscode}[withpreamble]
\begin{conjecture}
The first number is the section.
\end{conjecture}
\end{keythmscode}

\end{docKey}

\begin{docKey}{sibling}{=\meta{counter}}{initially unset}
Aliases \docAuxKey{numberlike} and \docAuxKey{sharenumber}.
Sets the sibling counter for the theorem counter, i.e., the sibling and theorem counters are incremented and reset simultaneously.

\begin{codepreamble}
\newkeytheorem{lemma}[sibling=theorem]
\end{codepreamble}

\begin{keythmscode}[withpreamble]
\begin{lemma}
This shares its counter with \texttt{theorem}.
\end{lemma}
\end{keythmscode}

\end{docKey}

\begin{docKey}{style}
  {=\meta{style name}}
  {initially unset}
Accepts any \meta{style name} defined by \refCom{newkeytheoremstyle}, as well as any of the predefined \pkg{amsthm} styles: \docValue{plain}, \docValue{definition}, and \docValue{remark}.
To emulate the appearance of theorems defined with the kernel \cs{newtheorem}, you may also use the predefined \docValue{legacy2e} style.
See \zcref{predefsty} for more on the predefined styles.

\begin{codepreamble}
\newkeytheorem{remark}[style=remark]
\end{codepreamble}

\begin{keythmscode}[withpreamble]
\begin{remark}
It's nice to distinguish remarks from definitions and theorems.
\end{remark}
\end{keythmscode}

\end{docKey}

\begin{docKeys}[
  doc parameter = {=\meta{code}},
  doc description = initially unset,
  ]
  {
    { doc name = preheadhook },
    { doc name = postheadhook },
    { doc name = prefoothook },
    { doc name = postfoothook },
  }
Details in \autoref{keythms-hooks}.

\begin{codepreamble}
\newkeytheorem{test}[
  preheadhook=PREHEAD,
  postheadhook=POSTHEAD,
  prefoothook=PREFOOT,
  postfoothook=POSTFOOT,
  ]
\end{codepreamble}

\begin{keythmscode}[withpreamble]
\begin{test}
Some text
\end{test}
\end{keythmscode}

\end{docKeys}

\begin{docKey}{qed}
  {\colOpt{=\meta{symbol}}}
  {default \cs{qedsymbol}, initially unset}
Adds \colOpt{\meta{symbol}} to the end of the theorem body.
If no value is given, the current value of |\qedsymbol| is used (one can redefine this or set it with \refKey{qed-symbol}).
By default, this is \qedsymbol.

\begin{codepreamble}
\newkeytheorem{example}[qed]
\newkeytheorem{solution}[qed=$\clubsuit$]
\end{codepreamble}

\begin{keythmscode}[withpreamble]
\begin{example}
Some text.
\end{example}
\begin{solution}
Some more text.
\end{solution}
\end{keythmscode}

\end{docKey}

\begin{docKey}[][before upper=\TCBdescnewline]{refname}
  {=\meta{ref name} \textrm{or} \brackets{\meta{singular name},\meta{plural name}}}
  {initially \cs{text\string_lowercase:n} \marg{display name}}
If a single string, then the name used by \pkg{hyperref}'s \cs{autoref}, \pkg{cleveref}'s \cs{cref}, and \pkg{zref-clever}'s \cs{zcref}.
If two strings separated by a comma, then the second string is the plural form used by \cs{cref} and \cs{zcref}.
\end{docKey}

\begin{docKey}[][before upper=\TCBdescnewline]{Refname}
  {=\meta{ref name} \textrm{or} \brackets{\meta{singular name},\meta{plural name}}}
  {initially \cs{text\string_titlecase\string_first:n} \marg{display name}}
Same as \refKey{refname} but for \docAuxCommand{Autoref}, \cs{Cref}, and \cs{zcref} with any of its capitalizing options.
Note that \cs{Autoref} is defined by \pkg{keytheorems}, but requires \pkg{hyperref} to work.
As with \cs{autoref}, there is also a starred version \docAuxCommand{Autoref*} that suppresses the hyperlink.

\begin{codepreamble}
\newkeytheorem{prop}[
  name=Proposition,
  refname={proposition,propositions},
  Refname={Proposition,Propositions},
  ]
\end{codepreamble}

\begin{keythmscode}[withpreamble]
\begin{prop}[label=abc]
Some text.
\end{prop}
\begin{prop}[label=def]
Some more text.
\end{prop}
Consider \zcref{abc,def}. \Autoref{abc} \dots
\end{keythmscode}

\end{docKey}

Both \pkg{cleveref} and \pkg{zref-clever} define default reference names for some commonly used counters like |theorem|, |lemma|, etc.
For technical reasons, unless explicit values for \refKey{refname} and \refKey{Refname} are given, \pkg{keytheorems} does not try to change these defaults at all in the case of \pkg{cleveref} and only the singular name in the case of \pkg{zref-clever}.
The easiest way to get exactly the output you want is to just explicitly set \refKey{refname} and \refKey{Refname}.

\begin{notebox}
The \refPkg{cleveref} package has not been updated since 2018 and contains several incompatibilities with the \LaTeX{} kernel.
These are often patched by the \LaTeX{} team, but further incompatibilities are likely to arise with each future update.
For this reason, I recommend moving to \refPkg{zref-clever}.
It offers all the same features as \pkg{cleveref} and is actively maintained.
\end{notebox}

\begin{docKeys}[doc parameter={=\meta{plural name}}]
  {
    { doc name=plural-refname, doc description=initially unset },
    { doc name=plural-Refname, doc description=initially unset },
  }
For convenience, you can also just specify the \meta{plural name} with these keys.
Since \pkg{keytheorems} uses the \meta{display name} to form the defaults for the \meta{singular name} but does not try to guess the \meta{plural name}, it's often the case that the user only needs to specify values for these keys and not \refKey{refname} or \refKey{Refname}.
\end{docKeys}

\subsection{Keys added by \pkg{keytheorems}} \label{thm-added-keys}

\begin{docKey}{counter-format}
  {=\meta{code}}
  {initially unset}
Syntactic sugar that essentially does \cs{renewcommand}\ttbraces{\cs{the}\meta{counter}}\marg{code}.
The \meta{code} should not contain any unexpandable tokens such as formatting commands.
Formatting should be taken care of in the style keys \refKey{headfont} and \refKey{numberfont}.
If used with an unnumbered theorem, a warning is issued.

\begin{codepreamble}
\newkeytheorem{mainthm}[
  name=Theorem,
  counter-format=\Alph*,
  ]
\end{codepreamble}

\begin{keythmscode}[withpreamble]
\begin{mainthm}
The first main result, distinguished by using letters.
\end{mainthm}
\begin{mainthm}
And here is the second main result.
\end{mainthm}
\end{keythmscode}

The |*| following |\Alph| means ``use the current counter'', a syntax originally introduced in \pkg{enumitem}'s |label| key.
This is available with a \LaTeX{} kernel 2025-06-01 or later.
For older kernels, the above example could be implemented equivalently with |counter-format=\Alph{mainthm}|.
\end{docKey}

\begin{docKeys}[doc parameter={=\meta{length}}]
  {
    { doc name=leftmargin },
    { doc name=rightmargin },
    { doc name=margin, doc description=initially |0pt| },
  }
Sets the left (respectively, right) margin of the theorem relative to the text width.
The |margin| key sets both simultaneously.
This sets the theorem apart from the text, similar to a block quote.
The code was adapted from Enrico Gregorio's \TeX{} Stack Exchange answers:
\begin{itemize}
	\item \href{https://tex.stackexchange.com/a/67251/208544}{How to change margins in enunciation (theorem-like environment)?}
	\item \href{https://tex.stackexchange.com/a/236407/208544}{A theoremstyle with complete indentation using amsthm}
\end{itemize}
\begin{codepreamble}
\newcommand{\marginthmtext}{%
  We need some text to show off theorems with margins. }
\newkeytheorem{quotethm}[name=Quote Theorem,margin=1cm]
\newkeytheorem{indentedthm}[name=Indented Theorem,leftmargin=1cm]
\end{codepreamble}

\newcommand{\marginthmtext}{We need some text to show off theorems with margins. }
\begin{keythmscode}[withpreamble]
\marginthmtext\marginthmtext\marginthmtext

\begin{quotethm}
\marginthmtext\marginthmtext\marginthmtext
\end{quotethm}

\marginthmtext\marginthmtext\marginthmtext

\begin{indentedthm}
\marginthmtext\marginthmtext\marginthmtext
\end{indentedthm}
\end{keythmscode}

\end{docKeys}

\begin{docKey}{tcolorbox}
  {\colOpt{=\marg{tcolorbox options}}}
  {initially unset}
This key specifies that the theorem be placed inside a |tcolorbox| environment with \colOpt{\meta{options}}.
The theorem head is typeset as a |tcolorbox| title; to avoid this see \refKey{tcolorbox-no-titlebar}.

\begin{codepreamble}
\tcbset{
  defstyle/.style={
    arc=0mm,
    colback=blue!5!white,
    colframe=blue!75!black
    },
  }
\newkeytheorem{corollary}[tcolorbox]
\newkeytheorem{definition}[style=definition,tcolorbox={defstyle}]
\end{codepreamble}

\begin{keythmscode}[withpreamble]
\begin{corollary}
Products exist in the category of schemes over $S$.
\end{corollary}
\begin{definition}[Dedekind domains]
A \emph{Dedekind domain} is an integrally closed, Noetherian domain of dimension one.
\end{definition}
\end{keythmscode}

\end{docKey}

\begin{docKey}{tcolorbox-no-titlebar}
  {\colOpt{=\marg{tcolorbox options}}}
  {initially unset}
Same usage as \refKey{tcolorbox} but the theorem head is typeset as usual, not as a |tcolorbox| title.

\begin{codepreamble}
\newkeytheorem{boxcor}[
  tcolorbox-no-titlebar={colback=red!10},
  name=Corollary,
  sibling=corollary,
  ]
\end{codepreamble}

\begin{keythmscode}[withpreamble]
\begin{boxcor}[Cauchy's theorem]
Let $G$ be a finite group and $p$ a prime dividing the order of $G$. Then $G$ contains an element of order $p$.
\end{boxcor}
\end{keythmscode}

\end{docKey}

\sloppy
Both \refKey{tcolorbox} and \refKey{tcolorbox-no-titlebar} set up a \pkg{tcolorbox} style |keythms_tcb_|\meta{env name} that can be accessed by the user if needed.
For convenience, one can also adjust the style for a specific theorem with the \refKey{tcb-append} key.

\fussy
\pkg{tcolorbox} offers its own comprehensive \texttt{theorems} library.
If all of your theorems are to be tcolorboxes, I highly recommend using it instead of this package! However, if only some of your theorems will use a tcolorbox, you may want to replicate the styles of \cs{NewTcbTheorem}.
Here is an example that emulates \pkg{tcolorbox}'s \texttt{standard} theorem style.

\begin{codepreamble}
\tcbset{
  thmstyle/.style={
    colback=green!5,
    colframe=green!35!black},
  }
\newkeytheoremstyle{tcb-standard}{
  tcolorbox=thmstyle,
  headpunct={},
  notebraces={}{},
  noteseparator={: },
  notefont=\bfseries,
  bodyfont=\normalfont,
  }
\newkeytheorem{mytheo}[
  name=Theorem,
  style=tcb-standard,
  ]
\end{codepreamble}

\begin{keythmscode}[withpreamble]
\begin{mytheo}[Quillen-Suslin]
Every finitely generated projective module over a polynomial ring is free.
\end{mytheo}
\end{keythmscode}

\section{Theorem styles}
\label{thmstyles}

\begin{docCommand}{newkeytheoremstyle}
  {\marg{style name}\marg{options}}
This is \pkg{keytheorems}' version of \pkg{thmtools}' \cs{declaretheoremstyle}.
Since it makes little sense to define a style with no keys, we've made the \meta{options} argument mandatory.
The defined style can be used with either the \refKey{style} key or the traditional \cs{theoremstyle}.
Note that unlike \pkg{amsthm}'s \cs{newtheoremstyle}, this command will error if a style has already been defined.
\end{docCommand}

\begin{docCommands}[
  doc parameter=\marg{style name}\marg{options}
  ]
  {
    {doc name = renewkeytheoremstyle},
    {doc name = providekeytheoremstyle},
    {doc name = declarekeytheoremstyle},
  }
\sloppy
To overwrite an existing style, there is the analogous \cs{renewkeytheoremstyle}.
For completeness, also provided are \cs{providekeytheoremstyle} and \cs{declarekeytheoremstyle}.
\end{docCommands}

\subsection{Predefined styles}
\label{predefsty}

\pkg{amsthm} defines the styles |plain|, |definition|, and |remark|. These, along with a |legacy2e| style meant to emulate the style of the kernel \cs{newtheorem}, are supported in both the \refKey{style} theorem key and the \refKey{inherit-style} style key.
The initial values changed by each style are described below.
\begin{itemize}
  \item \docValue*{plain}: This is the default.
  \item \docValue*{definition}: |bodyfont=\normalfont|
  \item \docValue*{remark}: |bodyfont=\normalfont|, |headfont=\itshape|, |spaceabove=0.5\topsep|, |spacebelow=0.5\topsep|
  \item \docValue*{legacy2e}: |notefont=\bfseries|, |headpunct={}|
\end{itemize}

\subsection{Keys also defined in \pkg{thmtools}}
\label{stylekeys:thmtools}

The following keys have the same meaning and syntax as the corresponding \pkg{thmtools} keys.
In addition to the list below, most of the keys available to \refCom{newkeytheorem} can be used in \cs{newkeytheoremstyle}.

\begin{docKey}{bodyfont}
  {=\meta{font declarations}}
  {initially \cs{itshape}}
Sets the font declarations for the theorem body.
This does not affect the theorem heading; see \refKey{headfont}.
\end{docKey}

\begin{docKey}{break}
  {}
  {initially unset}
Causes the theorem body to be typeset on a new line after the heading.
Do not use this with the \refKey{postheadspace} key.
\end{docKey}

\begin{docKey}{headfont}
  {=\meta{font declarations}}
  {initially \cs{bfseries}}
Sets the font declarations for the theorem heading, which includes the theorem name, number, and note.
The heading is typeset in a \TeX\ group, so these declarations will not affect the body of the theorem.
Note, however, that the declarations in the \refKey{numberfont} and \refKey{notefont} keys may reset some font features set in |headfont|.
By default, the number is typeset in upright shape and the note in both upright shape and medium weight.
\end{docKey}

\begin{docKey}[][before upper=\TCBdescnewline]{headformat}
  {=\docValue{margin}\textbar\docValue{swapnumber}\textbar\meta{code using \cs{NAME}, \cs{NUMBER}, and \cs{NOTE}\,}}
  {initially \cs{NAME}\cs{\textvisiblespace}\cs{NUMBER}\cs{NOTE}}
Alias \docAuxKey{headstyle}.
Allows the user to completely control the appearance of the theorem heading.
Within \meta{code}, the commands \docAuxCommand{NAME}, \docAuxCommand{NUMBER}, and \docAuxCommand{NOTE} correspond to the formatted parts of the theorem head.
For compatibility with \pkg{thmtools}, the user is in charge of specifying the separator (usually a space) preceding \cs{NUMBER}; the separator preceding \cs{NOTE} is controlled by \refKey{noteseparator}.

The special values |margin| and |swapnumber| are demonstrated below.

\begin{codepreamble}
\newkeytheoremstyle{marginstyle}{headformat=margin}
\newkeytheoremstyle{swapnumberstyle}{headformat=swapnumber}
\newkeytheorem{marginthm}[
  name=Margin Theorem,
  style=marginstyle,
  ]
\newkeytheorem{swapnumberthm}[
  name=Swapnumber Theorem,
  style=swapnumberstyle,
  ]
\end{codepreamble}

\begin{keythmscode}[withpreamble]
\begin{marginthm}
A theorem whose number juts into the margin.
\end{marginthm}
\begin{swapnumberthm}
A theorem whose name and number are swapped.
\end{swapnumberthm}
\end{keythmscode}

\end{docKey}

\begin{notebox}
In \refKey{headformat}, you may also use the traditional \pkg{amsthm} commands \cs{thmname}, \cs{thmnumber}, and \cs{thmnote}, where |#1| is the theorem name, |#2| the number, and |#3| the note.
\pkg{keytheorems} expands the head spec inside |\text_expand:n| so for these commands to work properly, the package adds them to |\l_text_expand_exclude_tl|.
Note also that if you use these lower-level commands, the style keys \refKey{notebraces}, \refKey{notefont}, \refKey{noteseparator}, and \refKey{numberfont} will have no effect (of course, you can manually control these things inside the commands' arguments).
\end{notebox}

\begin{docKey}{headindent}
  {=\meta{length}}
  {initially |0pt|}
Sets the distance between the left margin and the theorem heading.
\end{docKey}

\begin{docKey}{headpunct}
  {=\meta{code}}
  {initially \ttbraces{.}}
Sets the punctuation that ends the theorem heading.
\end{docKey}

\begin{docKey}{notebraces}
  {=\marg{left brace}\marg{right brace}}
  {initially \ttbraces{(}\ttbraces{)}}
Sets the delimiters surrounding the theorem note if present.
\end{docKey}

\begin{docKey}{notefont}
  {=\meta{font declarations}}
  {initially \cs{fontseries}\cs{mddefault}\cs{upshape}}
Sets the font declarations for the theorem note.
The note is also affected by \refKey{headfont}; the initial value of |notefont| happens to negate the initial value of |headfont| by resetting the font weight to medium, however any other settings in |headfont| will propagate to the note.
\end{docKey}

\begin{docKey}{postheadspace}
  {=\meta{skip expr}}
  {initially |5pt plus 1pt minus 1pt|}
Sets the distance between the theorem heading and body.
Do not use this with the \refKey{break} key.
\end{docKey}

\begin{docKey}{spaceabove}
  {=\meta{skip expr}}
  {initially \cs{topsep}}
Sets the vertical space before the theorem.
\end{docKey}

\begin{docKey}{spacebelow}
  {=\meta{skip expr}}
  {initially \cs{topsep}}
Sets the vertical space after the theorem.
\end{docKey}

\begin{notebox}
With \refKey{tcolorbox} and \refKey{tcolorbox-no-titlebar}, the \refKey{spaceabove} and \refKey{spacebelow} keys are internally passed to \pkg{tcolorbox}'s \texttt{before skip} and \texttt{after skip}.
When no explicit \texttt{spaceabove} or \texttt{spacebelow} values are given, \pkg{tcolorbox} defaults are used instead of \cs{topsep}.
\end{notebox}

\subsection{Keys added by \pkg{keytheorems}}
\label{stylekeys:new}

\begin{docKey}{inherit-style}
  {=\meta{style name}}
  {initially unset}
Inherit the keys of any style declared with \refCom{newkeytheoremstyle}.
Additionally, \docValue{legacy2e} and the three styles predefined by \pkg{amsthm} are possible values: \docValue{plain}, \docValue{definition}, and \docValue{remark}.
\end{docKey}

\begin{docKey}{noteseparator}
  {=\meta{code}}
  {initially \textvisiblespace}
The code inserted before the note, and printed only if there is a note.
This is executed \emph{before} the font commands set by \refKey{notefont} take effect.
\end{docKey}

\begin{docKey}{numberfont}
  {=\meta{font declarations}}
  {initially \cs{upshape}}
Sets the font declarations for the theorem number.
For almost all theorem styles, it is recommended that you \emph{do not} change this setting.
As with \refKey{notefont}, the number font is affect by \refKey{headfont}, though here the initial value only changes the shape to upright.
\end{docKey}

\begin{notebox}
For the AMS classes \cls{amsart}, \cls{amsbook}, and \cls{amsproc}, as well as the \cls{amsart}-based \cls{acmart} and \cls{aomart}, the initial key values are slightly different those listed in \zcref{stylekeys:new,stylekeys:thmtools} in order to match those class's defaults.
See \autoref{class-support} for details.
\end{notebox}

\section{Restating theorems}

When a theorem is given the \refKey{store} key, the contents of the theorem are saved and written to a |.thlist| file.
At the start of the next run, this file is input at the beginning of the document and allows you to retrieve the stored theorems at any point, before or after the original theorem.

\begin{docCommand}{getkeytheorem}
  {\oarg{property}\marg{tag}}
Retrieves the theorem given the key |store=|\meta{tag} or |store*=|\meta{tag}.
An optional \meta{property} can be given to retrieve only the corresponding part of the theorem.
Currently only the property |body| is implemented, which retrieves the (unformatted) body of the theorem.

\begin{keythmscode}
\getkeytheorem{mytag}

\begin{example}[store=mytag]
Fascinating example.
\end{example}

\getkeytheorem[body]{mytag}
\end{keythmscode}

\end{docCommand}

\begin{docCommands}
  {
    {
      doc name = IfRestatingTF,
      doc parameter=\marg{true code}\marg{false code}
    },
    {
      doc name = IfRestatingT,
      doc parameter=\marg{true code}
    },
    {
      doc name = IfRestatingF,
      doc parameter=\marg{false code}
    }
  }
Executes \meta{true code} if being retrieved with \refCom{getkeytheorem} and \meta{false code} if in the original theorem.
This is reversed if \texttt{store*} is used.

\begin{keythmscode}
\begin{example}[store=hmm]
I am the \IfRestatingTF{restated}{original} example!
\end{example}

\getkeytheorem{hmm}
\end{keythmscode}

\end{docCommands}

\subsection{Counters within a restated theorem}

Counters used within a theorem can be stored and set to their original value when restated.
By default, this is done for the |equation| counter, however more counters can be added with \refKey{restate-counters}.
This is necessary if, as is often the case, equations use the |section| or |subsection| counter as part of their numbering.

\begin{codepreamble}
\counterwithin{equation}{section}
\keytheoremset{restate-counters={section}}
\end{codepreamble}

\begin{keythmscode}[withpreamble]
\begin{theorem}[store=Fermat]
For $n\geq 3$, there are no nontrivial integer solutions to the equation
\begin{equation}
x^n+y^n=z^n.
\end{equation}
\end{theorem}

\getkeytheorem{Fermat}
\end{keythmscode}

In this example, removing |\keytheoremset{restate-counters={section}}| would not change the restated equation number because it is being restated in the same section.
If that line were removed, the restated equation number would be different (wrong) if restated in a different section.

\subsection{Restating theorems from an external file}

\begin{docCommand}{externaltheorems}
  {\oarg{prefix}\marg{file name}}
This is \pkg{keytheorems}' version of the \pkg{xr} package's \cs{externaldocument}.
It allows the user to restate theorems from another document's |.thlist| file.
Say you have a file |mycoolpaper.tex|,
\begin{dispListing}
% mycoolpaper.tex
\documentclass{article}
\usepackage{keytheorems}
\newkeytheorem{theorem}
\begin{document}
\begin{theorem}[store=cooltheorem]
My cool theorem.
\end{theorem}
\end{document}
\end{dispListing}
and you'd like to restate the theorem with tag |cooltheorem| in another file |myothercoolpaper.tex| with the same numbering as in the original paper.
Since your new paper probably also has cool theorems that you may want to tag as |cooltheorem|, you'd like to give all restatable theorems from |mycoolpaper.tex| a prefix when retrieved with \refCom{getkeytheorem}, say ``|orig:|''.
\sloppy Just call \cs{externaltheorems}|[orig:]{mycoolpaper}| after loading \pkg{keytheorems} in the new document.
Then any stored theorem from |mycoolpaper.tex| can be retrieved with \cs{getkeytheorem}\ttbraces{orig:\meta{tag}}.
\begin{dispListing}
% myothercoolpaper.tex
\documentclass{article}
\usepackage{keytheorems}
\externaltheorems[orig:]{mycoolpaper}
\newkeytheorem{theorem}
\begin{document}
\getkeytheorem{orig:cooltheorem}
\end{document}
\end{dispListing}
It is important that the |theorem| environment is defined in both documents.
\end{docCommand}

\section{Listing theorems}
\label{listingthms}

\begin{docCommand}{listofkeytheorems}
  {\oarg{options}}
Similar to \cs{listoffigures} or \cs{listoftables} but for theorems.
For \cls{memoir} and the AMS classes, \pkg{keytheorems} tries to copy the formatting of these commands as defined by the class.
For other classes, manual adjustments to \refKey{numwidth} and \refKey{indent} may be necessary.
\end{docCommand}

\begin{docCommand}{keytheoremlistset}
  {\marg{options}}
The \meta{options} of \refCom{listofkeytheorems} may also be set globally with this command.
\end{docCommand}

\begin{keythmscode}
\listofkeytheorems
\end{keythmscode}

\subsection{Keys also defined in \pkg{thmtools}}

\begin{docKey}{ignore}
  {=\marg{comma-list of env names}}
  {initially unset}
Environments in \meta{comma-list} are filtered out from the list of theorems.
\end{docKey}

\begin{docKey}{ignoreall}
  {}
  {initially unset}
Applies \refKey{ignore} to all theorems.
This is usually followed by the keys \refKey{show}, \refKey{onlynamed}, and/or \refKey{onlynumbered}.
 
\begin{keythmscode}
\listofkeytheorems[ignoreall,show=theorem]
\listofkeytheorems[
  ignoreall, show=conjecture,
  title=List of Conjectures
  ]
\end{keythmscode}

\end{docKey}

\begin{docKey}{numwidth}
  {=\meta{length}}
  {initially |2.3em|}
Sets the width that theorem numbers occupy in the list of theorems.
This is needed when theorems have long parent counter representations, e.g., Theorem 3.7.4.1.
For the AMS classes, this is initially |1.5pc|.
\end{docKey}

\begin{docKey}{onlynamed}
  {\colOpt{=\marg{comma-list of env names}}}
  {initially unset}
Environments in \meta{comma-list} are only printed if the theorem was given an optional note.
If no value is given, then this applies to all theorems.
\end{docKey}

\begin{docKey}{show}
  {=\marg{comma-list of env names}}
  {initially all theorems}
The counterpart to \refKey{ignore}.
Environments in \meta{comma-list} are shown in the list of theorems.
Note that this is only needed if a theorem type was previously ignored, usually with \refKey{ignoreall}.
\end{docKey}

\begin{docKey}{showall}
  {}
  {initially set}
Applies \refKey{show} to all theorems.
\end{docKey}

\begin{docKey}{swapnumber}
  {\colOpt{=true\textbar false}}
  {initially |false|}
Swaps the position of the theorem name and number in the list of theorems.
This will override \refKey{format-code} if true.

\begin{keythmscode}
\listofkeytheorems[ignoreall,show=lemma]
\listofkeytheorems[ignoreall,show=lemma,swapnumber]
\end{keythmscode}

\end{docKey}

\begin{docKey}{title}
  {=\meta{text}}
  {initially \cs{GetTranslation}\ttbraces{keythms\string_listof\string_title}}
Defaults to ``List of Theorems'' if English or an unknown language is used.
Currently several European languages have (likely inaccurate!) translations.
A translation can be added with a GitHub pull request or manually with
\begin{center}
\cs{DeclareTranslation}\marg{lang}\ttbraces{keythms\string_listof\string_title}\marg{text}.
\end{center}
\end{docKey}

\subsection{Keys added by \pkg{keytheorems}}

\begin{docKey}{format-code}
  {=\meta{code with \textup{\texttt{\#1}}, \textup{\texttt{\#2}}, and \textup{\texttt{\#3}}}}
  {initially \cs{numberline}\texttt{\{\#2\}\#1\#3}}
Allows full control over the format for list entries.
The theorem name is |#1|, the number is |#2|, and the (formatted) note is |#3|.
The note formatting is still controlled by \refKey{note-code}.
\end{docKey}

\begin{docKey}{indent}
  {=\meta{length}}
  {initially |1.5em|}
Sets the left indent of items in the list of theorems.
For \cls{memoir} and the AMS classes, the indent is initially |0pt|.
It is not recommended to change this unless your class has different defaults not already covered.
\end{docKey}

\begin{docKey}{no-chapter-skip}
  {\colOpt{=true\textbar false}}
  {initially |false|}
By default a small vertical space is inserted between each chapter's chunk of theorems.
Setting this key to |true| removes this space.
\end{docKey}

\begin{docKey}{chapter-skip-length}
  {=\meta{length}}
  {initially |10pt|}
Controls the amount of space inserted between chunks of theorems belonging to each chapter.
\end{docKey}

\begin{docKey}{no-continues}
  {\colOpt{=true\textbar false}}
  {initially |false|}
Suppresses the printing of theorems given the \refKey{continues} key in the list of theorems.
\end{docKey}

\begin{docKey}{no-title}
  {\colOpt{=true\textbar false}}
  {initially |false|}
Suppresses the title of the list of theorems.
This is useful for custom ordering of the list.

\begin{keythmscode}
\keytheoremlistset{ignoreall}
\listofkeytheorems[show=example]
\listofkeytheorems[show=solution,no-title]
\end{keythmscode}

\end{docKey}

\begin{docKey}{no-toc}
  {\colOpt{=true\textbar false}}
  {initially |false|}
With the standard classes, lists of figures/tables are not added to the table of contents by default.
The same is true for \cs{listofkeytheorems}, and with those classes this key does nothing.
However some classes, notably \cls{memoir} and the AMS classes, do add lists to the table of contents.
With these classes, this key suppresses the addition of the list of theorems to the table of contents.
\end{docKey}

\begin{docKey}{note-code}
  {=\meta{code with \textup{\texttt{\#1}}}}
  {initially \ttbraces{\textvisiblespace(\#1)}}
Formats the optional note in the list of theorems.
\end{docKey}

\begin{docKey}{one-col}
  {\colOpt{=true\textbar false}}
  {initially |false|}
In |twocolumn| mode, some classes such as the standard \cls{book} typeset lists of figures, etc., in one column.
\pkg{keytheorems} does not do this by default; this key forces the list into |onecolumn| mode.
Note that this is \emph{not} compatible with the application mentioned under \refKey{no-title} since switching between \cs{onecolumn} and \cs{twocolumn} starts a new page.
You can, however, achieve the same effect manually:
\begin{dispListing}
\keytheoremlistset{ignoreall}
\onecolumn
\listofkeytheorems[show=example]
\listofkeytheorems[show=solution,no-title]
\twocolumn
\end{dispListing}
If \refKey{no-chapter-skip} is false (the default), you may want to add some vertical space between the two lists.
\end{docKey}

\begin{docKey}{onlynumbered}
  {\colOpt{=\marg{comma-list of env names}}}
  {initially unset}
Similar to \refKey{onlynamed}, but lists only those theorems which are numbered.
This is useful if you'd like to exclude things like unnumbered definitions and remarks from the list of theorems.
\end{docKey}

\begin{docKey}{print-body}
  {}
  {initially unset}
Instead of listing the theorem headings, the theorems are restated with their body text.
Not very useful without the \refKey{store-all} load-time option.
\end{docKey}

\begin{docKey}[][doc label=listof/seq]{seq}
  {=\meta{name}}
  {initially unset}
Used to list only the theorems added to the custom sequence \meta{name} with the \refKey{thmuse/seq} theorem key.
This is the only way to fully customize which theorems appear in the list of theorems.
Unlike with \refKey{show}, you do not need to use \refKey{ignoreall} to prevent theorems not in \meta{name} from being printed.
\end{docKey}

\begin{docKey}{title-code}
  {=\meta{code with \textup{\texttt{\#1}}}}
  {initially \cs{section*}\ttbraces{\#1}}
If \cs{chapter} is defined, then initially this is instead \cs{chapter*}\ttbraces{\#1}.
This key has no effect if used with an AMS class because these classes hard-code the section heading into \cs{@starttoc}.
\end{docKey}

\subsection{Adding code to list of theorems}

\begin{docCommand}{addtheoremcontentsline}
  {\marg{level}\marg{text}}
This command is analogous to \cs{addcontentsline} and has the same usage, that is, manually adding entries to the list of theorems.
\end{docCommand}

\begin{docCommand}{addtotheoremcontents}
  {\marg{code}}
This command is analogous to \cs{addtocontents} and has the same usage, that is, manually adding arbitrary code to the list of theorems.
\end{docCommand}

\begin{notebox}
You \emph{must} use these commands rather than the analogous ones mentioned because the |.thlist| file is also used to define restated theorems and cannot contain unexpected code.
\end{notebox}

\section{Theorem hooks} \label{keythms-hooks}

\begin{docCommand}{addtotheoremhook}
  {\oarg{env name}\marg{hook name}\marg{code}}
The \meta{hook name} can be \hook{prehead}, \hook{posthead}, \hook{prefoot}, \hook{postfoot}, or \hook{restated}.
If no \meta{env name} is given, the \meta{code} is added to the ``generic'' hook, i.e., applied to all theorems.
As in \pkg{thmtools}, the order of hooks is as follows:

\begin{center}
  \small
  \tcbset{
    nobeforeafter,
    tikznode,
    tcbox width=forced center,
    width=1.85cm,
    tcbox raise=-0.4cm,
    size=fbox,
    after=\;\textrightarrow,
    }
  \tcbox{\meta{env name}\\ \hook{prehead}}
  \tcbox{generic\\ \hook{prehead}}
  \tcbox[width=3.25cm,tcbox raise=-0.2cm]{\cs{begin}\brackets{\meta{env name}}}
  \tcbox{\meta{env name}\\ \hook{posthead}}
  \tcbox[after={}]{generic\\ \hook{posthead}}
  \\[2ex]
  \tcbset{before=\textrightarrow\;}
  \tcbox[width=2.25cm,tcbox raise=-0.2cm]{\meta{theorem body}}
  \\[2ex]
  \tcbset{after={}}
  \tcbox[before={}]{generic\\ \hook{prefoot}}
  \tcbox{\meta{env name}\\ \hook{prefoot}}
  \tcbox[width=3.25cm,tcbox raise=-0.2cm]{\cs{end}\brackets{\meta{env name}}}
  \tcbox{generic\\ \hook{postfoot}}
  \tcbox{\meta{env name}\\ \hook{postfoot}}
\end{center}
The \hook{restated} hook is applied at the start of theorems retrieved with the command \cs{getkeytheorem}, after the \hook{prehead} hook.
This can be useful for disabling commands such as \cs{footnote} in the restated theorems, e.g.,
\begin{dispListing}
\addtotheoremhook{restated}{\renewcommand\footnote[2][]{}}
\end{dispListing}

By default, the \hook{restated} hook disables the \cs{glossary}, \cs{index}, \cs{label}, and \cs{RecordProperties} commands.

In \pkg{thmtools}, the \hook{prefoot} and \hook{postfoot} hooks always prepend code, i.e., the code
\begin{dispListing}
\addtotheorempostfoothook{A}
\addtotheorempostfoothook{B}
\end{dispListing}
results in |BA| after the theorem.
With \pkg{keytheorems}, code is added in the order declared, meaning
\begin{dispListing}
\addtotheoremhook{postfoot}{A}
\addtotheoremhook{postfoot}{B}
\end{dispListing}
results in |AB| after the theorem.
This is the behavior of the \LaTeX{} kernel hooks that \pkg{keytheorems} uses under the hood.

Code added using the hook keys \refKey{preheadhook}, etc.\@ is outermost, meaning executed first in \hook{prehead} and \hook{posthead} and last in \hook{prefoot} and \hook{postfoot}.
Furthermore, if present, the \refKey{qed} symbol is placed \emph{before} the \hook{prefoot} hook.
\end{docCommand}

\section{Miscellaneous notes}

\subsection{\cls{beamer} support}
\label{subsec:beamer}

The package contains some \emph{highly experimental} code to support theorems with \cls{beamer}, including overlays.
The support differs based on whether or not the \cls{beamer} class option |noamsthm| is used.

User feedback is necessary to make this code fully compatible.
Please report issues on the \href{https://github.com/mbertucci47/keytheorems/issues}{Github page}!

\subsubsection{Without \texttt{noamsthm}}
Most style keys are disabled by the |default| \cls{beamer} theorem template.
More become functional by setting
\begin{dispListing}
\setbeamertemplate{theorems}[ams style]
\end{dispListing}
in the preamble.
For full control of theorems, load the class option |noamsthm| and see \zcref{subsubsec:noamsthm}.

Note that by default \cls{beamer} defines a set of theorems when the class is loaded.
These can be overwritten with \refCom{renewkeytheorem} or disabled entirely with the |notheorems| class option.

Due to complications with overlays, writing contents of theorems to the |thlist| file is disabled.
This means theorems can only be restated \emph{after} their original statement.
Furthermore, \refCom{listofkeytheorems} is disabled and a warning issued if used.

\subsubsection{With \texttt{noamsthm}}
\label{subsubsec:noamsthm}

If |noamsthm| is loaded, you can use keytheorems exactly as you would in any other document except that \refCom{listofkeytheorems} is disabled.
This includes no limitations on storing and restating theorems that exist without |noamsthm|.

With or without |noamsthm|, overlays are supported with syntax
\begin{tcolorbox}[blankest]
\cs{begin}\braces{\meta{theorem name}}\colOpt{\pbarg{overlay spec}}\colOpt{\oarg{options}} \\
\hspace*{2ex}\meta{contents} \\
\cs{end}\braces{\meta{theorem name}}
\end{tcolorbox}

\subsection{Support for other classes}
\label{class-support}

As mentioned in \autoref{thmstyles}, the initial style key values set by \pkg{keytheorems} are adjusted for the AMS classes \cls{amsart}, \cls{amsbook}, and \cls{amsproc}, the \cls{amsart}-based \cls{acmart} and \cls{aomart}, and \cls{jlreq}.
You can find the exact changed values in the support files \texttt{keythms-\meta{class}-support.tex}.

These class support files also contain code to adapt to class' formatting of lists-of as mentioned in \autoref{listingthms}; changes are made for the AMS classes, \cls{memoir}, \cls{IEEEtran}, and \cls{jlreq}.

Lastly, in addition to the \cls{beamer} support outlined in \zcref{subsec:beamer}, support is provided for overlays in the experimental tagging-compatible presentation class \cls{ltx-talk}.
See \zcref{subsec:tagging} for more details.

\subsection{Support for font packages}

Some font packages, all by Michael Sharpe, offer a |theoremfont| option that redefines the |plain| style body font to have italic text with upright figures, punctuation, and delimiters.
\pkg{keytheorems} detects this option and sets its initial style values accordingly.
The supported packages are \pkg{baskervillef}, \pkg{cochineal}, \pkg{libertinust1math}, \pkg{newpxtext}, \pkg{newtxtext}, \pkg{scholax}, \pkg{stickstootext}, and \pkg{XCharter}.

\subsection{Support for tagged PDF}
\label{subsec:tagging}

\sloppy
The \LaTeX{} team has been working hard to support the creation of tagged PDFs (see \url{https://latex3.github.io/tagging-project/}).
In the current format, \pkg{amsthm} is compatible with the kernel tagging code.
Most of \pkg{keytheorems} is supported too, and anything that doesn't work should be reported.
Explicitly not yet supported are the \refKey{tcolorbox} and \refKey{tcolorbox-no-titlebar} keys and values of \refKey{headformat} other than |margin| and |swapnumber|.

\fussy
To produce a tagged PDF, add \cs{DocumentMetadata} in the first line of your document (additional instructions are found on the Tagging Project \href{https://latex3.github.io/tagging-project/documentation/usage-instructions}{website}).
An example invocation might look like

\begin{dispListing}
\DocumentMetadata
  {
    lang=en-US,
    pdfversion=2.0,
    pdfstandard=ua-2,
    tagging=on,
    % tagging-setup={math/setup=mathml-SE}, % optional
  }
\end{dispListing}

As mentioned above, support is also provided for the tagging-compatible \cls{ltx-talk} presentation class.
You may use \pkg{keytheorems} exactly as you would in a normal tagged document, with the added support of overlays.
The syntax for overlays is the same as for \cls{beamer}, shown in \zcref{subsubsec:noamsthm}.
Also as for \cls{beamer}, the \refCom{listofkeytheorems} command is disabled.

\subsection{\pkg{subfiles} compatibility}

\sloppy
Because of how the \pkg{subfiles} package works, it is not possible to restate theorems from one subfile in another without an extra step.
The issue boils down to the same reason the \pkg{xr} package is needed for labels and references to work between subfiles.
Thankfully, the fix is fairly easy with \refCom{externaltheorems}.
Just add \cs{externaltheorems}\bracks{\meta{prefix}}\marg{main file name} to the preamble of your main file.
Then, after compiling your main file at least once, theorems can be restated in subfiles with \cs{getkeytheorem}\braces{\meta{prefix}\meta{tag}}.

\fussy
Here is a complete example.
\begin{dispListing*}{breakable}
% mainfile.tex
\documentclass{article}
\usepackage{keytheorems} 
\usepackage{subfiles}

\externaltheorems[main:]{mainfile}
\newkeytheorem{theorem}

\begin{document}
\subfile{subfile1.tex}
\subfile{subfile2.tex}
\end{document}

% subfile1.tex
\documentclass[mainfile.tex]{subfiles}
\begin{document}
\section{subfile1}
\begin{theorem}
Some theorem from the first subfile.
\end{theorem}
\getkeytheorem{main:secondthm}
\end{document}

% subfile2.tex
\documentclass[mainfile.tex]{subfiles}
\begin{document}
\section{subfile2}
\begin{theorem}[store=secondthm]
Some theorem from the second subfile.
\end{theorem}
\end{document}
\end{dispListing*}

\subsection{Public coding interfaces}

\begin{docCommand}{l_keythms_thmuse_envname_tl}{}
Inside theorem environments and in all theorem hooks, you have access to the theorem's environment and counter name in this token list variable.
\end{docCommand}

\begin{docCommands}
  {
    {
      doc name=keythms_getthm_theorem:nnnnn,
      doc parameter={%
        \ \marg{name} \marg{number} \marg{restate counters}\\
        \hspace*{1cm}%
        \marg{keys} \marg{body text}%
        },
    },
    {
      doc name=keythms_getthm_body:nnn,
      doc parameter=\ \marg{name} \marg{restate counters} \marg{body text},
    },
  }
These are the commands called by \refCom{getkeytheorem} when restating stored theorems. They can be useful for customizing the behavior of the list of theorems with a printed body; see \refCom{keythms_listof_listcmd:nnnnnnn}.
\end{docCommands}

\begin{docCommand}{keythms_listof_listcmd:nnnnnnn}
  {%
    \ \marg{name} \marg{number} \marg{Href} \marg{page}\\
    \hspace*{1cm}%
    \marg{restate counters} \marg{keys} \marg{body text}%
  }
This is the command that controls how theorems are printed in the list of theorems. See \url{https://tex.stackexchange.com/a/747257/208544} for a concrete use-case in tandem with \refCom{keythms_getthm_theorem:nnnnn}.  
\end{docCommand}

\begin{docKeys}[doc no index,color key=black]
  {
    {
      doc name=keytheorems/allthms/\textmd{\meta{hook name}},
      doc label=allthms-hook,
    },
    {
      doc name=keytheorems/\textmd{\meta{envname}}/\textmd{\meta{hook name}},
      doc label=envname-hook,
    }
  }
These are the ``real'' names for the hooks described in \autoref{keythms-hooks}.
They can be useful with \cs{AddToHookNext} or the kernel's label mechanism for hooks.
\end{docKeys}

\section{Further examples}

\sloppy
More examples will be added soon -- rather, eventually\dots{}
For now, you can find a \pkg{keytheorems} adaptation of \pkg{amsthm}'s classic \href{https://mirrors.ctan.org/macros/latex/required/amscls/doc/thmtest.tex}{\texttt{thmtest.tex}} in the Github \texttt{tests} folder: \href{https://github.com/mbertucci47/keytheorems/blob/develop/tests/keytheorems-amsthmtest.tex}{\texttt{keytheorems-amsthmtest.tex}}.
There is also a version for tagged PDF: \href{https://github.com/mbertucci47/keytheorems/blob/develop/tests/tagged-keytheorems-amsthmtest.tex}{\texttt{tagged-keytheorems-amsthmtest.tex}}.

\fussy
%\section{Implementation}
%\inputminted[linenos,style=bw]{latex}{../keytheorems.sty}

\printindex

\end{document}
