% \iffalse meta-comment
%
% Copyright (C) 2022-2026 by Julien Labbé <Julien.Labbe@univ-grenoble-alpes.fr>
%
% This file may be distributed and/or modified under the conditions of the
% LaTeX Project Public License (LPPL), either version 1.3c of this license or
% (at your option) any later version. The latest version of this license is in
% the file https://www.latex-project.org/lppl.txt
%
% \fi
%
% \iffalse
%
%<package>\NeedsTeXFormat{LaTeX2e}
%<package>\ProvidesExplPackage{altsubsup}{2026/11/29}{v2.0}
%<package>{Alternative and customizable formatting for subscripts and superscripts}
%
%<*driver>
\documentclass[nohyperref]{ltxdoc}

\usepackage{altsubsup-doc} %^^A defined at end of this file, with guard <docstyle>

%^^A Load the settings used by mode=active-delimiters, for illustration
\ExplSyntaxOn
\input{altsubsup-active-delimiters.code.tex}
\cs_undefine:c { \c__keys_code_root_str altsubsup / command } %^^A Force altsubsup to erase the setting made by altsubsup-active-delimiters.code.tex
\ExplSyntaxOff
\usepackage[spbmark]{altsubsup}
\altsubsupset{
  []/disable,
  command = \textnormal
}

\usepackage{metalogo}
\usepackage{derivative}

%^^A Define some settings used by mode=active-symbols, for illustration
\ExplSyntaxOn
\cs_new_protected:Nn \altsubsup_patch_macro_catcodes:N
  {
    \regex_replace_all:nnN { \cD\_ }{ \cO\_ } #1
    \regex_replace_all:nnN { \cU\^ }{ \cO\^ } #1
  }
\keys_define:nn { altsubsup }
  {
    ,patch-macro .code:n =
      {
        \clist_map_function:nN { #1 } \altsubsup_patch_macro_catcodes:N
      }
  }
\ExplSyntaxOff

%^^A Some settings are overwritten by active-delimiters.code.tex at
%^^A begindocument. Redefine them.
\ExplSyntaxOn
\AtBeginDocument{
  \keys_define:nn { altsubsup }
    {
      ,enable                     .code:n  =
        {
          \__altsubsup_enable_subscript:
          \__altsubsup_enable_superscript:
        }
      ,disable                     .code:n  =
        {
          \__altsubsup_disable_subscript:
          \__altsubsup_disable_superscript:
        }
    }
}
\ExplSyntaxOff

\altsubsupset {
  new-delimiters = {
    <> = {put-left = {\mathcolor{red}{\rightarrow}}},
    // = {command = {\mathcolor{blue}}}
  },
  <> / disable,
  // / disable,
}

\EnableCrossrefs
\PageIndex
% \CodelineIndex
\RecordChanges
% \OnlyDescription

\begin{document}

\DocInput{altsubsup.dtx}

\PrintIndex
\PrintChanges

\end{document}
%</driver>
% \fi
%
% \changes{v1.0}{2022/01/23}{Initial version.}
%
% \GetFileInfo{\jobname.sty}
%
% \title{The \pkg*{altsubsup} package\thanks{This document corresponds to
% \pkg*{altsubsup}~\fileversion, dated \filedate.}}
% \author{Julien Labb\'e \\ {\small \url{https://github.com/julienlabbe/latex-packages}}}
%
% \maketitle
%
% \begin{abstract}
%   A \LaTeX{} package for custom subscripts and superscripts. An alternative
%   formatting is used when the subscript or the superscript is written in
%   square brackets. By default, it lets you quickly obtain an upright format.
%
% \bigskip
%
% Example:
% \iffalse
%<*example>
% \fi
\begin{dispExample}
  $ x_[roman]^{italic} \qquad x_{italic}^[roman] $
\end{dispExample}
% \iffalse
%</example>
% \fi
%
% \end{abstract}
%
% \tableofcontents{}
% \clearpage
%
% \section{Introduction}
%
% \subsection{Presentation of the package}
%
% The \pkg*{altsubsup} package provides an alternative formatting for subscripts
% and superscripts when written with square brackets in math mode:
% \iffalse
%<*example>
% \fi
\begin{dispExample}
$ x_[my~subscript] $ \qquad or \qquad $ x^[my~superscript] $.
\end{dispExample}
% \iffalse
%</example>
% \fi
%
% The alternative formatting of subscripts and superscripts is customizable
% through a key-value interface:
% \iffalse
%<*example>
% \fi
\begin{dispExample}
\altsubsupset{
  subscript-command = \mathbf,
  superscript-put-left = \color{purple}
}

$ x_[my~subscript] $ \qquad or \qquad $ x^[my~superscript] $.
\end{dispExample}
% \iffalse
%</example>
% \fi
% \noindent By default, the \cs{textnormal} command is used for both subscript
% and superscript.
%
% \medskip
%
% The \pkg*{altsubsup} implementation uses |lua| callbacks, when the \LaTeX{}
% engine is \LuaLaTeX{}, or active characters, with pdf\LaTeX{} or \XeLaTeX{}.
% These different operating modes are detailed in section~\ref{sec:modes}, page~\pageref{sec:modes}.
% It's also possible to choose the implementation mechanism through the
% \refOpt{mode} package option. Note that many settings are specific to the
% selected mode.
%
% \medskip
%
% In addition, the \refKey{spbmark} option provides integration with the
% \pkg{spbmark} package.
%
% \subsection{Motivations}
%
% Common typographic conventions\footnotemark{} use italic (sloping) type for
% physical quantities or mathematical variables and roman (upright) type for
% words or fixed numbers. For example, the heat capacity at constant pressure
% should be printed $C_p$, but the kinetic energy $E_[k]$ (instead of $E_k$) and
% the relative permeability $\mu_[r]$ (instead of $\mu_r$). This can be obtained
% in \LaTeX{} with \code{$E_{\mathrm{k}}$} and \code{$\mu_{\mathrm{r}}$}.
% This package allows writing them simply \code{$E_[k]$} and \code{$\mu_[r]$}.
%
% \footnotetext{See, for
% example: International Organization for Standardization. (2009). \emph{Quantities and units -- Part 1: General}
% (ISO Standard No. 80000-1:2009).
% \url{https://www.iso.org/standard/30669.html}.}
%
% \medskip
%
% By default, the upright format is obtained with the command \cs{textnormal},
% from the \pkg{amstext} package (which is loaded by \pkg{amsmath}).
% Unlike \cs{mathrm}, the command \cs{textnormal} handles spaces or non-ASCII
% characters\footnote{See also this answer from Enrico Gregorio, on \TeX{} -- \LaTeX{} Stack Exchange: \url{https://tex.stackexchange.com/a/98407/}}.
%
% \subsection{Modes}
% \label{sec:modes}
%
% The \pkg*{altsubsup} package uses one of these three mechanisms to detect the
% usage of \code{_[...]} or \code{^[...]} in the \LaTeX{} code:
%\begin{itemize}
%  \item hooking into the Lua callback |process_input_buffer|: this is the |lua|
%    mode;
%  \item making active the symbols \code{_} and \code{^}: this is the
%    |active-symbols| mode;
%  \item making active the delimiter \code{[}: this is the |active-delimiters| mode.
% \end{itemize}
%
% The mode can be set, at package loading, with the package option
% \refOpt{mode}. By default, \refOpt{mode} is set to |lua| when the engine is
% \LuaLaTeX{}, and |active-symbols| otherwise.
%
% \subsubsection{\texttt{lua} mode}
%
% With the |lua| \refOpt{mode}, the \pkg*{altsubsup} package uses the
% |process_input_buffer| callback to replace
% \begin{itemize}
%   \item \code{_[} with the command \refCom{altsubsup_alt_subscript:w};
%   \item \code{^[} with the command \refCom{altsubsup_alt_superscript:w}.
% \end{itemize}
% These replacements occur before \TeX{} processing. They are effective
% immediately after the package is loaded, so that commands can internally use
% alternative subscripts or superscripts.
%
% For example, this code works:
% \iffalse
%<*example>
% \fi
\begin{dispListing}
\usepackage{altsubsup}
\newcommand*{\Ek}{E_[k]}
\end{dispListing}
% \iffalse
%</example>
% \fi
% but that code doesn't:
% \iffalse
%<*example>
% \fi
\begin{dispListing}
\newcommand*{\Ek}{E_[k]}
\usepackage{altsubsup}
\end{dispListing}
% \iffalse
%</example>
% \fi
% because the command \cs{Ek} is defined \emph{before} \pkg*{altsubsup}
% package loading.
%
% \medskip
%
% Note that, because the replacement of the sequences \code{_[} and \code{_^}
% occurs before \TeX{} processing, it also happens in |verbatim| environments.
% If needed, disable the \pkg*{altsubsup} functionality with
% \code{\altsubsupset{disable}} before the |verbatim| block, and reactivate it
% afterward using the \refKey{subscripts-and-superscripts} key.
%
% \subsubsection{\texttt{active-symbols} mode}
%
% \label{sec:active-symbols-mode}
%
% \TeX{} assigns to each character a \emph{category code} or \emph{catcode} and a \emph{math code}.
% With the |active-symbols| mode, the catcode and mathcode are modified for the
% symbols circumflex \code{^} and underscore \code{_}\footnotemark{}.
%
% \footnotetext{When the option \refKey{only-subscripts} or
% \refKey{only-superscripts} is used, only the corresponding
% character, the underscore or the circumflex, is altered.}
%
% By default, the circumflex \code{^} has the catcode~7 corresponding to math
% superscript, and the underscore \code{_} has the catcode~8 corresponding to
% math subscript. The \pkg*{altsubsup} package sets the catcode of these two
% symbols to~12, which corresponds to the category \emph{other} used for digits or
% punctuation. It also sets their math code to the special value \code{"8000},
% which is used for characters that are active in math mode. This configuration
% allows the symbols to be treated as macros, and then use an alternative
% formatting if a following square bracket \code{[} is detected.
%
% \medskip
%
% When the \refOpt{mode} is set to |active-symbols|, all changes are applied
% through the hook |begindocument|.
%
%  \medskip
%
%  The alteration of the category code of the \code{_} or \code{^} characters
%  may break some macros that use these symbols as arguments (such as commands
%  created by \cs{NewDocumentCommand} with \texttt{e} or \texttt{E}-type arguments). You can
%  generally fix them with the key \refKey{patch-macro}.
%
%  For example (see also section~\ref{sec:specific-keys:active-symbols}, page~\pageref{sec:specific-keys:active-symbols}), if you define such a command in
%  your preamble:
%  \iffalse
%<*example>
% \fi
\begin{dispListing}
\NewDocumentCommand{\mycmd}{ e{_^} } {%
  \IfValueTF{#1}{\mathcolor{blue}{X_{#1}}}{\mathcolor{red}{X}} /
  \IfValueTF{#2}{\mathcolor{blue}{Y^{#2}}}{\mathcolor{red}{Y}}%
}
\end{dispListing}
% \iffalse
%</example>
% \fi
% \noindent add \code{\altsubsupset{patch-macro=\mycmd}} for the \texttt{e}-type
% argument to work:
% \iffalse
%<*example>
% \fi
\NewDocumentCommand{\mycmd}{ e{_^} } {%
  \IfValueTF{#1}{\mathcolor{blue}{X_{#1}}}{\mathcolor{red}{X}} /
  \IfValueTF{#2}{\mathcolor{blue}{Y^{#2}}}{\mathcolor{red}{Y}}%
}
\UseName{char_set_catcode_other:N} _
\UseName{char_set_catcode_other:N} ^
\begin{dispExample}
Before patching: $ \mycmd \qquad \mycmd_{x} \qquad \mycmd_{x}^{y} $\\[1em]

\altsubsupset{patch-macro=\mycmd}

After patching: $ \mycmd \qquad \mycmd_{x} \qquad \mycmd_{x}^{y} $
\end{dispExample}
\UseName{char_set_catcode_math_subscript:N} _
\UseName{char_set_catcode_math_superscript:N} ^
% \iffalse
%</example>
% \fi
%
% \medskip
%
% The |active-symbols| \refOpt{mode} was the only one available with version~1
% of the \pkg*{altsubsup} package.
%
% \subsubsection{\texttt{active-delimiters} mode}
%
% Version~1 of \pkg*{altsubsup} worked only by making the symbols underscore
% \code{_} and circumflex \code{^} active. This method, corresponding to the \texttt{active-symbols}
% \refOpt{mode} and described in section~\ref{sec:active-symbols-mode}, may generate some issues, for
% example when a circumflex is associated with a prime symbol
% (see section~\ref{sec:issue:double-subscript-error}, page~\pageref{sec:issue:double-subscript-error}) or when a command looks ahead for an underscore \code{_}
% or a circumflex \code{^} symbol (see section~\ref{sec:issue:look-ahead-commands}, page~\pageref{sec:issue:look-ahead-commands}).
%
% Max Chernoff, on \TeX{} -- \LaTeX{} Stack Exchange\footnote{See Max Chernoff's great answer at \url{https://tex.stackexchange.com/a/719150/}.}, suggested another
% approach: instead of making \code{^} and \code{_} active and patching the
% definition of the prime, making the symbol \code{[} math active and have it
% handle everything, without needing to patch any commands or modify any
% other catcodes.
%
% \medskip
%
% This mechanism is used if the \refOpt{mode} is set to |active-delimiters|.
% It fixes all issues that are related to the redefinition of the circumflex
% \code{^} or underscore \code{_} characters.
%
% An important drawback is that great attention must be paid to isolated left
% brackets (not paired with a right bracket). Without protection, one of these
% errors is raised: \emph{Paragraph ended before [ was complete} or \emph{Argument of [ has an extra \}}
% (these messages are listed as known issues in section~\ref{sec:issue:active-bracket}, page~\pageref{sec:issue:active-bracket}).
% To typeset an isolated left bracket, either
% \begin{itemize}
%   \item use the dedicated \refCom{leftbracket} or \refCom{lbrack} commands;
%   \item protect it with \cs{big}, \cs{Big}, \cs{bigg} or \cs{Bigg} (or \cs{left},
%     \cs{bigl}, \cs{Bigl}, \cs{biggl}, \cs{Biggl} and the corresponding closing
%     delimiter);
% \end{itemize}
%
% Examples:
% \iffalse
%<*example>
% \fi
\begin{dispExample}
$ \leftbracket 0, \infty) \qquad
  \lbrack 0, \infty \lbrack \qquad
  \bigl[ 0, \infty \bigr) \qquad
  \left[ 0, \infty \right[ \qquad
  xyz \leftbracket \qquad
  xyz \big[ \qquad
  xyz \left[\right. $
\end{dispExample}
% \iffalse
%</example>
% \fi
%
% \medskip
%
% When the \refOpt{mode} is set to |active-delimiters|, all changes are applied
% through the hook |begindocument|.
%
% \medskip
%
% In fact, the |active-delimiters| \refOpt{mode} affects all contents in
% \cs{scriptstyle} or \cs{scriptscriptstyle}, when written in square brackets:
%\iffalse
%<*example>
% \fi
\edef\standardbracketmathcode{\the\mathcode`[}
\begingroup
\lccode`~=`[
\lowercase{\endgroup
  \def~#1]{%
    \mathchoice
        {\lbrack #1 ]}
        {\lbrack #1 ]}
        { \mathcolor{red}{#1}}
        { \mathcolor{red}{#1}}%
  }%
}%
\mathcode`[="8000
\begin{dispExample}
\altsubsupset{command=\mathcolor{red}}

$ [abcd] \qquad
  { \scriptstyle [abcd] } \qquad
  { \scriptscriptstyle [abcd] } \qquad
  x_{[abcd]} $
\end{dispExample}
\mathcode`[=\standardbracketmathcode\relax
% \iffalse
%</example>
% \fi
% \noindent Use the same tricks as for non-paired brackets, if you need a pair
% of square brackets with \cs{scriptstyle} or \cs{scripscriptstyle}:
% \iffalse
%<*example>
% \fi
\begin{dispExample}
$ [abcd] \qquad
  { \scriptstyle \lbrack abcd ] } \qquad
  { \scriptscriptstyle \leftbracket abcd ] } \qquad
  x_{\left[ abcd \right]} $
\end{dispExample}
\mathcode`[=\standardbracketmathcode\relax
% \iffalse
%</example>
% \fi
%
%\medskip
%
% The |active-delimiters| \refOpt{mode} was implemented in a very flexible way:
% it's also possible to define new active delimiters, and assign a different
% setting to each.
%
% Example (see also section~\ref{sec:specific-keys:active-delimiters}, page~\pageref{sec:specific-keys:active-delimiters}):
% \iffalse
%<*example>
% \fi
\begin{dispExample}
\altsubsupset {
  new-delimiters = {!! = {command=\mathbf}},
  define-letter-command = {\bang=!}
}

$ x^{ab, c}_{de, f} \qquad x^[ab, c]_[de, f] \qquad x^!ab, c!_!de, f! ~\bang $
\end{dispExample}
% \iffalse
%</example>
% \fi
%
% \subsection{Default settings}
%
% By default, both superscripts and subscripts are handled. When a square
% bracket \code{[} follows the symbol circumflex \code{^} or underscore
% \code{_}, the content is typeset with the \cs{textnormal} command
% ^^A\footnote{This choice is motivated by this answer from Enrico Gregorio: \url{https://tex.stackexchange.com/a/98407/}.}
% from the \href{https://ctan.org/pkg/amstext}{\pkg{amstext}} package (loaded by
% \href{https://ctan.org/pkg/amsmath}{\pkg{amsmath}}).
%
% \tcbdocmarginnote{\tcbdocupdated{2026-11-29, v2.0}}
% Note that version~1 of \pkg*{altsubsup} used the \cs{text}
% command by default instead of \cs{textnormal}. However, content typeset with \cs{text}
% depends on the surrounding text font, which is why \cs{textnormal}
% is preferable.
%
% \medskip
%
% The \refOpt{mode} is set to |lua| if the engine is \LuaLaTeX{},
% |active-symbols| otherwise.
%
% \section{User interface}
%
% \subsection{Package options}
%
% \begin{docOption}[%
%   doc description = {default: |lua| with \LuaLaTeX{}, |active-symbols| otherwise},
%   doc parameter = {=lua\textbar{}active-symbols\textbar{}active-delimiters\textbar{}nolua},
%   before lower = {\bigskip},
%   ]
%   {mode}
%
%   Set the mechanism used by the \pkg*{altsubsup} package. The different modes
%   are described in section~\ref{sec:modes}, page~\pageref{sec:modes}. The mode |nolua| is equivalent to
%   |active-symbols|.
%
%   This option is only available at package loading (it can't be set with
%   \refCom{altsubsupset}). Example:
% \iffalse
%<*example>
% \fi
\begin{dispListing}
\usepackage[mode=active-delimiters]{altsubsup}
\end{dispListing}
% \iffalse
%</example>
% \fi
% \end{docOption}
%
% \begin{docOption}[%
%   ]
%   {nolua}
%
%   Set |mode = nolua|. This is a shorthand.
% \end{docOption}
%
% \subsection{Keys}
%
% \subsubsection{Alternative format setting}
%
% \begin{docKeys}
%   {
%     {
%       doc name = {command},
%       doc description = {no default},
%       doc parameter eq meta = cmd,
%     },
%     {
%       doc name = {subscript-command},
%       doc description = {no default},
%       doc parameter eq meta = cmd,
%     },
%     {
%       doc name = {superscript-command},
%       doc description = {no default},
%       doc parameter eq meta = cmd,
%     },
%     {
%       doc name = {put-left},
%       doc description = {no default},
%       doc parameter eq meta = code,
%     },
%     {
%       doc name = {subscript-put-left},
%       doc description = {no default},
%       doc parameter eq meta = code,
%     },
%     {
%       doc name = {superscript-put-left},
%       doc description = {no default},
%       doc parameter eq meta = code,
%     },
%   }
%
%   Set the alternative format used when subscripts or superscripts are written
%   with square brackets.
%
%   With the |command| keys, the script content is formatted by the command
%   \meta{cmd}. With the |put-left| keys, the code \meta{code} is appended
%   before the script content.
%
%   The \refOpt{mode} |active-delimiters| can't distinguish subscripts and
%   superscripts. When this mode is selected, only the settings |command| and
%   |put-left| are available.
%
%\iffalse
%<*example>
% \fi
\begin{dispExample}
\altsubsupset{
  subscript-command = \mathcolor{red},
  superscript-put-left = \mathcolor{blue}{\boldsymbol{\star}}
}

$ x^{ab, c}_{de, f} \qquad x^[ab, c]_[de, f] $
\end{dispExample}
% \iffalse
%</example>
% \fi
%
% \end{docKeys}
%
% \subsubsection{Script selection}
%
% \begin{docKeys}
%   {
%     {
%       doc name = {only-subscripts},
%     },
%     {
%       doc name = {subscript},
%     },
%     {
%       doc name = {only-superscripts},
%     },
%     {
%       doc name = {superscript},
%     },
%     {
%       doc name = {subscripts-and-superscripts},
%     },
%     {
%       doc name = {both},
%     },
%     {
%       doc name = {disable},
%     },
%   }
%
%     Activate or disable the functionalities of the \pkg*{altsubsup} package for
%     subscripts, superscripts or for both.
%
%     |subscript|, |superscript| and |both| are aliases for, respectively,
%     |only-subscripts|, |only-superscripts| and |subscripts-and-superscripts|.
%     To ensure compatibility with version~1 of \pkg*{altsubsup}, these keys can
%     also be used as package options.
%
%     Non-Lua modes have some limitations:
%   \begin{itemize}
%   \item with \refOpt*{mode}|=active-symbols|, the settings have to be made in the
%   preamble, before |\begin{document}| ^^A dummy \end{document}
%       and the key \refKey*{disable} is unavailable;
%   \item  with \refOpt*{mode}|=active-delimiters|, the package can't distinguish
%   subscripts and superscripts: the keys \refKey*{only-subscripts}
%       and \refKey*{only-superscripts} are unavailable.
%   \end{itemize}
%
%\iffalse
%<*example>
% \fi
\altsubsupset{only-subscripts}
\begin{dispExample}
\altsubsupset{only-subscripts}

$ x^{ab, c}_{de, f} \qquad x^[ab, c]_[de, f] $
\end{dispExample}
\altsubsupset{subscripts-and-superscripts}
% \iffalse
%</example>
% \fi
%
% \end{docKeys}
%
% \subsubsection{Keys specific to the \texttt{active-symbols} mode}
%
% \label{sec:specific-keys:active-symbols}
%
% The following keys are only defined when the \refOpt{mode} is set to
% |active-symbols|.
%
% \begin{docKeys}
%   {
%     {
%       doc name = {no-catcode-warnings},
%       doc description = {default: |true|, initially |false|},
%       doc parameter = {=true\textbar{}false},
%     },
%   }
%
%     Do not show a warning if the symbols underscore \code{_} and circumflex
%     \code{^} do not have their standard catcodes (respectively 8 and 7) before
%     \pkg*{altsubsup} sets them to 12.
%
% \end{docKeys}
%
% \begin{docKeys}
%   {
%     {
%       doc name = {patch-macro},
%       doc description = {no default},
%       doc parameter eq meta = {list of macros},
%     },
%   }
%     Try to patch a macro that looks ahead for an underscore \code{_} or
%     a circumflex \code{^} with their new catcodes. \meta{list of macros} is
%     a single macro or a comma-separated list of macros.
%
%     Some commands can change their behavior when an underscore \code{_} or
%     a circumflex \code{^} follows (such as commands created with
%     \cs{NewDocumentCommand} and \texttt{e} or \texttt{E}-type arguments).
%     This mechanism is generally broken when the catcode of these symbols has
%     been modified, as \pkg*{altsubsup} does when the |active-symbols|
%     \refOpt{mode} is selected.
%
%     \refKey*{patch-macro} modifies the catcode of the symbols \code{_} and
%     \code{^} in the definition of macros. This works only for
%     macros without arguments or macros created with \cs{NewDocumentCommand}
%     (which, formally, do not grab any arguments).
%
%     This works, for example, with the commands \cs{odv} and \cs{pdv} defined
%     by the \pkg{derivative} package\footnote{\url{https://ctan.org/pkg/derivative}.}:
%
%\iffalse
%<*example>
% ^^A As DocStrip strip percent chars, use another char § for comments, but
% ^^A hide it in the code. As there is only one literate setting for
% ^^A listing, we need to add also \$, \&, \}, \{ and \\.
% \fi
\UseName{char_set_catcode_other:N} _
\UseName{char_set_catcode_other:N} ^
\begin{dispExample*}{
    before lower={\UseName{char_set_catcode_comment:N} §},
    documentation listing style = {
      lstaltsbspdoc,
      literate = {§ }{{}}0
                 {\$}{{\textcolor{red}{\$}}}{1}
                 {\&}{{\textcolor{red}{\&}}}{1}
                 {\}}{{\textcolor{darkgray}{\}}}}{1}
                 {\{}{{\textcolor{darkgray}{\{}}}{1}
                 {\\\\}{{\textcolor{red}{\textbackslash\textbackslash}}}{2}
    }
}
% § \odv and \pdf are defined with \usepackage{derivative}
Before patching:\\[1ex]
$ \odv{f}{x}_{a}^{b} \qquad \pdv{f}{x}_{a}^{b} $\\[1em]

\altsubsupset{patch-macro={\odv, \pdv}}

After patching:\\[1ex]
$ \odv{f}{x}_{a}^{b} \qquad \pdv{f}{x}_{a}^{b} $
\end{dispExample*}
\UseName{char_set_catcode_math_subscript:N} _
\UseName{char_set_catcode_math_superscript:N} ^
% \iffalse
%</example>
% \fi
%
% \end{docKeys}
%
% \subsubsection{Keys specific to the \texttt{active-delimiters} mode}
%
% \label{sec:specific-keys:active-delimiters}
%
% The |active-delimiters| \refOpt{mode} is implemented in a very flexible way,
% so that it is possible to define new active delimiters and separately manage
% the settings of each delimiter pair.
%
% \medskip
%
% The following keys are only defined when the \refOpt{mode} is set to
% |active-delimiters|.
%
% \begin{docKeys}
%   {
%     {
%       doc name = {enable},
%     },
%     {
%       doc name = {disable},
%       doc label = {active-delimiters:disable},
%     },
%   }
%     Enable or disable the active delimiter pair \code{[]}.
%
%     These keys are simple wrappers for the keys |[]/enable| and |[]/disable|
%     (see \refKey{delimiters/enable} and \refKey{delimiters/disable}).
%
%\iffalse
%<*example>
% \fi
\altsubsupset{disable}
\begin{dispExample}
\altsubsupset{disable}

$ x^{ab, c}_{de, f} \qquad x^[ab, c]_[de, f] $\\[1em]

\altsubsupset{enable}

$ x^{ab, c}_{de, f} \qquad x^[ab, c]_[de, f] $
\end{dispExample}
\altsubsupset{enable}
% \iffalse
%</example>
% \fi
% \end{docKeys}
%
%
%
% \begin{docKeys}
%   {
%     {
%       doc name = {new-delimiters},
%       doc description = {no default},
%       doc parameter = {=\{\meta{delimiters}=\meta{settings}\}},
%     },
%   }
%     Define the new active delimiter pair \meta{delimiters} with the settings
%     \meta{settings}.
%
%     The settings \meta{settings} are optional and consist of a comma-separated
%     list of |command|, |put-left|, |enable| or |disable| keys documented
%     below. Several delimiter pairs can be defined at once, separated by
%     commas. It's impossible to define multiple delimiter pairs beginning with
%     the same symbol.
%
%     The first symbol of the delimiter pair \meta{delimiters} is made active
%     and will raise errors if used alone. Use \refKey{define-letter-command} to
%     define a replacement macro.
%
%\iffalse
%<*example>
% \fi
\begin{dispExample}
\altsubsupset {
  new-delimiters = {
    <> = {put-left = {\mathcolor{red}{\rightarrow}}},
    // = {command = {\mathcolor{blue}}}
  },
}
$ x^<ab, c>_<de, f> \qquad x^/ab, c/_/de, f/ $
\end{dispExample}
% \iffalse
%</example>
% \fi
%
% \end{docKeys}
%
% \begin{docKeys}
%   {
%     {
%       doc name = {define-letter-command},
%       doc description = {no default},
%       doc parameter = {=\{\meta{cmd}=\meta{delimiter}\}},
%     },
%   }
%
%     Define the command \meta{cmd} to typeset the delimiter \meta{delimiter}.
%
%\iffalse
%<*example>
% \fi
\begin{dispExample}
\altsubsupset {
  define-letter-command = {
    \mybracket = [,
    \myless = <,
    \myslash = /
  }
}

Use letter commands for unpaired delimiters:\\
$\mybracket$ \qquad $\myless$ \qquad $\myslash$
\end{dispExample}
% \iffalse
%</example>
% \fi
%
% \end{docKeys}
%
% \begin{docKeys}
%   {
%     {
%       doc name        = {\meta{delimiters}/command},
%       doc label       = delimiters/command,
%       doc index       = delimiters/command,
%       doc sort index  = delimiters/command,
%       doc description = {no default},
%       doc parameter   = {=\meta{cmd}},
%     },
%     {
%       doc name        = {\meta{delimiters}/put-left},
%       doc label       = delimiters/put-left,
%       doc index       = delimiters/put-left,
%       doc sort index  = delimiters/put-left,
%       doc description = {no default},
%       doc parameter   = {=\meta{code}},
%     },
%     {
%       doc name        = {\meta{delimiters}/enable},
%       doc label       = delimiters/enable,
%       doc index       = delimiters/enable,
%       doc sort index  = delimiters/enable,
%     },
%     {
%       doc name        = {\meta{delimiters}/disable},
%       doc label       = delimiters/disable,
%       doc index       = delimiters/disable,
%       doc sort index  = delimiters/disable,
%     },
%   }
%     Configure the active delimiter pair \meta{delimiters} previously declared with
%     \refKey{new-delimiters}.
%
%\iffalse
%<*example>
% \fi
\altsubsupset{
  ,<> / enable
  ,// / enable
}
\begin{dispExample}
$ x^<ab, c>_<de, f> \qquad x^/ab, c/_/de, f/ $\\[1em]

\altsubsupset{
  <> / command = \mathcolor{red},
  // / disable
}

$ x^<ab, c>_<de, f> \qquad x^/ab, c/_/de, f/ $
\end{dispExample}
\altsubsupset{
  ,<> / disable
  ,// / disable
}
% \iffalse
%</example>
% \fi
%
% \end{docKeys}
%
%
% \subsubsection{Interface with the \texorpdfstring{\pkg*{spbmark}}{spbmark} package}
%
% The \pkg{spbmark} package, by Qu Yi, allows complete customization of
% subscripts and superscripts. The key \refKey{spbmark} activates for
% \pkg*{altsubsup} an interface with this package.
%
% Note that the key \refKey{spbmark} is not available when the \refOpt{mode} is
% set to |active-delimiters|.
%
% \medskip
%
% After the \refKey{spbmark} key has been used, the keys
% \refKey{spbmark-subscript-style}, \refKey{spbmark-superscript-style} and
% \refKey{spbmark-style} set the \pkg*{sbpmark} styles used when the subscript
% or the superscript is written in square brackets. Subscripts are typeset by
% the
% \pkg*{spbmark} \cs{sub} macro and superscripts by the \pkg*{spbmark}
% \cs{super} macro. By default, the |spbmark| style used is called |altsub| for
% subscripts and |altsup| for superscripts.
%
% A limitation is the bad alignment generated when a subscript and a superscript
% are used simultaneously (the \pkg*{spbmark} macro for this is \cs{supersub}).
% For example, \code{x_[sub]^[super]}
% gives $x\sub{\text{sub}}\super{\text{super}}$ instead of $x_[sub]^[super]$.
%
% \medskip
%
% \tcbdocmarginnote{\tcbdocupdated{2026-11-29, v2.0}}
% The implementation of the \pkg*{spbmark} interface has evolved between
% versions~1 and~2 of \pkg*{altsubsup}:
% \begin{itemize}
%   \item With version~1, the \pkg*{spbmark} styles were used in addition to the
%     \pkg*{altsubsup} command. By default, the styles were created empty and
%     the \pkg*{altsubsup} command was \cs{text}.
%   \item Since version~2, all the formatting is done by \pkg*{spbmark}
%     styles. The default styles use the command \cs{textnormal}. It's also
%     possible to switch from the default \pkg*{spbmark} styles to others and
%     from the standard implementation to the \pkg*{spbmark} mechanism and
%     vice versa.
% \end{itemize}
%
% \begin{docKeys}
%   {
%     {
%       doc name = {spbmark},
%     },
%   }
%     Activate the \pkg*{altsubsup} interface with \pkg{spbmark} package.
%
%     This loads the \pkg*{spbmark} package and defines the default styles
%     |altsub| and |altsup| together with the keys
%     \refKey{spbmark-subscript-style}, \refKey{spbmark-superscript-style} and
%     \refKey{spbmark-style}. By default, scripts are typeset with the
%     \cs{textnormal} command.
%
%     This key is only accessible in the preamble and should not be used after
%     \code{\begin{document}}.% ^^A dummy \end{document}
%
%     To ensure compatibility with version~1 of the \pkg*{altsubsup}
%     package, this key can also be used as a package option.
% \end{docKeys}
%
% \begin{docKeys}
%   {
%     {
%       doc name = {spbmark-subscript-style},
%       doc parameter = {=\meta{style}},
%       doc description = {no default},
%     },
%     {
%       doc name = {spbmark-superscript-style},
%       doc parameter = {=\meta{style}},
%       doc description = {no default},
%     },
%     {
%       doc name = {spbmark-style},
%       doc parameter = {=\meta{style}},
%       doc description = {no default},
%     },
%   }
%     Set the \pkg*{spbmark} style used for subscripts, superscripts or for both
%     and activate the |spbmark| mechanism. The styles are defined with the
%     command \cs{defspbstyle} provided by the \pkg*{spbmark} package.
%
% \iffalse
%<*example>
% \fi
\begin{dispExample}
\defspbstyle{style1}{cmd=\color{blue}}
\defspbstyle{style2}{cmd=\color{red}}

\altsubsupset{spbmark-style = style1}
$ x^{ab, c} \qquad x_{de, f} \qquad x^[ab, c] \qquad x_[de, f] $\\[1em]

\altsubsupset{command = \mathbf}
$ x^{ab, c} \qquad x_{de, f} \qquad x^[ab, c] \qquad x_[de, f] $\\[1em]

\altsubsupset{spbmark-style = style2}
$ x^{ab, c} \qquad x_{de, f} \qquad x^[ab, c] \qquad x_[de, f] $
\end{dispExample}
% \iffalse
%</example>
% \fi
% \end{docKeys}
%
% \subsection{Commands}
%
% \subsubsection{Setting keys}
%
% \begin{docCommands}{%
%   {
%       doc name=altsubsupset,
%       doc parameter=\marg{option list},
%   },
% }
%   Set \pkg*{altsubsup} keys.
%
%   This is equivalent to \cs{SetKeys} |[altsubsup]| \marg{option list}.
% \end{docCommands}
%
% \subsubsection{Commands specific to the \texttt{active-delimiters} mode}
%
% \begin{docCommands}{%
%   {
%       doc name=lbrack,
%   },
%   {
%       doc name=leftbracket,
%   },
% }
%   Typeset a left bracket \code{[}. These commands are useful in situations
%   where the open bracket is active and not associated with a right bracket.
%
%   The \LaTeX{} command \refCom*{lbrack} is redefined at package loading (but
%   may be redefined later by other packages, such as \pkg{unicode-math}, that
%   make their settings through the hook |begindocument|).
%
%   The command \refCom*{leftbracket} is defined only if it does not already
%   exist (it is defined with \cs{ProvideDocumentCommand}).
%
%   These commands are unexpandable.
% \end{docCommands}
%
% \subsubsection{Deprecated commands}
%
% \begin{docCommands}{%
%   {
%       doc name=SetAltSubscriptCommand,
%       doc parameter=\marg{command},
%   },
%   {
%     doc name=SetAltSubscriptCommand*,
%     doc parameter=\marg{code},
%   },
%   {
%     doc name=SetAltSuperscriptCommand,
%     doc parameter=\marg{command},
%   },
%   {
%     doc name=SetAltSuperscriptCommand*,
%     doc parameter=\marg{code},
%   },
%   {
%     doc name=SetAltSubSupCommands,
%     doc parameter=\marg{command},
%   },
%   {
%     doc name=SetAltSubSupCommands*,
%     doc parameter=\marg{code},
%   },
% }
%   \tcbdocmarginnote{Deprecated (legacy)}
%   Set the format used for the alternative form of subscript or superscript,
%   when written with square brackets.
%
%   These commands are simply wrappers to the keys \refKey{subscript-command},
%   \refKey{superscript-command} and \refKey{command} (commands without star) or
%   \refKey{subscript-put-left}, \refKey{superscript-put-left} and
%   \refKey{put-left} (commands with star). They are defined for legacy reasons,
%   to ensure compatibility with code written for version~1 of the
%   \pkg*{altsubsup} package. Nowadays, it is recommended to use
%   \refCom{altsubsupset} instead.
% \end{docCommands}
%
% \subsubsection{Public LaTeX3 commands}
%
% Most internal LaTeX3 (or |expl3|) commands are private, but some of them are
% public and can be used safely, if needed.
%
% \enlargethispage{6pt}
%
% \begin{docCommands}{%
%   {
%       doc name=altsubsup_alt_subscript:w,
%   },
%   {
%       doc name=altsubsup_alt_superscript:w,
%   },
% }
%   These two commands hold the definition of the subscript or the superscript
%   commands, when a square bracket follows. They are used when the
%   \refOpt{mode} is set to |lua| or |active-symbols|.
%
%   These commands are expandable.
% \end{docCommands}
%
% \paragraph{Commands specific to the \texttt{active-symbols} mode}
%
% \begin{docCommands}{%
%   {
%       doc name=altsubsup_subscript:w,
%   },
%   {
%       doc name=altsubsup_superscript:w,
%   },
% }
%   These two commands hold the definition of the subscript or the superscript
%   commands when the \refOpt{mode} is set to |active-symbols|.
%
%   These commands are unexpandable.
% \end{docCommands}
%
% \begin{docCommands}{%
%   {
%       doc name=altsubsup_patch_macro_catcodes:N,
%   },
% }
%   This command patches the catcodes of the symbols \code{_} and \code{^} in
%   the definition of a command. It is used by \refKey{patch-macro}.
%
%   This command is unexpandable.
% \end{docCommands}
%
% \begin{docCommands}{%
%   {
%       doc name=altsubsup_prime:,
%   },
% }
%   This command holds the definition of the prime symbol \code{'} when the
%   \refOpt{mode} is set to |active-symbols|.
%
%   This command is unexpandable.
% \end{docCommands}
%
% \paragraph{Command specific to the \texttt{active-delimiters} mode}
%
% \begin{docCommands}{%
%   {
%       doc name=altsubsup_use_letter:n,
%   },
% }
%   This command inserts the letter corresponding to an active delimiter. It is
%   used by \refKey{define-letter-command}.
%
%   This command is unexpandable.
% \end{docCommands}
%
% \section{Additional information}
%
% \subsection{Known issues}
%
% \subsubsection{\emph{Double subscript error}}
%
% \label{sec:issue:double-subscript-error}
%
% The use of the prime symbol \code{'} can raise the \emph{Double
% superscript} error message. This is normally fixed (\code{x'^2}
% gives $x'^2$ correctly). If needed, enclose the expression with \code{{...}}.
% In particular, \code{x'^[sup]} doesn't work, and should be written:
% \code{{x'}^[sup]}.
%
% \subsubsection{Commands that look ahead}
%
% \label{sec:issue:look-ahead-commands}
%
% Some commands look ahead for an underscore \code{_} or a circumflex \code{^}.
% When the \refOpt{mode} is set to |active-symbols|, the catcode of the two
% symbols is modified and usually such commands fail to identify their presence.
%
% The \pkg*{altsubsup} package provides the key \refKey{patch-macro} to fix
% them. See its documentation or the example given at the end of section \ref{sec:active-symbols-mode}.
%
% \subsubsection{%
%   \emph{Paragraph ended before \dots{} was complete}
%   \texorpdfstring{\newline}{}%
%   or \emph{Argument of \dots{} has an extra \}}%
%   }
%
% \label{sec:issue:active-bracket}
%
% When a left bracket follows an underscore \code{_} or a circumflex \code{^},
% the subscript or the superscript is handled by a command that needs an
% argument closed by a right bracket \code{]}. If the right bracket is missing,
% \TeX{} can't find the end of the command and an error is raised.
%
% \medskip
%
% This is particularly problematic when the \refOpt{mode} is set to
% |active-delimiters|. In this case, the left bracket \code{[} itself is made
% active: it becomes a command that grabs everything until the next right bracket
% \code{]}.
%
% For an isolated left bracket, the right one is missing and an error is raised:
% \emph{Paragraph ended before [ was complete} or \emph{Argument of [ has an
% extra \}}. To avoid it, use the commands \refCom{lbrack} or
% \refCom{leftbracket}.
%
% \subsubsection{Brackets inside subscripts or superscripts}
%
% As \pkg*{altsubsup} package uses commands that look for the \code{[...]}
% pattern, the use of square brackets inside subscripts or superscripts should
% be protected width braces. Example:
% \iffalse
%<*example>
% \fi
\begin{dispExample}
\altsubsupset{command=\mathcolor{red}}

$ x_[{f[0]}] \qquad x^[{f[0]}] $
\end{dispExample}
% \iffalse
%</example>
% \fi
%
% \medskip
%
% With the |active-delimiters| mode, use the commands \refCom{lbrack} or
% \refCom{leftbracket}, or a \cs{left}-\cs{right} pair
% \iffalse
%<*example>
% \fi
\begin{dispExample}
\altsubsupset{command=\mathcolor{red}}

$ x_[{f\lbrack 0 ]}] \qquad x^[{f \left[ 0 \right]}] $
\end{dispExample}
% \iffalse
%</example>
% \fi
%
% \subsection{Alternatives}
%
% \begin{description}
%   \item[\pkg{subtext} package] The \pkg{subtext} package, by Palle J\o{}rgensen, formats \code{_[...]}
%     subscripts with \cs{text}. The \pkg*{altsubsup} package works both for
%     subscripts and superscripts and allows customizing the commands.
% \end{description}
%
% \subsection{Changelog}
%
% \begin{description}
%  \item[v2.0]
% \begin{itemize}
%   \item Complete rewrite using \LaTeX3/|expl3| syntax.
%   \item Add a key-value interface and provide the \refCom{altsubsupset} command.
%   \item Use \cs{textnormal} as default, instead of \cs{text}.
%   \item Add \refOpt{mode} package option.
%   \item Implement the |lua| \refOpt{mode}.
%   \item Implement the |active-delimiters| \refOpt{mode}.
%   \item Provide catcode patching for macros through \refKey{patch-macro}.
%   \item Add warnings for |active-symbols| \refOpt{mode} if the catcodes don't have
%     their standard values before being modified.
%   \item Change \refKey{spbmark} interface.
% \end{itemize}
% \item[v1.1]
% \begin{itemize}
% \item Backup standard subscript \code{_} and superscript \code{^}
%     commands to handle packages that redefine \cs{sb} or \cs{sp} macros, like
%     \pkg{spbmark}.
%   \item Add option \refKey{spbmark} to handle alternative subscript and
%     superscript forms with the \pkg{spbmark} package.
% \end{itemize}
%   \item[v1.0] Initial version.
% \end{description}
%
% \MaybeStop{}
%
% \section{Implementation}
%
% \setlength{\parindent}{0em}
% \setlength{\parskip}{\smallskipamount}
%
%\iffalse
%<*prefix>
% Internal prefix for \pkg{DocStrip}.
%    \begin{macrocode}
%<@@=altsubsup>
%    \end{macrocode}
%</prefix>
%\fi
%
%\iffalse
%<*package>
%\fi
%
% \subsection{File \texttt{altsubsup.sty}}
%
% \changes{v2.0}{2026/11/29}{Reimplement the package with \LaTeX3/expl3 syntax.}
%
% \subsubsection{Messages}
%
%    \begin{macrocode}
\msg_new:nnn { altsubsup } { unknown-choice }
  {
    the ~ choice ~ '#3' ~ is ~ unknown ~ for ~ the ~ option ~ '#1'. ~
    Available ~ values : ~ #2.
  }
%    \end{macrocode}
%
% \subsubsection{Package options}
%
% \paragraph{Variable initialization}
%
%    \begin{macrocode}
\str_new:N   \g@@_mode_str
\bool_new:N  \l@@_subscript_bool
\bool_new:N  \l@@_superscript_bool
\bool_set_true:N \l@@_subscript_bool
\bool_set_true:N \l@@_superscript_bool
\sys_if_engine_luatex:TF
  { \str_gset:Nn  \g@@_mode_str { lua } }
  { \str_gset:Nn  \g@@_mode_str { active-symbols } }
\keys_define:nn { altsubsup }
  {
%    \end{macrocode}
%
% \paragraph{Mode selection}
%
% \changes{v2.0}{2026/11/29}{Add lua and active-delimiters options}
%
%    \begin{macrocode}
    ,mode           .choices:nn =
        { lua, active-symbols, active-delimiters }
        { \str_gset_eq:NN \g@@_mode_str \l_keys_choice_str }
    ,mode           .usage:n    = load
    ,nolua          .meta:n     = { mode = nolua }
    ,mode / nolua   .meta:n     = { mode = active-symbols }
    ,mode / unknown .code:n     =
        \msg_error:nneee { altsubsup } { unknown-choice }
            { mode }
            { lua, ~ nolua, ~ active-symbols, ~ active-delimiters }
            { \exp_not:n {#1} }
%    \end{macrocode}
%
% \paragraph{Scripts selection}
%
% \changes{v2.0}{2026/11/29}{Rename script selection options}
%
%    \begin{macrocode}
    ,only-subscripts             .code:n  =
      {
        \bool_set_true:N  \l@@_subscript_bool
        \bool_set_false:N \l@@_superscript_bool
      }
    ,subscript                   .meta:n  = only-subscripts
    ,only-superscripts           .code:n  =
      {
        \bool_set_false:N \l@@_subscript_bool
        \bool_set_true:N  \l@@_superscript_bool
      }
    ,superscript                 .meta:n  = only-superscripts
    ,subscripts-and-superscripts .code:n  =
      {
        \bool_set_true:N \l@@_subscript_bool
        \bool_set_true:N \l@@_superscript_bool
      }
    ,both                        .meta:n  = subscripts-and-superscripts
%    \end{macrocode}
%
% \paragraph{spbmark option}
%
% \changes{v1.1}{2022/03/15}{Add spbmark option}
%
% If the key is set at package loading, use the |package / altsubsup / after|
% hook to overwrite defaults. If not, the hook is evaluated immediately.
%
%    \begin{macrocode}
    ,spbmark     .code:n =
      {
        \RequirePackage { spbmark }
        \defspbstyle { altsub } { cmd = { \textnormal } }
        \defspbstyle { altsup } { cmd = { \textnormal } }
        \keys_define:nn { altsubsup }
          {
            ,spbmark-subscript-style   .code:n =
              {
                \cs_set:Npn \altsubsup_alt_subscript:w [ ####1 ]
                  { \sub [ style = ##1 ] { ####1 } }
              }
            ,spbmark-superscript-style .code:n =
              {
                \cs_set:Npn \altsubsup_alt_superscript:w [ ####1 ]
                  { \super [ style = ##1 ] { ####1 } }
              }
            ,spbmark-style             .meta:n =
              {
                ,spbmark-subscript-style   = ##1
                ,spbmark-superscript-style = ##1
              }
          }
        \hook_gput_code:nnn { package / altsubsup / after } { . }
          {
            \keys_set:nn { altsubsup }
                {
                  ,spbmark-subscript-style   = { altsub }
                  ,spbmark-superscript-style = { altsup }
                }
          }
      }
    ,spbmark     .usage:n            = preamble
%    \end{macrocode}
%
% \paragraph{Options processing}
%
%    \begin{macrocode}
  }
\ProcessKeyOptions [ altsubsup ]
%    \end{macrocode}
%
% \subsubsection{Mode configuration loading}
%
% For the |lua| mode the changes are applied immediately. The keys used as
% package option for scripts selection are redefined accordingly.
%
% For non-lua modes, the changes are applied through the \code{begindocument}
% hook. Simply load the relevant auxiliary file.
%
%    \begin{macrocode}
\str_if_eq:VnTF \g@@_mode_str { lua }
  {
    \lua_load_module:n { altsubsup }
    \bool_if:NT \l@@_subscript_bool   { \@@_enable_subscript: }
    \bool_if:NT \l@@_superscript_bool { \@@_enable_superscript: }
    \keys_define:nn { altsubsup }
      {
        ,only-subscripts             .code:n  =
          {
            \@@_enable_subscript:
            \@@_disable_superscript:
          }
        ,only-superscripts           .code:n  =
          {
            \@@_disable_subscript:
            \@@_enable_superscript:
          }
        ,subscripts-and-superscripts .code:n  =
          {
            \@@_enable_subscript:
            \@@_enable_superscript:
          }
        ,disable                     .code:n  =
          {
            \@@_disable_subscript:
            \@@_disable_superscript:
          }
      }
  }
  {
    \file_input:n { altsubsup- \g@@_mode_str .code.tex }
  }
%    \end{macrocode}
%
% \subsubsection{User interface}
%
% \paragraph{Keys setting command}
%
% \changes{v2.0}{2026/11/29}{Add keys setting command.}
%
% \begin{macro}{\altsubsupset}
%    \begin{macrocode}
\NewDocumentCommand { \altsubsupset } { m }
  {
    \keys_set:nn { altsubsup } { #1 }
  }
%    \end{macrocode}
% \end{macro}
%
% \paragraph{Alternative form of subscripts and superscripts}
%
% \changes{v2.0}{2026/11/29}{Add a key-value interface.}
%
% Do not define the keys if they have already been defined in the mode sub-file.
%
% \medskip
%
% The commands used to display the alternative form of subscripts or
% superscripts are expandable. They contain an underscore \code{_} or
% a circumflex \code{^} with their standard catcodes (thanks to the expandable
% command \cs{char_generate:nn}). Since they are used directly in the |lua|
% \refOpt{mode}, their current definition is written into the |toc| file, for
% example, if used inside an heading.
%
% In the |active-symbols| \refOpt{mode}, theses commands are internally wrapped
% in \refCom{altsubsup_subscript:w} and \refCom{altsubsup_superscript:w}, which
% are unexpandable. In the |active-delimiters| \refOpt{mode}, they are not used
% at all.
%
%    \begin{macrocode}[literate        = *{\$}{{\textcolor{red}{\$}}}{1}]
\keys_if_exist:nnF { altsubsup } { command }
  {
    \keys_define:nn { altsubsup }
      {
        ,subscript-command    .code:n =
          {
            \cs_set:Npe \altsubsup_alt_subscript:w [ ##1 ]
              {
                \char_generate:nn { `\_ } { 8 } { \exp_not:n { #1 } { ##1 } }
              }
          }
        ,subscript-put-left   .code:n =
          {
            \cs_set:Npe \altsubsup_alt_subscript:w [ ##1 ]
              {
                \char_generate:nn { `\_ } { 8 } { \exp_not:n { #1 } ##1 }
              }
          }
        ,superscript-command  .code:n =
          {
            \cs_set:Npn \altsubsup_alt_superscript:w [ ##1 ]
              {
                \char_generate:nn { `\^ } { 7 } { \exp_not:n { #1 } { ##1 } }
              }
          }
        ,superscript-put-left .code:n =
          {
            \cs_set:Npn \altsubsup_alt_superscript:w [ ##1 ]
              {
                \char_generate:nn { `\^ } { 7 } { \exp_not:n { #1 } ##1 }
              }
          }
        ,command              .meta:n =
          {
            ,subscript-command    = { #1 }
            ,superscript-command  = { #1 }
          }
        ,put-left             .meta:n =
          {
            ,subscript-put-left   = { #1 }
            ,superscript-put-left = { #1 }
          }
      }
  }
%    \end{macrocode}
%
% \changes{v2.0}{2026/11/29}{Add starred versions for the setting commands.}
%
% \begin{macro}{\SetAltSubscriptCommand}
% \begin{macro}{\SetAltSubscriptCommand*}
% \indexmacro{SetAltSubscriptCommand*}
%    \begin{macrocode}
\NewDocumentCommand { \SetAltSubscriptCommand } { s m }
  {
    \IfBooleanTF{ #1 }
      {
        \keys_set:nn { altsubsup } { subscript-put-left = { #2 } }
      }
      {
        \keys_set:nn { altsubsup } { subscript-command = { #2 } }
      }
  }
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\SetAltSuperscriptCommand}
% \begin{macro}{\SetAltSuperscriptCommand*}
% \indexmacro{SetAltSuperscriptCommand*}
%    \begin{macrocode}
\NewDocumentCommand { \SetAltSuperscriptCommand } { s m }
  {
    \IfBooleanTF{ #1 }
      {
        \keys_set:nn { altsubsup } { superscript-put-left = { #2 } }
      }
      {
        \keys_set:nn { altsubsup } { superscript-command = { #2 } }
      }
  }
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\SetAltSubSupCommands}
% \begin{macro}{\SetAltSubSupCommands*}
% \indexmacro{SetAltSubSupCommands*}
%    \begin{macrocode}
\NewDocumentCommand { \SetAltSubSupCommands } { s m }
  {
    \IfBooleanTF{ #1 }
      {
        \keys_set:nn { altsubsup } { put-left = { #2 } }
      }
      {
        \keys_set:nn { altsubsup } { command = { #2 } }
      }
  }
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \subsubsection{Default settings}
%
%\changes{v2.0}{2026/11/29}{Use \cs{textnormal} as default, instead of \cs{text}.}
%
% Use \cs{textnormal} for default, as recommended by Enrico Gregorio on
% \TeX{} -- \LaTeX{} Stack Exchange (see
% \url{https://tex.stackexchange.com/a/98407/}).
%
%    \begin{macrocode}
\RequirePackage { amstext }
\keys_set:nn { altsubsup }
  {
    ,command = { \textnormal }
  }
%    \end{macrocode}
%
%\iffalse
%</package> ^^A End of package implementation.
%\fi
%
%\iffalse
%<*lua>
%\fi
%
% \subsection{File \texttt{altsubsup.lua}}
%
% \changes{v2.0}{2026/11/29}{Add lua implementation.}
%
% \restartlinenumber
%
% \subsubsection{Substitution functions}
%
% Replace
% \begin{itemize}
% \item \code{_[} by \refCom{altsubsup_alt_subscript:w};
% \item \code{^[} by \refCom{altsubsup_alt_superscript:w}.
% \end{itemize}
%
%    \begin{macrocode}[language={[5.3]Lua}]
local SUB_CMD = [[\UseName{altsubsup_alt_subscript:w}[]]
local function dosub_subscript ( s )
   return ( s:gsub("_%[", SUB_CMD) )
end

local SUP_CMD = [[\UseName{altsubsup_alt_superscript:w}[]]
local function dosub_superscript ( s )
   return ( s:gsub("%^%[", SUP_CMD) )
end

%    \end{macrocode}
%
% \subsubsection{Activation functions}
%
% Add the callbacks to \code{process_input_buffer}.
%
%    \begin{macrocode}[language={[5.3]Lua}]
local function enable_subscript ()
    if not luatexbase.in_callback ("process_input_buffer",
            "altsubsup subscript")
    then
        luatexbase.add_to_callback ( "process_input_buffer",
            dosub_subscript, "altsubsup subscript")
    end
end

local function enable_superscript ()
    if not luatexbase.in_callback ("process_input_buffer",
            "altsubsup superscript")
    then
        luatexbase.add_to_callback ( "process_input_buffer",
            dosub_superscript, "altsubsup superscript" )
    end
end

%    \end{macrocode}
%
% Remove the callbacks from \code{process_input_buffer}.
%
%    \begin{macrocode}[language={[5.3]Lua}]
local function disable_subscript ()
    if luatexbase.in_callback ("process_input_buffer",
            "altsubsup subscript")
    then
        luatexbase.remove_from_callback("process_input_buffer",
            "altsubsup subscript")
    end
end

local function disable_superscript ()
    if luatexbase.in_callback ("process_input_buffer",
            "altsubsup superscript")
    then
        luatexbase.remove_from_callback("process_input_buffer",
            "altsubsup superscript")
    end
end

%    \end{macrocode}
%
% \subsubsection{LaTeX interface}
%
% Define the commands
% \begin{itemize}
%   \item \cs{__altsubsup_enable_subscript:};
%   \item \cs{__altsubsup_enable_superscript:}.
% \end{itemize}
%
% \begin{macro}{\__altsubsup_enable_subscript:}
% \begin{macro}{\__altsubsup_enable_superscript:}
%    \begin{macrocode}[language={[5.3]Lua}]
local funid = luatexbase.new_luafunction('@@_enable_subscript:')
lua.get_functions_table()[funid]=enable_subscript
token.set_lua('@@_enable_subscript:', funid)

local funid = luatexbase.new_luafunction('@@_enable_superscript:')
lua.get_functions_table()[funid]=enable_superscript
token.set_lua('@@_enable_superscript:', funid)

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% Define the commands
% \begin{itemize}
% \item \cs{__altsubsup_disable_subscript:};
% \item \cs{__altsubsup_disable_superscript:}.
% \end{itemize}
%
% \begin{macro}{\__altsubsup_disable_subscript:}
% \begin{macro}{\__altsubsup_disable_superscript:}
%    \begin{macrocode}[language={[5.3]Lua}]
local funid = luatexbase.new_luafunction('@@_disable_subscript:')
lua.get_functions_table()[funid]=disable_subscript
token.set_lua('@@_disable_subscript:', funid)

local funid = luatexbase.new_luafunction('@@_disable_superscript:')
lua.get_functions_table()[funid]=disable_superscript
token.set_lua('@@_disable_superscript:', funid)

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%\iffalse
%</lua> ^^A End of lua auxiliary file
%\fi
%
%\iffalse
%<*active-symbols>
%\fi
%
% \subsection{File \texttt{altsubsup-active-symbols.code.tex}}
%
% \restartlinenumber
%
% \subsubsection{Messaging}
%
% \paragraph{Non standard catcode}
%
% \changes{v2.0}{2026/11/29}{Add warnings if symbols don't have their standard catcodes}
%
%    \begin{macrocode}
\msg_new:nnn { altsubsup } { no-standard-catcode }
  {
    the ~ symbol ~ '#1' ~ does ~ not ~ have ~ its ~ standard ~ catcode ~ (#2) ~
    before ~ the ~ package ~ altsubsup ~ modifies ~ it. ~ Something ~ might ~
    go ~ wrong.
  }
%    \end{macrocode}
%
% \changes{v2.0}{2026/11/29}{Add no-catcode-warnings option}
%
%    \begin{macrocode}
\keys_define:nn { altsubsup }
  {
    ,no-catcode-warnings .bool_set_inverse:N = \l@@_warn_catcode_bool
    ,no-catcode-warnings .initial:n          = false
    ,no-catcode-warnings .usage:n            = preamble
  }
%    \end{macrocode}
%
% \paragraph{Unpatchable command}
%
%    \begin{macrocode}
\msg_new:nnnn { altsubsup } { no-patch }
  {
    the ~ macro ~ #1 can't ~ be ~ patched.
  }
  {
    Catcode ~ patching ~ is ~ limited ~ to ~ macros ~ without ~ arguments ~ or ~
    commands ~ created ~ with ~ \token_to_str:N \NewDocumentCommand.
  }
%    \end{macrocode}
%
% \subsubsection{Backup of standard tokens}
%
% \changes{v1.1}{2022/03/15}{Backup standard superscript and superscript commands}
% \changes{v2.0}{2026/11/29}{Replace backups with expl3 generic tokens}
%
% The backup of standard subscript and superscript commands have been replaced
% by the expl3 generic tokens
% \begin{itemize}
% \item \cs{c_math_superscript_token};
% \item \cs{c_math_subscript_token}.
% \end{itemize}
%
% Nothing to do now.
%
% \subsubsection{Redefinition of symbols}
%
% \paragraph{Subscript symbol}
%
% \begin{macro}{\altsubsup_subscript:w}
%    \begin{macrocode}
\cs_new_protected:Npn \altsubsup_subscript:w
  {
    \peek_meaning:NTF [
      {
        \altsubsup_alt_subscript:w
      }
      {
        \c_math_subscript_token
      }
  }
%    \end{macrocode}
% \end{macro}
%
% \paragraph{Superscript symbol}
%
% \begin{macro}{\altsubsup_superscript:w}
%    \begin{macrocode}
\cs_new_protected:Npn \altsubsup_superscript:w
  {
    \peek_meaning:NTF [
      {
        \altsubsup_alt_superscript:w
      }
      {
        \c_math_superscript_token
      }
  }
%    \end{macrocode}
% \end{macro}
%
% \subsubsection{Symbols activation}
%
%    \begin{macrocode}
\keys_define:nn { altsubsup }
  {
    ,only-subscripts             .usage:n = preamble
    ,only-superscripts           .usage:n = preamble
    ,subscripts-and-superscripts .usage:n = preamble
  }
\hook_gput_code:nnn { begindocument } { . }
  {
%    \end{macrocode}
%
% \paragraph{Subscripts}
%
%    \begin{macrocode}
    \bool_if:NT \l@@_subscript_bool
      {
%    \end{macrocode}
%
% The standard catcode of \code{_} is 8 (subscript). Display a warning if it was
% already altered.
%
%    \begin{macrocode}
        \int_compare:nNnF { \char_value_catcode:n { `\_ } } = { 8 }
          {
            \bool_if:NT \l@@_warn_catcode_bool
              {
                \msg_warning:nnnn
                  { altsubsup } { no-standard-catcode } { _ } { 8 }
              }
          }
%    \end{macrocode}
%
% Make \code{_} active in math mode.
%
%    \begin{macrocode}
        \char_set_mathcode:nn { `\_ } { "8000 }
        \char_set_active_eq:NN _ \altsubsup_subscript:w
        \char_set_catcode_other:N _
      }
%    \end{macrocode}
%
% \paragraph{Superscripts}
%
%    \begin{macrocode}
    \bool_if:NT \l@@_superscript_bool
      {
%    \end{macrocode}
%
% The standard catcode of \code{^} is 7 (superscript). Display a warning if it
% was already altered.
%
%    \begin{macrocode}
        \int_compare:nNnF { \char_value_catcode:n { `\^ } } = { 7 }
          {
            \bool_if:NT \l@@_warn_catcode_bool
              {
                \msg_warning:nnnn
                  { altsubsup } { no-standard-catcode } { ^ } { 7 }
              }
          }
%    \end{macrocode}
%
% Make \code{^} active in math mode.
%
%    \begin{macrocode}
        \char_set_mathcode:nn { `\^ } { "8000 }
        \char_set_active_eq:NN ^ \altsubsup_superscript:w
        \char_set_catcode_other:N ^
      }
%    \end{macrocode}
%
% End of \code{begindocument} hook.
%    \begin{macrocode}
  }
%    \end{macrocode}
%
% \subsubsection{Catcode fixes}
%
% \paragraph{Prime symbol}
%
% To handle math expressions with prime and superscript, like \code{x'^2}, the
% prime symbol is usually made active in math mode and looks ahead for
% a \code{^} symbol. This is done by the \cs{pr@m@s} macro, defined in the file
% |latex.ltx|, or by the macro \cs{__um_superscript:n} if the package
% \pkg{unicode-math} is loaded.
%
% We should take care of this, if the category code of \code{^} is altered.
%
% \changes{v2.0}{2026/11/29}{Reimplement prime symbol support}
%
% \begin{macro}{\altsubsup_prime:}
%    \begin{macrocode}
\tl_new:N \g@@_std_prime_tl
\cs_new_protected:Nn \altsubsup_prime:
  {
    \tl_set:Nn \l_tmpa_tl { \g@@_std_prime_tl }
    \peek_analysis_map_inline:n
      {
        \int_case:nnF { ##2 }
          {
            { `' }
            {
              \tl_put_right:Nn \l_tmpa_tl { ' }
            }
            { `\^ }
            {
              \tl_put_right:Nn \l_tmpa_tl { \c_math_superscript_token }
              \peek_analysis_map_break:n { \tl_use:N \l_tmpa_tl }
            }
          }
          {
            \peek_analysis_map_break:n { \tl_use:N \l_tmpa_tl ##1 }
          }
      }
  }
\group_begin:
\char_set_catcode_active:N '
\hook_gput_code:nnn { begindocument } { . }
  {
    \tl_gset_eq:NN \g@@_std_prime_tl '
    \bool_if:NT \l@@_superscript_bool
      { \char_gset_active_eq:NN ' \altsubsup_prime: }
  }
\group_end:
\clist_map_inline:nn
  {
    unicode-math, unicode-math-luatex, unicode-math-xetex,
  }
  { \hook_gset_rule:nnnn { begindocument } { . } { after } { #1 } }
%    \end{macrocode}
% \end{macro}
%
% \paragraph{Patching of macro catcodes}
%
% \changes{v2.0}{2026/11/29}{Support patching of macros catcodes}
%
% Patch command.
%
% \begin{macro}{\altsubsup_patch_macro_catcodes:N}
%    \begin{macrocode}
\cs_new_protected:Nn \altsubsup_patch_macro_catcodes:N
  {
    \hook_gput_code:nnn { begindocument } { . }
      {
        \exp_args:Ne \str_if_empty:nTF { \cs_parameter_spec:N #1 }
          {
            \bool_if:NT \l@@_subscript_bool
              {
                \regex_replace_all:nnN { \cD\_ }{ \cO\_ } #1
              }
            \bool_if:NT \l@@_superscript_bool
              {
                \regex_replace_all:nnN { \cU\^ }{ \cO\^ } #1
              }
          }
          {
            \msg_warning:nnn { altsubsup } { no-patch } { #1 }
          }
      }
  }
%    \end{macrocode}
% \end{macro}
%
% User interface.
%
%    \begin{macrocode}
\keys_define:nn { altsubsup }
  {
    ,patch-macro .code:n =
      {
        \clist_map_function:nN { #1 } \altsubsup_patch_macro_catcodes:N
      }
  }
%    \end{macrocode}
%
%\iffalse
%</active-symbols> ^^A End of active-symbols mode auxiliary file implementation
%\fi
%
%\iffalse
%<*active-delimiters>
%\fi
%
% \subsection{File \texttt{altsubsup-active-delimiters.code.tex}}
%
% \changes{v2.0}{2026/11/29}{Add the implementation of active delimiters mode.}
%
% \restartlinenumber
%
% The mechanism used for active delimiters is an adaptation of an answer from
% Max Chernoff on \TeX{} -- \LaTeX{} Stack Exchange (see
% \url{https://tex.stackexchange.com/a/719150/}).
%
% He gets all the merit. All bugs are mine.
%
% \subsubsection{Messaging}
%
%    \begin{macrocode}
\msg_new:nnn { altsubsup } { key-unavailable }
  {
    with ~ the ~ mode ~ '#1' the ~ key ~ '#2' ~ is ~ not ~ available ~ and ~
    will ~ be ~ ignored.
  }
\msg_new:nnn { altsubsup } { delimiter-already-active }
  {
    the ~ delimiter ~ ' \tl_to_str:n { #1 } ' ~ was ~ already ~ active ~ when ~
    defining ~ the ~ pair ~ ' \tl_to_str:n { #2 } '. ~ The ~  previous ~
    definition ~ is ~ lost.
  }
\msg_new:nnn { altsubsup } { wrong-value }
  {
    wrong ~ value ~ for ~ the ~ key ~ '#1' ~ (read: ~ '#2'). ~ Ignored.
  }
%    \end{macrocode}
%
% Warn if \code{spbmark} was used as package option.
%
%    \begin{macrocode}
\keys_if_exist:nnT { altsubsup } { spbmark-style }
  {
    \msg_warning:nnnn { altsubsup } { key-unavailable }
      { active-delimiters } { spbmark }
  }
%    \end{macrocode}
%
% \subsubsection{Auxiliary private commands}
%
% Define an \textsf{expl3} interface for \cs{mathchardef} (from Enrico Gregorio,
% \url{https://tex.stackexchange.com/a/611898/}).
%
% \begin{macro}{\__altsubsup_mathchardef:Nn}
% \begin{macro}{\__altsubsup_mathchardef:Nc}
%    \begin{macrocode}
\cs_new_protected:Nn \@@_mathchardef:Nn
  {
    \tex_mathchardef:D #1 = #2 \scan_stop:
  }
\cs_generate_variant:Nn \@@_mathchardef:Nn { c }
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% Get the last node type to see if we immediately follow \code{_} or \code{^}.
%
% \begin{macro}{\__altsubsup_check_first:}
%    \begin{macrocode}
\bool_new:N \l@@_first_item_bool
\cs_new_protected:Nn \@@_check_first:
  {
    \exp_after:wN \int_set:Nn
    \exp_after:wN \l_tmpa_int
    \exp_after:wN { \int_use:N \lastnodetype }
    \int_compare:nNnTF { \l_tmpa_int } = { 15 }
      { \bool_set_true:N   \l@@_first_item_bool }
      { \bool_set_false:N  \l@@_first_item_bool }
  }
%    \end{macrocode}
% \end{macro}
%
% Check to see if a prime comes before a superscript (\cs{pr@@@t} places an
% \cs{egroup} before the closing delimiter, so we need to move it to the end, if
% present).
%
% \begin{macro}{\__altsubsup_check_prime:w}
%    \begin{macrocode}
\tl_new:N \l@@_content_tl
\tl_new:N \g@@_after_tl
\cs_new_protected:Npn \@@_check_prime:w #1#2\q_stop:
  {
    \if_catcode:w #1 \c_group_end_token
      \tl_set:Nn \l@@_content_tl { #2 }
      \tl_gset:Nn \g@@_after_tl { #1 }
    \else:
      \tl_set:Nn \l@@_content_tl { #1 #2 }
      \tl_gclear:N \g@@_after_tl
    \fi:
  }
%    \end{macrocode}
% \end{macro}
%
%\subsubsection{Delimiters definition}
%
% Define a new pair of delimiters for alternative subscript and
% superscript forms.
%
% \begin{macro}{\__altsubsup_define_delimiters:nn}
% \begin{macro}{\__altsubsup_define_delimiters:ee}
%    \begin{macrocode}
\cs_new_protected:Nn \@@_define_delimiters:nn
  {
%    \end{macrocode}
%
% Check what to use: the letter or the alternative output.
%
%    \begin{macrocode}
    \cs_set_protected:cpn { @@_active_#1:w } ##1#2
      {
        \exp_after:wN \exp_after:wN \exp_after:wN
        \c_group_begin_token
        \@@_check_first:
        \tl_if_empty:nTF { ##1 }
          {
            \tl_clear:N  \l@@_content_tl
            \tl_gclear:N \g@@_after_tl
            \use:c { @@_use_letter_#1: }
          }
          {
            \@@_check_prime:w ##1 \q_stop:
            \bool_if:NTF \l@@_first_item_bool
              {
                \mathchoice
                  { \use:c { @@_use_letter_#1: } }
                  { \use:c { @@_use_letter_#1: } }
                  { \use:c { @@_use_alternative_#1: } }
                  { \use:c { @@_use_alternative_#1: } }
              }
              { \use:c { @@_use_letter_#1: } }
          }
        \c_group_end_token
        \tl_use:N \g@@_after_tl
      }
%    \end{macrocode}
%
% Check if already defined. If not, save the original math code and make the
% symbol active in math mode.
%
%    \begin{macrocode}
    \cs_if_exist:cTF { @@_use_letter_#1: }
      {
        \msg_warning:nnnn  { altsubsup } { delimiter-already-active }
          { #1 } { #1#2 }
      }
      {
        \hook_gput_code:nnn { begindocument } { . }
          {
            \int_new:c { @@_standard_mathcode_#1_int }
            \int_set:cn
              { @@_standard_mathcode_#1_int }
              { \char_value_mathcode:n { `#1 } }
            \@@_mathchardef:cn
              { @@_letter_#1: }
              { \char_value_mathcode:n { `#1 } }
            \char_set_active_eq:nc { `#1 } { @@_active_#1:w }
          }
        \cs_new_protected:cn { @@_use_letter_#1: }
          {
            \use:c { @@_letter_#1: }
            \tl_use:N \l@@_content_tl
            \cs_if_exist_use:cF { @@_letter_#2: } { #2 }
          }
        \cs_new_eq:cc { @@_use_alternative_#1: } { @@_use_letter_#1: }
      }
%    \end{macrocode}
%
% Key-value interface: alternative output.
%
%    \begin{macrocode}
    \keys_define:nn { altsubsup / #1#2 }
      {
        ,command  .code:n           =
          {
            \cs_set_protected:cpn { @@_use_alternative_#1: }
              { ##1 { \l@@_content_tl } }
          }
        ,command  .value_required:n = true
        ,put-left .code:n           =
          {
            \cs_set_protected:cpn { @@_use_alternative_#1: }
              { ##1 \l@@_content_tl }
          }
        ,put-left .value_required:n = true
%    \end{macrocode}
%
% Key-value interface: enable and disable commands.
%
%    \begin{macrocode}
        ,enable       .code:n           =
          {
            \hook_gput_code:nnn { begindocument } { . }
              {
                \char_set_mathcode:nn { `#1 }
                  {
                    "8000
                  }
              }
          }
        ,disable      .code:n           =
          {
            \hook_gput_code:nnn { begindocument } { . }
              {
                \char_set_mathcode:nn { `#1 }
                  {
                    \int_use:c { @@_standard_mathcode_#1_int }
                  }
              }
          }
      }
%    \end{macrocode}
%
% End of the definition of the new delimiter pair.
%
%    \begin{macrocode}
    \keys_set:nn { altsubsup / #1#2 } { enable }
  }
\cs_generate_variant:Nn \@@_define_delimiters:nn { ee }
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% As \pkg{unicode-math} redefines a lot of things, apply the \code{begindocument}
% hook after it.
%
%    \begin{macrocode}
\clist_map_inline:nn
  {
    unicode-math, unicode-math-luatex, unicode-math-xetex,
  }
  { \hook_gset_rule:nnnn { begindocument } { . } { after } { #1 } }
%    \end{macrocode}
%
% \subsubsection{Public expl3 interface}
%
% \begin{macro}{\altsubsup_use_letter:n}
%    \begin{macrocode}
\cs_new_protected:Nn \altsubsup_use_letter:n
  {
    \cs_if_exist_use:cF { @@_letter_#1: } { #1 }
  }
%    \end{macrocode}
% \end{macro}
%
% \subsubsection{Key-value interface}
%
%    \begin{macrocode}
\keys_define:nn { altsubsup }
  {
    ,new-delimiters           .code:n =
      {
        \keyval_map_inline:nnn { #1 }
          {
            \@@_define_delimiters:ee
              { \tl_head:n { ##1 } } { \tl_tail:n { ##1 } }
          }
          {
            \@@_define_delimiters:ee
              { \tl_head:n { ##1 } } { \tl_tail:n { ##1 } }
            \keys_set:nn { altsubsup / ##1 } { ##2 }
          }
      }
    ,define-letter-command    .code:n =
        {
          \keyval_map_inline:nnn { #1 }
            {
              \msg_warning:nnnn { altsubsup } { wrong-value }
                { define-letter-command } { ##1 }
            }
            {
              \bool_lazy_and:nnTF
                { \tl_if_single_p:n { ##1 } }
                { \tl_if_head_is_N_type_p:n { ##1 } }
                {
                  \cs_set_protected:Npn ##1 { \altsubsup_use_letter:n { ##2 } }
                }
                {
                  \msg_warning:nnnn { altsubsup } { wrong-value }
                    { define-letter-command } { ##1 ~=~ ##2 }
                }
            }
        }
    ,enable               .meta:nn = { altsubsup / [] } { enable }
    ,disable              .meta:nn = { altsubsup / [] } { disable }
    ,command              .meta:nn = { altsubsup / [] } { command = #1 }
    ,put-left             .meta:nn = { altsubsup / [] } { put-left = #1 }
    ,subscript-command    .code:n  =
      {
        \msg_warning:nnnn { altsubsup } { key-unavailable }
          { active-delimiters } { subscript-command }
      }
    ,superscript-command  .code:n  =
      {
        \msg_warning:nnnn { altsubsup } { key-unavailable }
          { active-delimiters } { superscript-command }
      }
    ,subscript-put-left   .code:n  =
      {
        \msg_warning:nnnn { altsubsup } { key-unavailable }
          { active-delimiters } { subscript-put-left }
      }
    ,superscript-put-left .code:n  =
      {
        \msg_warning:nnnn { altsubsup } { key-unavailable }
          { active-delimiters } { superscript-put-left }
      }
    ,spbmark              .code:n  =
      {
        \msg_warning:nnnn { altsubsup } { key-unavailable }
          { active-delimiters } { spbmark }
      }
  }
%    \end{macrocode}
%
% \subsubsection{Activation of square brackets}
%
%    \begin{macrocode}
\@@_define_delimiters:nn { [ } { ] }
%    \end{macrocode}
%
% Provides user access to the left bracket: define the command \cs{leftbracket}
% and redefine \cs{lbrack} (but this is overwritten by \pkg{unicode-math}, if
% loaded).
%
% \begin{macro}{\leftbracket}
% \begin{macro}{\lbrack}
%    \begin{macrocode}
\ProvideDocumentCommand { \leftbracket } { } { \altsubsup_use_letter:n { [ } }
\cs_set_protected:Npn \lbrack { \altsubsup_use_letter:n { [ } }
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%\iffalse
%</active-delimiters> ^^A End of active-delimiters mode auxiliary file implementation
%\fi
%
% \iffalse ^^A The following is not for the doc
%<*docstyle>
%
% \section{altsubsup-doc package}
%
% The following defines some styles used for documentation and should not be
% included in the documentation itself.
%
% \subsection*{Packages}
%
%    \begin{macrocode}
\RequirePackage{xcolor}
\PassOptionsToPackage{hyperref}{xcolor}
\RequirePackage[many]{tcolorbox}
\tcbuselibrary{listings}
\tcbuselibrary{documentation}
\hypersetup{hidelinks}
%    \end{macrocode}
%
% \subsection*{Colors}
%
%    \begin{macrocode}
\definecolor{altsbsp_lavender}{rgb}{0.92,0.92,1}
\definecolor{altsbsp_darkblue}{rgb}{0.1,0.2,0.5}
\definecolor{altsbsp_darkgreen}{rgb}{0,0.39,0}
\definecolor{altsbsp_beige}{rgb}{.96,.96,.86}
\colorlet{altsbsp_commands}{altsbsp_darkblue}
\colorlet{altsbsp_keys}{altsbsp_darkgreen}
\colorlet{altsbsp_lengths}{violet}
\colorlet{altsbsp_options}{Definition} % from tcolorbox documentation
%    \end{macrocode}
%
% \subsection*{listings styles}
%
%    \begin{macrocode}
\lstdefinestyle{lstaltsbspdoc}{%
  language = [LaTeX]TeX
  ,alsoletter      = {_,:*},% for expl3  + starred version
  ,columns         = flexible
  ,keepspaces      = true
  ,keywordstyle    = {\bfseries\color{altsbsp_darkblue}}
%    \end{macrocode}
%
% Usually, it's better to use a star with \code{texcsstyle} to highlight also
% the backslash. But here, this interferes with the pattern |\\UseName| used
% with literate.
%
%    \begin{macrocode}
  ,texcsstyle      = {\bfseries\color{altsbsp_darkblue}}
  ,commentstyle    = {\color{gray}}
  ,identifierstyle = {\color{altsbsp_darkgreen}}
  ,morekeywords    = {}% keywordsprefix needs a morekeywords before
  ,keywordsprefix  = {\\}
%    \end{macrocode}
%
% For literate, the extra braces around the replacement text avoid the error: "Argument of |lst@FillFixed@| has an extra \}."
%
%    \begin{macrocode}
  ,literate        = *{\$}{{\textcolor{red}{\$}}}{1}
                     {\&}{{\textcolor{red}{\&}}}{1}
                     {\}}{{\textcolor{darkgray}{\}}}}{1}
                     {\{}{{\textcolor{darkgray}{\{}}}{1}
                     {\\\\}{{\textcolor{red}{\textbackslash\textbackslash}}}{2}
%    \end{macrocode}
%
% Handle replacements made by lua \code{process_input_buffer} callbacks.
%
%    \begin{macrocode}
                     {\\UseName\{altsubsup_alt_subscript:w\}}{{\_}}{1}
                     {\\UseName\{altsubsup_alt_superscript:w\}}{{\textasciicircum}}{1}
%    \end{macrocode}
%
% One \% and four spaces to remove extra lines added by \cs{macrocode}
%
%    \end{macrocode}
                     {\%\ \ \ \ }{}0
  ,basicstyle      = \ttfamily\footnotesize
  ,frame           = none
  ,framesep        = 0pt
  ,aboveskip       = 0pt
  ,belowskip       = 0pt
}
\lstdefinestyle{lstaltsbspcode}{%
  style           = lstaltsbspdoc
  ,backgroundcolor = \color{altsbsp_beige}
  ,breakindent     = 1cm
  ,numbers         = left
  ,numberstyle     = \scriptsize\ttfamily\color{gray}
  ,aboveskip       = \smallskipamount
  ,belowskip       = \smallskipamount
}
%    \end{macrocode}
%
% \subsection*{tcolorbox}
%
%    \begin{macrocode}
\tcbset{% copied and adapted from tcolorbox.doc.s_main.sty
  documentation listing style = lstaltsbspdoc
  ,doc key prefix             =
  ,size                       = small
  % ,verbatim ignore percent
  %% styles
  ,docexample/.style          = {%
    bicolor jigsaw
    ,before skip balanced     = 0.5\baselineskip plus 2\baselineskip
    ,after skip balanced      = 0.5\baselineskip plus 2\baselineskip
    ,fonttitle                = \bfseries
    ,fontlower                = \normalfont
    ,halign lower             = center
    ,colframe                 = altsbsp_darkblue
    ,colback                  = altsbsp_lavender
    ,colbacklower             = white
    ,drop fuzzy shadow
  }
  ,color key                  = altsbsp_keys
  ,color command              = altsbsp_commands
  ,color length               = altsbsp_lengths
  ,doc head key               = {fontlower = \footnotesize, collower = darkgray}
  ,before doc body            = {\parskip = \smallskipamount}
  ,doc raster          = {
    ,raster before skip       = 12pt plus 24pt minus 2.0pt
    ,raster after skip        = 6pt plus 12pt minus 2.0pt
  }
}
%    \end{macrocode}
%
% Inline code
%
%    \begin{macrocode}
\DeclareTotalTCBox{\code}{ v }
  {%
    verbatim
    ,colframe = altsbsp_beige
    ,colback  = altsbsp_beige
    ,sharp corners
    ,size     = tight
    ,left     = 2pt
    ,right    = 2pt
  }
  {%
    \strut\lstinline[%
      basicstyle = \ttfamily\small\color{altsbsp_darkblue}
      ,literate  = {\\UseName\{altsubsup_alt_subscript:w\}}{{\_}}{1}
                   {\\UseName\{altsubsup_alt_superscript:w\}}{{\textasciicircum}}{1}
    ]!#1!%
  }
%    \end{macrocode}
%
% \subsection*{Index}
%
% To deal with internal macros, use '=' as index actual, in place of '@'.
%
%    \begin{macrocode}
\begin{filecontents*}{\jobname.mst}
actual '='
\end{filecontents*}
\tcbset{%
  index actual    = {=}
  ,index colorize = true
  ,index gather all
  ,index format   = pgfsection
}
%    \end{macrocode}
%
% Redefine \cs{tcb@doc@index@pgfsection} to add prologue (adapted from
% tcbdocumentation.code.tex).
%
%    \begin{macrocode}
\def\tcb@doc@index@pgfsection{%
  \def\index@prologue{%
    \section*{\kvtcb@text@index}\addcontentsline{toc}{section}{\kvtcb@text@index}
    {\small%
      Entries listed in the categories ``commands'', ``internal macros'' and
      ``keys'' also include references to package implementation. }
    \bigskip\par\noindent%
  }%
  \tcb@doc@index@pgf@%
}
%    \end{macrocode}
%
% Unset |\lst@UM| before indexing, to deal with comma (avoid |\unhbox \voidb@x
% \kern \z@| in index file, see: \url{https://tex.stackexchange.com/a/510108}).
%
%    \begin{macrocode}
\newcommand{\indexmacro}[1]{%
  \begingroup
  \let\lst@UM\@empty%
  \index{{Commands!#1=\tcbIndexPrintComC {#1}}}%
  \endgroup
}
\newcommand{\indexmacrointernal}[1]{%
  \begingroup
  \let\lst@UM\@empty%
  \index{{Internal macros!#1=\tcbIndexPrintComC {#1}}}%
  \endgroup
}
\newcommand{\indexkey}[1]{%
  \begingroup
  \let\lst@UM\@empty%
  \index{{Keys!#1=\tcbIndexPrintKeyC {#1}}}%
  \endgroup
}
\newcommand{\indexlength}[1]{%
  \begingroup
  \let\lst@UM\@empty%
  \index{{Lengths!#1=\tcbIndexPrintLenC {#1}}}%
  \endgroup
}
%    \end{macrocode}
%
% \subsection*{Redefinition of macrocode environment}
%
%    \begin{macrocode}
\let\macrocode\relax
\lstnewenvironment{macrocode}[1][]{%
  \lstset{%
    name          = macrocode
    ,style        = lstaltsbspcode
    ,showlines    = true
    ,keepspaces   = true
%    \end{macrocode}
%
% Commands and lengths identification and indexing
%
% Note: indexing works badly with inherited styles. It seems that "texcs" and
% "index" keys should be set together.
%
%    \begin{macrocode}
    ,texcs        = [2]{% commands
      altsubsupset
      ,leftbracket
      ,lbrack
      ,SetAltSubscriptCommand
      ,SetAltSuperscriptCommand
      ,SetAltSubSupCommands
      ,SetAltSubscriptCommand*
      ,SetAltSuperscriptCommand*
      ,SetAltSubSupCommands*
      ,altsubsup_alt_subscript:w
      ,altsubsup_alt_superscript:w
      ,altsubsup_patch_macro_catcodes:N
      ,altsubsup_subscript:w
      ,altsubsup_superscript:w
      ,altsubsup_use_letter:n
      ,altsubsup_prime:
    }
    ,index        = [2][texcs2]
    ,indexstyle   = [2]\indexmacro
    ,texcs        = [3]{}% lengths
    ,index        = [3][texcs3]
    ,indexstyle   = [3]\indexlength
%    \end{macrocode}
%
% Internal macros identification and indexing
%
%    \begin{macrocode}
    ,texcs        = [4]{% internal macros (@@@@ → @@ with DocStrip)
      @@@@_check_first:
      ,@@@@_check_prime:w
      ,@@@@_define_delimiters:ee
      ,@@@@_define_delimiters:nn
      ,@@@@_disable_subscript:
      ,@@@@_disable_superscript:
      ,@@@@_enable_subscript:
      ,@@@@_enable_superscript:
      ,@@@@_mathchardef:cn
      ,@@@@_mathchardef:Nn
      ,g@@@@_after_tl
      ,g@@@@_mode_str
      ,g@@@@_std_prime_tl
      ,l@@@@_content_tl
      ,l@@@@_first_item_bool
      ,l@@@@_subscript_bool
      ,l@@@@_superscript_bool
      ,l@@@@_warn_catcode_bool
    }
    ,index        = [4][texcs4]
    ,indexstyle   = [4]\indexmacrointernal
%    \end{macrocode}
%
% Keys identification and indexing ^^A works badly if keys have spaces
%
%    \begin{macrocode}
    ,morekeywords = [2]{%
      both
      ,command
      ,define-letter-command
      ,disable
      ,enable
      ,mode
      ,new-delimiters
      ,no-catcode-warnings
      ,nolua
      ,only-subscripts
      ,only-superscripts
      ,patch-macro
      ,put-left
      ,spbmark
      ,spbmark-style
      ,spbmark-subscript-style
      ,spbmark-superscript-style
      ,subscript
      ,subscript-command
      ,subscript-put-left
      ,subscripts-and-superscripts
      ,superscript
      ,superscript-command
      ,superscript-put-left
    }
    ,index        = [3][keywords2]
    ,indexstyle   = [3]\indexkey
    ,#1
  }
%    \end{macrocode}
%
% Save and restore the line number (not done by environments defined with
% |\lstnewenvironment|, see \url{https://tex.stackexchange.com/a/95048}):
%
%    \begin{macrocode}
  \csname\@lst @SetFirstNumber\endcsname
}{%
  \csname \@lst @SaveFirstNumber\endcsname
}
%    \end{macrocode}
%
% Restart line number.
%
%    \begin{macrocode}
\NewDocumentCommand{\restartlinenumber} { O{1} } {%
  \lstset{firstnumber = #1}%
  \AddToHookNext{env/macrocode/after}{%
    \lstset{firstnumber = auto}%
  }%
}%
%    \end{macrocode}
%
% \subsection*{Redefinition of macro environment}
%
%    \begin{macrocode}
\DeclareDocumentEnvironment{macro}{m}{%
%    \end{macrocode}
%
% Extraction of macro name. Save/restore current \cs{escapechar} in \cs{count@}.
%
%    \begin{macrocode}
 \count@\escapechar \escapechar=-1
 \edef\macroname{\string#1}
 \escapechar\count@
 \marginpar{%
   \parbox{0.88\linewidth}{%
     \scriptsize\flushright\color{darkgray}
     \rlap{%
       \ifcsdef{r@com:\macroname}
         {\refCom*{\macroname}}%
         {\cs{\macroname}}%
    }%
   }%
 }%
}{% end of macro environment
}
%    \end{macrocode}
%
% \subsection*{Documentation styles}
%
% \subsubsection{Paragraph}
%
%    \begin{macrocode}
\RenewDocumentCommand{\paragraph} { m } {%
  \textsf{#1}\qquad%
}
%    \end{macrocode}
%
% \subsubsection*{Tool for references}
%
%    \begin{macrocode}
\def\refDoc#1{\tcb@ref@doc{#1}}
%    \end{macrocode}
%
% \subsubsection*{Package name}
%
%    \begin{macrocode}
\NewDocumentCommand{\pkg}{ s O{#3} m }{%
  \IfBooleanTF {#1}
    {\textsf{#3}}
    {\refPkg[#2]{\textsf{#3}}}%
}
%    \end{macrocode}
%
% \subsubsection*{Redefinition of the \cs{cs} command}
%
% To handle \textsf{expl3} syntax.
%
%    \begin{macrocode}
\ExplSyntaxOn
\cs_new_protected:Nn \altsubsupdoc_cs:n
  {
   \str_set:Nn \l_tmpa_str { #1 }
   \exp_args:Ne \texttt{ \c_backslash_str \str_use:N \l_tmpa_str }
 }
\cs_generate_variant:Nn \altsubsupdoc_cs:n { e }
\RenewDocumentCommand{\cs}{ m }{\altsubsupdoc_cs:e { #1} }
\ExplSyntaxOff
%    \end{macrocode}
%
% \subsubsection*{Package options}
%
% Definition of docOption environment to document package options, like keys.
%
%    \begin{macrocode}
\newrobustcmd{\tcbIndexPrintOptionCA}[1]{% adapted from \tcbIndexPrintKeyCA
  \tcb@Index@Print@CA{#1}{altsbsp_options}{package option}%
}
\newrobustcmd{\tcbIndexPrintOptionC}[1]{% adapted from \tcbIndexPrintKeyCA
  \tcb@Index@Print@C{#1}{altsbsp_options}%
}
\DeclareDocumentEnvironment{docOption}{  >{\TrimSpaces} O{} m }{%
  \begin{docKey*}[]
    [%
      doc name  = {#2},
      doc label = {opt:#2},
      color key = altsbsp_options,
      #1
    ]
    {#2}{}{}%
    \kvtcb@index@command{%
      \kvtcb@doc@sortindex\idx@actual\tcbIndexPrintOptionCA{#2}%
    }%
    \kvtcb@index@command{%
      {Package options}\idx@level\kvtcb@doc@sortindex\idx@actual%
      \tcbIndexPrintOptionC{#2}%
    }%
}{%
  \end{docKey*}%
}
\def\refOpt{\refDoc{key:opt}}
%    \end{macrocode}
%
% \subsubsection*{Lengths}
%
% Definition of docLength environment to document lengths, like commands.
%
%    \begin{macrocode}
\let\tcbdocLength\docLength% save original definition
\DeclareDocumentEnvironment{docLength}{ O{} m }{%
  \begin{docCommand*}[doc name=#2, color command=altsbsp_lengths,#1]{#2}{}
    \protected@edef\@currentlabel{\cs{#2}}%
    \label{len:#2}%
    %% add length index entry (from \docLength original definition)
    \kvtcb@index@command{%
      \kvtcb@doc@sortindex\idx@actual\tcbIndexPrintLenCA{\kvtcb@doc@index}%
    }%
    \kvtcb@index@command{%
      \kvtcb@text@lengths\idx@level\kvtcb@doc@sortindex\idx@actual%
      \tcbIndexPrintLenC{\kvtcb@doc@index}%
    }%
}{%
  \end{docCommand*}%
}
\def\refLen{\refDoc{len}}
%    \end{macrocode}
%
%</docstyle>
%
% \fi %^^A end of \iffalse
%
% \Finale
%
\endinput
