Debian Codegraph @

texmf-dist/source/latex-dev/base/ltcmdhooks.dtx

raw
1 % \iffalse meta-comment
2 %
3 %% From File: ltcmdhooks.dtx
4 %% Copyright (C) 2020-2026
5 %% Frank Mittelbach, Phelype Oleinik, The LaTeX Project
6 %
7 % It may be distributed and/or modified under the conditions of the
8 % LaTeX Project Public License (LPPL), either version 1.3c of this
9 % license or (at your option) any later version. The latest version
10 % of this license is in the file
11 %
12 % https://www.latex-project.org/lppl.txt
13 %
14 %
15 % \fi
16 %
17 % \iffalse
18 %%% From File: lthooks.dtx
19 %
20 %<*driver>
21 % \fi
22 \ProvidesFile{ltcmdhooks.dtx}
23 [2026-03-12 v1.0n LaTeX Kernel (Command hooks)]
24 % \iffalse
25 %
26 \documentclass{l3in2edoc}
27 \GetFileInfo{ltcmdhooks.dtx}
28 % \usepackage{ltcmdhooks}
29 \EnableCrossrefs
30 \CodelineIndex
31 \begin{document}
32 \DocInput{ltcmdhooks.dtx}
33 \end{document}
34 %</driver>
35 %
36 % \fi
37 %
38 %
39 % \providecommand\hook[1]{\texttt{#1}}
40 % \providecommand\fmi[1]{\marginpar{\footnotesize FMi: #1}}
41 % \providecommand\pho[1]{\marginpar{\footnotesize PhO: #1}}
42 % \providecommand\phoinline[1]{\begin{quote}\itshape\footnotesize PhO: #1\end{quote}}
43 %
44 % \title{Hook management for commands\thanks{This file has version
45 % \fileversion\ dated \filedate, \copyright\ \LaTeX\
46 % Project.}}
47 % \author{Frank Mittelbach \and Phelype Oleinik}
48 %
49 % \maketitle
50 %
51 %
52 % \tableofcontents
53 %
54 %
55 % \section{Introduction}
56 %
57 % This file implements generic hooks for (arbitrary) commands.
58 % In theory every command \tn[no-index]{\meta{name}} offers now two
59 % associated hooks to which code can be added using
60 % \tn{AddToHook},\!\footnote{In this documentation, when something is
61 % being said about \tn{AddToHook}, the same will be valid for
62 % \tn{AddToHookWithArguments}, unless that particular paragraph is
63 % highlighting the differences between both. The same is true for
64 % the other hook-related functions and their
65 % \texttt{\ldots WithArguments} counterparts.}
66 % \tn{AddToHookNext}, \tn{AddToHookWithArguments}, and
67 % \tn{AddToHookNextWithArguments}.\footnote{In practice this is not
68 % supported
69 % for all types of commands, see section~\ref{sec:look-ahead} for
70 % the restrictions that apply and what happens if one tries to use
71 % this with commands for which this is not supported.}
72 %
73 % However, this is only true \enquote{in theory}. In practice there
74 % are a number of restrictions that makes it impossible to use such
75 % generic command hooks in a number of cases, so please read all
76 % of section~\ref{sec:restrictions} to understand what may prevent
77 % you from using them successfully.
78 %
79 % The generic command hooks are:
80 % \begin{description}
81 % \item[\hook{cmd/\meta{name}/before}]
82 %
83 % This hook is executed at the very start of the command, right
84 % after its arguments (if any) are parsed. The hook \meta{code}
85 % runs in the command inside a call to \cs{UseHookWithArguments}.
86 % Any code added to this hook using \tn{AddToHookWithArguments}
87 % or \tn{AddToHookNextWithArguments} can access the command's
88 % arguments using |#1|, |#2|, etc., up to the number of arguments
89 % of the command. If \tn{AddToHook} or \tn{AddToHookNext} are
90 % used, the arguments cannot be accessed (see the \pkg{lthooks}
91 % documentation\footnote{\texttt{texdoc lthooks-doc}} on hooks
92 % with arguments).
93 %
94 % \item[\hook{cmd/\meta{name}/after}]
95 %
96 % This hook is similar to \hook{cmd/\meta{name}/before}, but it is
97 % executed at the very end of the command body. This hook is
98 % implemented as a reversed hook.
99 % \end{description}
100 %
101 % The hooks are not physically present before
102 % \verb=\begin{document}=\footnote{More specifically, they are
103 % inserted in the commands after the \hook{begindocument} hook, so
104 % they are also not present while \LaTeX{} is reading the
105 % \texttt{.aux} file.} (i.e., using a command in the preamble
106 % will never execute the hook) and if nobody has declared any code
107 % for them, then they are not added to the command code ever. For
108 % example, if we have the following definition
109 %\begin{verbatim}
110 % \newcommand\foo[2]{Code #1 for #2!}
111 %\end{verbatim}
112 % then executing \verb=\foo{A}{B}= will simply run
113 % \verb*=Code A for B!=
114 % as it was always the case. However, if somebody, somewhere (e.g.,
115 % in a package) adds
116 %\begin{verbatim}
117 % \AddToHook{cmd/foo/before}{<before code>}
118 %\end{verbatim}
119 % then, after |\begin{document}| the definition of \cs[no-index]{foo} will be:
120 %\begin{verbatim}
121 % \renewcommand\foo[2]{%
122 % \UseHookWithArguments{cmd/foo/before}{2}{#1}{#2}%
123 % Code #1 for #2!}
124 %\end{verbatim}
125 % and similarly \verb=\AddToHook{cmd/foo/after}{<after code>}=
126 % alters the definition to
127 %\begin{verbatim}
128 % \renewcommand\foo[2]{%
129 % Code #1 for #2!%
130 % \UseHookWithArguments{cmd/foo/after}{2}{#1}{#2}}
131 %\end{verbatim}
132 %
133 % In other words, the mechanism is similar to what \pkg{etoolbox}
134 % offers with \tn{pretocmd} and \tn{apptocmd} with the important
135 % differences
136 % \begin{itemize}
137 % \item
138 %
139 % that code can be prepended or appended (i.e., added to the
140 % hooks) even if the command itself is not (yet) defined, because the
141 % defining package has not been loaded at this point;
142 %
143 % \item
144 %
145 % and that by using the hook management interface it is now
146 % possible to define how the code chunks added in these places
147 % are ordered, if different packages want to add code at these
148 % points.
149 %
150 % \end{itemize}
151 %
152 %
153 %
154 %
155 % \section{Restrictions and operational details}
156 % \label{sec:restrictions}
157 %
158 % Adding arbitrary material to commands is tricky because most of the
159 % time we do not know what the macro expects as arguments when expanding
160 % and \TeX{} doesn't have a reliable way to see that, so some guesswork
161 % has to be employed.
162 %
163 % We can do this in most cases when commands are defined using
164 % \cs{NewDocumentCommand} or \cs{newcommand} (with a few exceptions).
165 % For commands defined with \tn{def} the situation is less good.
166 % Common cases where the command hooks will not work are:
167 % \begin{itemize}
168 % \item
169 %
170 % Commands that use special catcode settings within their
171 % definition. In that case it is usually not possible to augment the
172 % definition (see~\ref{sec:patching}).
173 %
174 % \item
175 %
176 % If a command is defined while \cs{ExplSyntaxOn} is in force
177 % \textbf{and} the command contains \verb=~= characters to represent
178 % spaces, then it can't be patched to include the command hooks. In
179 % fact in some very special circumstances you might even get a
180 % low-level error rather than the information that the command can't
181 % be patched (see, for example,
182 % \url{https://github.com/latex3/latex2e/issues/1430}.
183 %
184 % \item
185 %
186 % Commands that have arguments as far as the user is concerned
187 % (e.g., \cs{section} or \cs{caption}), but are defined in a way that these
188 % arguments are not read by the user level command but only later
189 % during the processing. In that case the \texttt{after} hook
190 % doesn't work at all. The \text{before} hook only works with
191 % \cs{AddToHook} but not with \cs{AddToHookWithArguments} because the
192 % arguments haven't been read at that point where the hook is
193 % patched in. See
194 % section~\ref{sec:look-ahead}.
195 %
196 %
197 % \item
198 % Adding a specific generic command hook is only attempted once per
199 % command, thus after redefining a command such hooks will no longer
200 % be there and will also not being re-added, see section~\ref{sec:timing}.
201 %
202 % \end{itemize}
203 % All this means that you have to have a good understanding of how
204 % commands are defined when you attempt to make use of such hooks and
205 % something goes wrong.
206 % What can help in that case is to turn on \cs{DebugHooksOn} in which
207 % case you get much more (low-level) details on why something fails and
208 % what was tried to enable the hooks.
209 %
210 %
211 % \subsection{Patching}\label{sec:patching}
212 %
213 % The code here tries to find out if a command was defined with
214 % \tn{newcommand} or \tn{DeclareRobustCommand} or
215 % \tn{NewDocumentCommand}, and if so it \emph{assumes} that the argument
216 % specification of the command is as expected (which is not fail-proof,
217 % if someone redefines the internals of these commands in devious ways,
218 % but is a reasonable assumption).
219 %
220 % If the command is one of the defined types, the code here does a
221 % sandboxed expansion of the command such that it can be redefined again
222 % exactly as before, but with the hook code added.
223 %
224 % If however the command is not a known type (it was defined with
225 % \tn{def}, for example), then the code uses an approach similar to
226 % \pkg{etoolbox}'s \tn{patchcmd} to retokenize the command with the hook
227 % code in place. This procedure, however, is more likely to fail if the
228 % catcode settings are not the same as the ones at the time of command's
229 % definition, so not always adding a hook to a command will work.
230 %
231 % \subsubsection{Timing}\label{sec:timing}
232 %
233 % When \cs{AddToHook} (or its \pkg{expl3} equivalent) is called with
234 % a generic |cmd| hook, say, \hook{cmd/foo/before}, for the first time
235 % (that is, no code was added to that same hook before), in the preamble
236 % of a document, it will store a patch instruction for that command
237 % until |\begin{document}|, and only then all the commands which had
238 % hooks added will be patched in one go. That means that no command in
239 % the preamble will have hooks patched into them.
240 %
241 % At |\begin{document}| all the delayed patches will be executed, and
242 % if the command doesn't exist the code is still added to the hook,
243 % but it will not be executed. After |\begin{document}|, when
244 % \cs{AddToHook} is called with a generic |cmd| hook the first time,
245 % the command will be immediately patched to include the hook, and if
246 % it doesn't exist or if it can't be patched for any reason, an error
247 % is thrown; if \cs{AddToHook} was already used in the preamble no new
248 % patching is attempted.
249 %
250 % This has the consequence that a command defined or redefined after
251 % |\begin{document}| only uses generic |cmd| hook code if
252 % \cs{AddToHook} is called for the first time after the definition is
253 % made, or if the command explicitly uses the generic hook in its
254 % definition by declaring it with \cs{NewHookPair} adding \cs{UseHook} as
255 % part of the code.\footnote{We might change this behavior in the main
256 % document slightly after gaining some usage experience.}
257 %
258 % \subsection{Command copies}
259 %
260 % Once a hook has been added to a command, it will be present in any copies
261 % of that command which are made. For example, if in the preamble we have
262 % \begin{verbatim}
263 % \NewDocumentCommand\foo{}{}
264 % \AddToHook{cmd/foo/after}{1}%
265 % \end{verbatim}
266 % then after |\begin{document}|, any use of \cs{NewCommandCopy} will
267 % include the hook in the copy, for example
268 % \begin{verbatim}
269 % \NewCommandCopy\baz\foo
270 % \end{verbatim}
271 % would include the hook in this copied command.
272 %
273 % \subsection{Grouping}
274 %
275 % Command hooks are intended to be added to document commands, which are
276 % typically defined globally. As such, adding a hook is a global operation,
277 % even if the command was previously only locally-defined. Addition of
278 % material to hooks is also global.
279 %
280 % \subsection{Commands that look ahead}
281 % \label{sec:look-ahead}
282 %
283 % Some commands are defined in different ``steps'' and they look ahead
284 % in the input stream to find more arguments. If you try to add some
285 % code to the \hook{cmd/\meta{name}/after} hook of such command, it will
286 % not work, and it is not possible to detect that programmatically, so
287 % the user has to know (or find out) which commands can or cannot have
288 % hooks attached to them.
289 %
290 % One good example is the \tn{section} command. You can add something
291 % to the \hook{cmd/section/before} hook (but only with \cs{AddToHook}
292 % not \cs{AddToHookWithArguments}),
293 % but if you try to add anything to the \hook{cmd/section/after}
294 % hook, \tn{section} will no longer work at all. That happens because the
295 % \tn{section} macro takes no argument, but instead calls a few
296 % internal \LaTeX{} macros to look for the optional and mandatory
297 % arguments. By adding code to the \hook{cmd/section/after} hook, you
298 % get in the way of that scanning.
299 %
300 % In such a case, where it is known that a specific generic command
301 % hook does not work if code is added to it, the package author can
302 % add a \cs{DisableGenericHook}\footnote{Please use
303 % \cs{DisableGenericHook} if at all, only on hooks that you
304 % \enquote{own}, i.e., for commands your package or class defines and
305 % not second guess whether or not hooks of other packages should get
306 % disabled!} declaration to prevent this from happening in user
307 % documents and thereby avoiding obscure errors.
308 %
309 %
310 % \section{Package author interface}
311 % \label{sec:pkg-author}
312 %
313 % The \hook{cmd} hooks are, by default, available for all commands
314 % that can be patched to add the hooks. For some commands, however,
315 % the very beginning or the very end of the code is not the best place
316 % to put the hooks, for example, if the command looks ahead for
317 % arguments (see section~\ref{sec:look-ahead}).
318 %
319 % If you are a package author and you want to add the hooks to your
320 % own commands in the proper position you can define the command and
321 % manually add the \cs{UseHookWithArguments} calls inside the command in
322 % the proper positions, and manually define the hooks with
323 % \cs{NewHookWithArguments} or \cs{NewReversedHookWithArguments}.
324 % When the hooks are explicitly defined,
325 % patching is not attempted so you can make sure your command works
326 % properly. For example, an (admittedly not really useful) command
327 % that typesets its contents in a framed box with width optionally
328 % given in parentheses:
329 % \begin{verbatim}
330 % \newcommand\fancybox{\@ifnextchar({\@fancybox}{\@fancybox(5cm)}}
331 % \def\@fancybox(#1)#2{\fbox{\parbox{#1}{#2}}}
332 % \end{verbatim}
333 % If you try that definition, then add some code after it with
334 % \begin{verbatim}
335 % \AddToHook{cmd/fancybox/after}{<code>}
336 % \end{verbatim}
337 % and then use the \cs[no-index]{fancybox} command you will see that it
338 % will be completely broken, because the hook will get executed in the
339 % middle of parsing for optional \texttt{(...)} argument.
340 %
341 % If, on the other hand, you want to add hooks to your command you can
342 % do something like:
343 % \begin{verbatim}
344 % \newcommand\fancybox{\@ifnextchar({\@fancybox}{\@fancybox(5cm)}}
345 % \def\@fancybox(#1)#2{\fbox{%
346 % \UseHookWithArguments{cmd/fancybox/before}{2}{#1}{#2}%
347 % \parbox{#1}{#2}%
348 % \UseHookWithArguments{cmd/fancybox/after}{2}{#1}{#2}}}
349 % \NewHookWithArguments{cmd/fancybox/before}{2}
350 % \NewReversedHookWithArguments{cmd/fancybox/after}{2}
351 % \end{verbatim}
352 % then the hooks will be executed where they should and no patching
353 % will be attempted. It is important that the hooks are declared with
354 % \cs{NewHookWithArguments} or \cs{NewReversedHookWithArguments},
355 % otherwise the command hook
356 % code will try to patch the command. Note also that the call to
357 % |\UseHookWithArguments{cmd/fancybox/before}| does not need to be in
358 % the definition of \cs[no-index]{fancybox}, but anywhere it makes sense
359 % to insert it (in this case in the internal
360 % \cs[no-index]{@fancybox}).
361 %
362 % Alternatively, if for whatever reason your command does not support
363 % the generic hooks provided here, you can disable a hook with
364 % \cs{DisableGenericHook}\footnote{Please use \cs{DisableGenericHook} if
365 % at all, only on hooks that you \enquote{own}, i.e., for commands
366 % your package or class defines and not second guess
367 % whether or not hooks of other packages should get disabled!}, so
368 % that when someone tries to add code to it they will get an error.
369 % Or if you don't want the error, you can simply declare the hook with
370 % \cs{NewHook} and never use it.
371 %
372 %
373 % The above approach is useful for really complex commands where for
374 % one or the other reason the hooks can't be placed at the very
375 % beginning and end of the command body and some hand-crafting is
376 % needed. However, in the example above the real (and in fact only)
377 % issue is the cascading argument parsing in the style developed long
378 % ago in \LaTeX~2.09. Thus, a much simpler solution for this case is
379 % to replace it with the modern \cs{NewDocumentCommand} syntax and
380 % define the command as follows:
381 % \begin{verbatim}
382 % \DeclareDocumentCommand\fancybox{D(){5cm}m}{\fbox{\parbox{#1}{#2}}}
383 % \end{verbatim}
384 % If you do that then both hooks automatically work and are patched
385 % into the right places.
386 %
387 % \subsection{Arguments and redefining commands}
388 % \label{sec:redef-warn}
389 %
390 % The code in \pkg{ltcmdhooks} does its best to find out how many
391 % arguments a given command has, and to insert the appropriate call to
392 % \cs{UseHookWithArguments}, so that the arguments seen by the hook are
393 % exactly those grabbed by the command (the hook, after all, is a macro
394 % call, so the arguments have to be placed in the right order, or they
395 % won't match).
396 %
397 % When using the package writer interface, as discussed in
398 % section~\ref{sec:pkg-author}, to change the position of the hooks in
399 % your commands, you are also free to change how the hook code in your
400 % command sees its arguments. When a \hook{cmd} hook is declared with
401 % \cs{NewHook} (or \cs{NewHookWithArguments} or other variations of
402 % that), it loses its \enquote{generic} nature and works as a regular
403 % hook. This means that you may choose to declare it without
404 % arguments regardless if the command takes arguments or not, or
405 % declare it with arguments, even if the command takes none.
406 %
407 % However, this flexibility should not be abused. When using a
408 % nonstandard configuration for the hook arguments, think reasonably:
409 % a user will expect that the argument \verb|#1| in the hook corresponds
410 % to the argument's first argument, and so on. Any other configuration
411 % is likely to cause confusion and, if used, will have to be well
412 % documented.
413 %
414 % This flexibility, however, allows you to \enquote{correct} the
415 % arguments for the hooks. For example, \LaTeX's \cs{refstepcounter}
416 % has a single argument, the name of the counter. The \pkg{cleveref}
417 % package adds an optional argument to \cs{refstepcounter}, making the
418 % name of the counter argument \verb|#2|. If the author of
419 % \pkg{cleveref} wanted, for whatever reason, to add hooks to
420 % \cs{refstepcounter}, to preserve compatibility he could write
421 % something along the lines of:
422 % \begin{verbatim}
423 % \NewHookWithArguments{cmd/refstepcounter/before}{1}
424 % \renewcommand\refstepcounter[2][<default>]{%
425 % \UseHookWithArguments{cmd/refstepcounter/before}{1}{#2}%
426 % <code for \refstepcounter>}
427 % \end{verbatim}
428 % so that the mandatory argument, which is arg \verb|#2| in the
429 % definition, would still be seen as \verb|#1| in the hook code.
430 %
431 % Another possibility would be to place the optional argument as the
432 % second argument for the hook, so that people looking for it would be
433 % able to use it. In either case, it would have to be well documented
434 % to cause as little confusion as possible.
435 %
436 % \MaybeStop{\setlength\IndexMin{200pt} \PrintIndex }
437 %
438 %
439 %
440 % \section{The Implementation}
441 %
442 % \subsection{Execution plan}
443 %
444 % To add |before| and |after| hooks to a command we will need to peek
445 % into the definition of a command, which is always a tricky thing to
446 % do. Some cases are easy because we know how the command was defined,
447 % so we can assume how its \meta{parameter text} looks like (for example
448 % a command defined with \tn{newcommand} may have an optional argument
449 % followed by a run of mandatory arguments), so we can just expand that
450 % command and make it grab |#1|, |#2|, etc.\@ as arguments and
451 % define it all back with the hooks added.
452 %
453 % Life's usually not that easy, so with some commands we can't do that
454 % (a |#1| might as well be |#|$_{12}$|1|$_{12}$ instead of the expected
455 % |#|$_{6}$|1|$_{12}$, for example) so we need to resort to ``patching''
456 % the command: read its \tn{meaning}, and tokenize it again with
457 % \tn{scantokens} and hope for the best.
458 %
459 % So the overall plan is:
460 % \begin{enumerate}
461 % \item
462 % Check if a command is of a known type (that is, defined with
463 % \tn{newcommand}\footnote{It's not always possible to reliably
464 % detect this case because a command defined with no optional
465 % argument is indistinguishable from a \tn{def}ed command.},
466 % \cs[no-index]{DeclareRobustCommand}, or
467 % \cs[no-index]{New(Expandable)DocumentCommand}), and if is, take
468 % appropriate action.
469 % \item
470 % If the command is not a known type, we'll check if the command can
471 % be patched. Two things will prevent a command from being
472 % patched: if it was defined in a nonstandard catcode setting, or
473 % if it is an internal expl3 command with |__|\meta{module} in its
474 % name, in which case we refuse to patch.
475 % \item
476 % If the command was defined in nonstandard catcode settings, we
477 % will try a few standard ones to try our best to carry out the
478 % pathing. If this doesn't help either, the code will give up and
479 % throw an error.
480 % \end{enumerate}
481 %
482 %
483 % \begin{macrocode}
484 %<@@=hook>
485 % \end{macrocode}
486 %
487 % \changes{v1.0b}{2021/05/24}{Use \cs{msg_...} instead of \cs{__kernel_msg...}}
488 % \changes{v1.0j}{2024/04/17}{Use \cs{__kernel_cs_parameter_spec:N} instead
489 % of \cs{cs_argument_spec:N}/\cs{cs_parameter_spec:N}}
490 % \changes{v1.0n}{2026-03-12}{Switch from \texttt{x}- to \texttt{e}-type
491 % expansion in expl3 code}
492 %
493 % \begin{macrocode}
494 %<*2ekernel|latexrelease>
495 \ExplSyntaxOn
496 %<latexrelease>\NewModuleRelease{2021/06/01}{ltcmdhooks}
497 %<latexrelease> {The~hook~management~system~for~commands}
498 % \end{macrocode}
499 %
500 % \subsection{Variables}
501 %
502 % \begin{macro}[int]{\g_hook_patch_action_list_tl}
503 % Pairs of |\if<cmd>..\patch<cmd>| to be used with
504 % \tn{robust@command@act} when looking for a known patching
505 % rule. This token list is exposed because we see some future
506 % applications (with very specialized packages, such as
507 % \pkg{etoolbox} that may want to extend the pairs processed. It is
508 % not meant for general use which is why it is not documented in
509 % the interface documentation above.
510 % \begin{macrocode}
511 \tl_new:N \g_hook_patch_action_list_tl
512 % \end{macrocode}
513 % \end{macro}
514 %
515 % \begin{macro}{\l_@@_patch_num_args_int}
516 % The number of arguments in a macro being patched.
517 % \begin{macrocode}
518 \int_new:N \l_@@_patch_num_args_int
519 % \end{macrocode}
520 % \end{macro}
521 %
522 % \begin{macro}{\l_@@_patch_prefixes_tl}
523 % \begin{macro}{\l_@@_param_text_tl}
524 % \begin{macro}{\l_@@_replace_text_tl}
525 % The prefixes and parameters of the definition for the macro being
526 % patched.
527 % \begin{macrocode}
528 \tl_new:N \l_@@_patch_prefixes_tl
529 \tl_new:N \l_@@_param_text_tl
530 \tl_new:N \l_@@_replace_text_tl
531 % \end{macrocode}
532 % \end{macro}
533 % \end{macro}
534 % \end{macro}
535 %
536 % \begin{macro}{\c_@@_hash_tl,\c_@@_hashes_tl}
537 % Two constant token lists that contain one and two parameter tokens.
538 % \changes{v1.0g}{2023/04/06}
539 % {Rename to \cs{c__hook_hashes_tl} and add \cs{c__hook_hash_tl} (hook-args)}
540 % \begin{macrocode}
541 \tl_const:Nn \c_@@_hash_tl { # }
542 \tl_const:Nn \c_@@_hashes_tl { # # }
543 % \end{macrocode}
544 % \end{macro}
545 %
546 % \begin{macro}{\@@_exp_not:NN}
547 % \begin{macro}{\@@_def_cmd:w}
548 % Two temporary macros that change depending on the macro being
549 % patched.
550 % \begin{macrocode}
551 \cs_new_eq:NN \@@_exp_not:NN ?
552 \cs_new_eq:NN \@@_def_cmd:w ?
553 % \end{macrocode}
554 % \end{macro}
555 % \end{macro}
556 %
557 % \begin{macro}{\q_@@_recursion_tail,\q_@@_recursion_stop}
558 % Internal quarks for recursion: they can't appear in any macro being
559 % patched.
560 % \begin{macrocode}
561 \quark_new:N \q_@@_recursion_tail
562 \quark_new:N \q_@@_recursion_stop
563 % \end{macrocode}
564 % \end{macro}
565 %
566 % \begin{macro}{\g_@@_delayed_patches_prop}
567 % A list containing the patches delayed to |\begin{document}|, so that
568 % patching is not attempted twice.
569 % \begin{macrocode}
570 \prop_new:N \g_@@_delayed_patches_prop
571 % \end{macrocode}
572 % \end{macro}
573 %
574 % \begin{macro}{\@@_patch_debug:e}
575 % A helper for patching debug info.
576 % \begin{macrocode}
577 \cs_new_protected:Npn \@@_patch_debug:e #1
578 { \@@_debug:n { \iow_term:e { [lthooks]~#1 } } }
579 % \end{macrocode}
580 % \end{macro}
581 %
582 % \subsection{Patching or delaying}
583 %
584 % Before |\begin{document}| all patching is delayed.
585 %
586 % \begin{macro}{\@@_try_put_cmd_hook:n,\@@_try_put_cmd_hook:w}
587 % This function is called from within \cs{AddToHook}, when code is
588 % first added to a generic |cmd| hook.
589 % If it is called within in the preamble, it delays the action
590 % until |\begin{document}|;
591 % otherwise it tries to update the hook.
592 % \changes{v1.0d}{2021/08/25}{Simplify generic hook detection}
593 % \begin{macrocode}
594 %<latexrelease>\IncludeInRelease{2024/12/22}{\@@_try_put_cmd_hook:n}%
595 %<latexrelease> {Don't~define~command}
596 \cs_new_protected:Npn \@@_try_put_cmd_hook:n #1
597 { \@@_try_put_cmd_hook:w #1 / / / \s_@@_mark {#1} }
598 \cs_new_protected:Npn \@@_try_put_cmd_hook:w
599 #1 / #2 / #3 / #4 \s_@@_mark #5
600 {
601 \@@_debug:n { \iow_term:n { ->~Adding~cmd~hook~to~'#2'~(#3): } }
602 % \end{macrocode}
603 % \cs{@@_patch_cmd_or_delay:Nnn} expects the command to be patched
604 % as its first argument so we need to construct it from its name
605 % (\texttt{\#2}). However, at this moment it may not exist yet, so
606 % using \cs{cs:w} would incorrectly turn it from
607 % \enquote{undefined} into \cs{relax}. We therefore use the
608 % following curious construction: we start a group and expand out of
609 % it to call \cs{cs:w}. If the command is now changed to \cs{relax}
610 % the \cs{group_end:} will undo that change, but the token is
611 % nevertheless there to be consumed by \cs{@@_patch_cmd_or_delay:Nnn}.
612 % \changes{v1.0k}{2024/12/22}{Avoid defining command while adding a cmd
613 % hook (gh/1591)}
614 % \begin{macrocode}
615 \group_begin:
616 \exp_after:wN
617 \group_end:
618 \exp_after:wN
619 \@@_patch_cmd_or_delay:Nnn
620 \cs:w #2\cs_end:
621 {#2} {#3}
622 }
623 %<latexrelease>\EndIncludeInRelease
624 % \end{macrocode}
625 %
626 % \begin{macrocode}
627 %<latexrelease>\IncludeInRelease{2021/11/15}{\@@_try_put_cmd_hook:n}%
628 %<latexrelease> {Standardise~generic~hook~names}
629 %<latexrelease>\cs_new_protected:Npn \@@_try_put_cmd_hook:n #1
630 %<latexrelease> { \@@_try_put_cmd_hook:w #1 / / / \s_@@_mark {#1} }
631 %<latexrelease>\cs_new_protected:Npn \@@_try_put_cmd_hook:w
632 %<latexrelease> #1 / #2 / #3 / #4 \s_@@_mark #5
633 %<latexrelease> {
634 %<latexrelease> \@@_debug:n { \iow_term:n { ->~Adding~cmd~hook~to~'#2'~(#3): } }
635 %<latexrelease> \exp_args:Nc \__hook_patch_cmd_or_delay:Nnn {#2} {#2} {#3}
636 %<latexrelease> }
637 %<latexrelease>\EndIncludeInRelease
638 % \end{macrocode}
639 %
640 % \begin{macrocode}
641 %<latexrelease>\IncludeInRelease{2021/06/01}{\@@_try_put_cmd_hook:n}%
642 %<latexrelease> {Standardise~generic~hook~names}
643 %<latexrelease>\cs_new_protected:Npn \@@_try_put_cmd_hook:n #1
644 %<latexrelease> { \@@_try_put_cmd_hook:w #1 / / / \s_@@_mark {#1} }
645 %<latexrelease>\cs_new_protected:Npn \@@_try_put_cmd_hook:w
646 %<latexrelease> #1 / #2 / #3 / #4 \s_@@_mark #5
647 %<latexrelease> {
648 %<latexrelease> \@@_debug:n { \iow_term:n { ->~Adding~cmd~hook~to~'#2'~(#3): } }
649 %<latexrelease> \str_case:nnTF {#3}
650 %<latexrelease> { { before } { } { after } { } }
651 %<latexrelease> { \exp_args:Nc \@@_patch_cmd_or_delay:Nnn {#2} {#2} {#3} }
652 %<latexrelease> { \msg_error:nnnn { hooks } { wrong-cmd-hook } {#2} {#3} }
653 %<latexrelease> }
654 %<latexrelease>\EndIncludeInRelease
655 % \end{macrocode}
656 % \end{macro}
657 %
658 % \begin{macro}{\@@_patch_cmd_or_delay:Nnn}
659 % \begin{macro}{\@@_cmd_begindocument_code:}
660 % In the preamble, \cs{@@_patch_cmd_or_delay:Nnn} just adds the patch
661 % instruction to a property list to be executed later.
662 % \begin{macrocode}
663 \cs_new_protected:Npn \@@_patch_cmd_or_delay:Nnn #1 #2 #3
664 {
665 \@@_debug:n { \iow_term:n { ->~Add~generic~cmd~hook~for~#2~(#3). } }
666 \@@_debug:n
667 { \iow_term:n { !~In~the~preamble:~delaying. } }
668 \prop_gput:Nnn \g_@@_delayed_patches_prop { #2 / #3 }
669 { \@@_cmd_try_patch:nn {#2} {#3} }
670 }
671 % \end{macrocode}
672 %
673 % The delayed patches are added to a property list to prevent
674 % duplication, and the code stored in the property list for each
675 % key is executed. The function \cs{@@_patch_cmd_or_delay:Nnn} is
676 % also redefined to be \cs{@@_patch_command:Nnn} so that no further
677 % delaying is attempted.
678 % \begin{macrocode}
679 \cs_new_protected:Npn \@@_cmd_begindocument_code:
680 {
681 \cs_gset_eq:NN \@@_patch_cmd_or_delay:Nnn \@@_patch_command:Nnn
682 \prop_map_function:NN \g_@@_delayed_patches_prop { \use_ii:nn }
683 \prop_gclear:N \g_@@_delayed_patches_prop
684 \cs_undefine:N \@@_cmd_begindocument_code:
685 }
686 \g@addto@macro \@kernel@after@begindocument
687 { \@@_cmd_begindocument_code: }
688 % \end{macrocode}
689 % \end{macro}
690 % \end{macro}
691 %
692 % \begin{macro}{\@@_cmd_try_patch:nn}
693 % At |\begin{document}| tries patching the command if the hook
694 % was not manually created in the meantime. If the document does not
695 % exist, no error is raised here as it may hook into a package that
696 % wasn't loaded. Hooks added to commands in the document body still
697 % raise an error if the command is not defined.
698 % \begin{macrocode}
699 \cs_new_protected:Npn \@@_cmd_try_patch:nn #1 #2
700 {
701 \@@_debug:n
702 { \iow_term:e { ->~\string\begin{document}~try~cmd / #1 / #2. } }
703 \@@_if_declared:nTF { cmd / #1 / #2 }
704 {
705 \@@_debug:n
706 { \iow_term:n { .->~Giving~up:~hook~already~created. } }
707 }
708 {
709 \cs_if_exist:cT {#1}
710 { \exp_args:Nc \@@_patch_command:Nnn {#1} {#1} {#2} }
711 }
712 }
713 % \end{macrocode}
714 % \end{macro}
715 %
716 %
717 %
718 %
719 %
720 % \subsection{Patching commands}
721 %
722 % \begin{macro}{\@@_patch_command:Nnn}
723 % \begin{macro}{\@@_patch_check:NNnn}
724 % \begin{macro}[TF]{\@@_if_public_command:N}
725 % \begin{macro}{\@@_if_public_command:w}
726 % \cs{@@_patch_command:Nnn} will do some sanity checks on the
727 % argument to detect if it is possible to add hooks to the command,
728 % and raises an error otherwise. If the command can contain hooks,
729 % then it uses \tn{robust@command@act} to find out what type is the
730 % command, and patch it accordingly.
731 % \begin{macrocode}
732 \cs_new_protected:Npn \@@_patch_command:Nnn #1 #2 #3
733 {
734 \@@_patch_debug:e { analyzing~'\token_to_str:N #1' }
735 \@@_patch_debug:e { \token_to_str:N #1 = \token_to_meaning:N #1 }
736 \@@_patch_check:NNnn \cs_if_exist:NTF #1 { undef }
737 {
738 \@@_patch_debug:e { ++~control~sequence~is~defined }
739 \@@_patch_check:NNnn \token_if_macro:NTF #1 { macro }
740 {
741 \@@_patch_debug:e { ++~control~sequence~is~a~macro }
742 \@@_patch_check:NNnn \@@_if_public_command:NTF #1 { expl3 }
743 {
744 \@@_patch_debug:e { ++~macro~is~not~private }
745 \robust@command@act
746 \g_hook_patch_action_list_tl #1
747 \@@_retokenize_patch:Nnn { #1 {#2} {#3} }
748 }
749 }
750 }
751 }
752 % \end{macrocode}
753 %
754 % And here's the auxiliary used above:
755 % \begin{macrocode}
756 \cs_new_protected:Npn \@@_patch_check:NNnn #1 #2 #3 #4
757 {
758 #1 #2 {#4}
759 {
760 \msg_error:nnee { hooks } { cant-patch }
761 { \token_to_str:N #2 } {#3}
762 }
763 }
764 % \end{macrocode}
765 % and a conditional \cs{@@_if_public_command:NTF} to check if a command
766 % has |__| in its name (no other checking is performed). Primitives
767 % with |:D| in their name could be included here, but they are already
768 % discarded in the \cs{token_if_macro:NTF} test above.
769 % \begin{macrocode}
770 \use:e
771 {
772 \prg_new_protected_conditional:Npnn
773 \exp_not:N \@@_if_public_command:N #1 { TF }
774 {
775 \exp_not:N \exp_last_unbraced:Nf
776 \exp_not:N \@@_if_public_command:w
777 { \exp_not:N \cs_to_str:N #1 }
778 \tl_to_str:n { _ _ } \s_@@_mark
779 }
780 }
781 \exp_last_unbraced:NNNNo
782 \cs_new_protected:Npn \@@_if_public_command:w
783 #1 \tl_to_str:n { _ _ } #2 \s_@@_mark
784 {
785 \tl_if_empty:nTF {#2}
786 { \prg_return_true: }
787 { \prg_return_false: }
788 }
789 % \end{macrocode}
790 % \end{macro}
791 % \end{macro}
792 % \end{macro}
793 % \end{macro}
794 %
795 %
796 %
797 %
798 %
799 %
800 %
801 % \subsubsection{Patching by expansion and redefinition}
802 %
803 % \begin{macro}[int]{\g_hook_patch_action_list_tl}
804 % This is the list of known command types and the function that
805 % patches the command hooks into them. The conditionals are taken
806 % from \tn{ShowCommand}, \tn{NewCommandCopy} and
807 % \cs{__kernel_cmd_if_xparse:NTF} defined in \texttt{ltcmd}.
808 % \begin{macrocode}
809 \tl_gset:Nn \g_hook_patch_action_list_tl
810 {
811 { \@if@DeclareRobustCommand \@@_patch_DeclareRobustCommand:Nnn }
812 { \@if@newcommand \@@_patch_newcommand:Nnn }
813 { \__kernel_cmd_if_xparse:NTF \@@_cmd_patch_xparse:Nnn }
814 }
815 % \end{macrocode}
816 % \end{macro}
817 %
818 %
819 %
820 %
821 % \begin{macro}{\@@_patch_DeclareRobustCommand:Nnn}
822 % At this point we know that the commands can be patched by expanding
823 % then redefining. These are the cases of commands defined with
824 % \tn{newcommand} with an optional argument or with
825 % \tn{DeclareRobustCommand}.
826 %
827 % With \cs{@@_patch_DeclareRobustCommand:Nnn} we check if the command
828 % has an optional argument (with a test counter-intuitively called
829 % \tn{@if@newcommand}; also make sure the command doesn't take args by
830 % calling \cs{robust@command@chk@safe}). If so, we pass the patching action
831 % to \cs{@@_patch_newcommand:Nnn}, otherwise we call the patching engine
832 % \cs{@@_patch_expand_redefine:NNnn} with a \cs{c_false_bool} to
833 % indicate that there is no optional argument.
834 %
835 % \changes{v1.0c}{2021/07/20}
836 % {Use \cs{robust@command@chk@safe} before \cs{@if@newcommand}.}
837 % \begin{macrocode}
838 \cs_new_protected:Npn \@@_patch_DeclareRobustCommand:Nnn #1
839 {
840 \exp_args:Nc \@@_patch_DeclareRobustCommand_aux:Nnn
841 { \cs_to_str:N #1 ~ }
842 }
843 \cs_new_protected:Npn \@@_patch_DeclareRobustCommand_aux:Nnn #1
844 {
845 \robust@command@chk@safe #1
846 { \@if@newcommand #1 }
847 { \use_ii:nn }
848 { \@@_patch_newcommand:Nnn }
849 { \@@_patch_expand_redefine:NNnn \c_false_bool }
850 #1
851 }
852 % \end{macrocode}
853 % \end{macro}
854 %
855 %
856 %
857 % \begin{macro}{\@@_patch_newcommand:Nnn}
858 % If the command was defined with \tn{newcommand} and an optional
859 % argument, call the patching engine with a \cs{c_true_bool} to flag
860 % the presence of an optional argument, and with
861 % \cs[no-index]{\string\command} to patch the actual code for
862 % \cs[no-index]{command}.
863 % \begin{macrocode}
864 \cs_new_protected:Npn \@@_patch_newcommand:Nnn #1
865 {
866 \exp_args:NNc \@@_patch_expand_redefine:NNnn \c_true_bool
867 { \c_backslash_str \cs_to_str:N #1 }
868 }
869 % \end{macrocode}
870 % \end{macro}
871 %
872 % \begin{macro}{\@@_cmd_patch_xparse:Nnn}
873 % And for commands defined by the \pkg{xparse} commands use this
874 % for patching:
875 % \begin{macrocode}
876 \cs_new_protected:Npn \@@_cmd_patch_xparse:Nnn #1
877 {
878 \exp_args:NNc \@@_patch_expand_redefine:NNnn \c_false_bool
879 { \cs_to_str:N #1 ~ code }
880 }
881 % \end{macrocode}
882 % \end{macro}
883 %
884 %
885 %
886 %
887 %
888 % \begin{macro}{\@@_patch_expand_redefine:NNnn}
889 % \begin{macro}{\@@_redefine_with_hooks:Nnnn}
890 % \begin{macro}[EXP]{\@@_make_prefixes:w}
891 % Now the real action begins. Here we have in |#1| a boolean
892 % indicating if the command has a leading |[|\ldots|]|-delimited
893 % argument, in |#2| the command control sequence, in |#3| the name of
894 % the command (note that |#1|${}\ne{}$|\csname#2\endcsname| at this
895 % point!), and in |#4| the hook position, either |before| or |after|.
896 %
897 % \changes{v1.0f}{2021/10/20}
898 % {Correct patching by expansion+redefinition when the macro
899 % contains a parameter token (gh/697)}
900 % Patching with expansion+redefinition is trickier than it looks like
901 % at first glance. Suppose the simple definition:
902 % \begin{verbatim}
903 % \def\foo#1{#1##2}
904 % \end{verbatim}
905 % When defined, its \meta{replacement text} will be a token list
906 % containing:
907 % \begin{quote}
908 % \itshape
909 % out\_param |1|, mac\_param |#|, character |2|
910 % \end{quote}
911 %
912 % Then, after expanding \cs{foo}|{##1}| (here |##| denotes a single
913 % |#|$_6$) we end up with a token list with \textit{out\_param}~|1|
914 % replaced:
915 % \begin{quote}
916 % \itshape
917 % mac\_param |#|, character |1|, mac\_param |#|, character |2|
918 % \end{quote}
919 % that is, the definition would be:
920 % \begin{verbatim}
921 % \def\foo#1{#1#2}
922 % \end{verbatim}
923 % which obviously fails, because the original input in the definition
924 % was |##| but \TeX{} reduced that to a single parameter token |#|$_6$
925 % when carrying out the definition. That leaves no room for a clever
926 % solution with (say) \cs{unexpanded}, because anything that would
927 % double the second |#|$_6$, would also (incorrectly) double the
928 % first, so there's not much to do other than a manual solution.
929 %
930 % There are three cases we can distinguish to make things hopefully
931 % faster on simpler cases:
932 % \begin{enumerate}
933 % \item a macro with no parameters;
934 % \item a macro with no parameter tokens in its definition;
935 % \item a macro with parameters \emph{and} parameter tokens.
936 % \end{enumerate}
937 %
938 % The first case is trivial: if the macro has no parameters, we can
939 % just use \cs{unexpanded} around it, and if there is a parameter
940 % token in it, it is handled correctly (the macro can be treated as a
941 % |tl| variable).
942 %
943 % The second case requires looking at the \meta{replacement text} of
944 % the macro to see if it has a parameter token in there. If it does
945 % not, then there is no worry, and the macro can be redefined normally
946 % (without \cs{unexpanded}).
947 %
948 % The third case, as usual, is the devious one. Here we'll have to
949 % loop through the definition token by token, and double every
950 % parameter token, so that this case can be handled like the previous
951 % one.
952 % \begin{macrocode}
953 %<latexrelease>\IncludeInRelease{2023/06/01}{\@@_patch_expand_redefine:NNnn}
954 %<latexrelease> {cmd~hooks~with~args}
955 \cs_new_protected:Npn \@@_patch_expand_redefine:NNnn #1 #2 #3 #4
956 {
957 \@@_patch_debug:e { ++~command~can~be~patched~without~rescanning }
958 % \end{macrocode}
959 % We'll start by counting the number of arguments in the command by
960 % counting the number of characters in the \cs{cs_parameter_spec:N} of
961 % the macro, divided by two, and subtracting one if the command has an
962 % optional argument (that is, an extra |[]| in its
963 % \meta{parameter text}).
964 % \begin{macrocode}
965 \int_set:Nn \l_@@_patch_num_args_int
966 {
967 \exp_args:Nf \str_count:n { \__kernel_cs_parameter_spec:N #2 } / 2
968 \bool_if:NT #1 { -1 }
969 }
970 % \end{macrocode}
971 % Now build two token lists:
972 % \begin{description}
973 % \item[\cs{l_@@_param_text_tl}] will contain the
974 % \meta{parameter text} to be used when redefining the macro. It
975 % should be identical to the \meta{parameter text} used when
976 % originally defining that macro.
977 % \item[\cs{l_@@_replace_text_tl}] will contain braced pairs of
978 % \cs{c_@@_hashes_tl}\meta{num} to feed to the macro when expanded.
979 % This token list as well as the previous will have the first item
980 % surrounded by |[|\ldots|]| in the case of an optional argument.
981 % \end{description}
982 %
983 % The use of \cs{c_@@_hashes_tl} here is to differentiate actual
984 % parameters in the macro from parameter tokens in the original
985 % definition of the macro. Later on, \cs{c_@@_hashes_tl} is either
986 % replaced by actual parameter tokens, or expanded into them.
987 % \begin{macrocode}
988 \int_compare:nNnTF { \l_@@_patch_num_args_int } > { \c_zero_int }
989 {
990 % \end{macrocode}
991 % We'll first check if the command has any parameter token in its
992 % definition (feeding it empty arguments), and set \cs{@@_exp_not:n}
993 % accordingly. \cs{@@_exp_not:n} will be used later to either leave
994 % \cs{c_@@_hashes_tl} or expand it, and also to remember the result of
995 % \cs{@@_if_has_hash:nTF} to avoid testing twice (the test can be
996 % rather slow).
997 % \begin{macrocode}
998 \tl_set:Ne \l_@@_tmpa_tl { \bool_if:NTF #1 { [ ] } { { } } }
999 \int_step_inline:nnn { 2 } { \l_@@_patch_num_args_int }
1000 { \tl_put_right:Nn \l_@@_tmpa_tl { { } } }
1001 \exp_args:NNo \exp_args:No \@@_if_has_hash:nTF
1002 { \exp_after:wN #2 \l_@@_tmpa_tl }
1003 { \cs_set_eq:NN \@@_exp_not:n \exp_not:n }
1004 { \cs_set_eq:NN \@@_exp_not:n \use:n }
1005 \cs_set_protected:Npn \@@_tmp:w ##1 ##2
1006 {
1007 ##1 \l_@@_param_text_tl { \use:n ##2 }
1008 ##1 \l_@@_replace_text_tl { \@@_exp_not:n {##2} }
1009 }
1010 % \end{macrocode}
1011 % Here we'll conditionally add |[|\ldots|]| around the first
1012 % parameter:
1013 % \changes{v1.0g}{2023/04/06}
1014 % {Rename to \cs{c__hook_hashes_tl} (hook-args)}
1015 % \begin{macrocode}
1016 \bool_if:NTF #1
1017 { \@@_tmp:w \tl_set:Ne { [ \c_@@_hash_tl 1 ] } }
1018 { \@@_tmp:w \tl_set:Ne { { \c_@@_hash_tl 1 } } }
1019 % \end{macrocode}
1020 % Then, for every parameter from the second, just add it normally:
1021 % \begin{macrocode}
1022 \int_step_inline:nnn { 2 } { \l_@@_patch_num_args_int }
1023 { \@@_tmp:w \tl_put_right:Ne { { \c_@@_hash_tl ##1 } } }
1024 % \end{macrocode}
1025 % Now, if the command has any parameter token in its definition
1026 % (then \cs{@@_exp_not:n} is \cs{exp_not:n}), call
1027 % \cs{@@_double_hashes:n} to double them, and replace every
1028 % \cs{c_@@_hashes_tl} by |#|:
1029 % \begin{macrocode}
1030 \tl_set:Ne \l_@@_replace_text_tl
1031 { \exp_not:N #2 \exp_not:V \l_@@_replace_text_tl }
1032 \tl_set:Ne \l_@@_replace_text_tl
1033 {
1034 \token_if_eq_meaning:NNTF \@@_exp_not:n \exp_not:n
1035 { \exp_args:NNV \exp_args:No \@@_double_hashes:n }
1036 { \exp_args:NV \exp_not:o }
1037 \l_@@_replace_text_tl
1038 }
1039 % \end{macrocode}
1040 % And now, set a few auxiliaries for the case that the macro has
1041 % parameters, so it won't be passed through \cs{unexpanded} (twice):
1042 % \begin{macrocode}
1043 \cs_set_eq:NN \@@_def_cmd:w \tex_gdef:D
1044 \cs_set_eq:NN \@@_exp_not:NN \prg_do_nothing:
1045 }
1046 {
1047 % \end{macrocode}
1048 % In the case the macro has no parameters, we'll treat it as a token
1049 % list and things are much simpler (expansion control looks a bit
1050 % complicated, but it's just a pair of \cs{exp_not:N} preventing
1051 % another \cs{exp_not:n} from expanding):
1052 % \begin{macrocode}
1053 \tl_clear:N \l_@@_param_text_tl
1054 \tl_set_eq:NN \l_@@_replace_text_tl #2
1055 \cs_set_eq:NN \@@_def_cmd:w \tex_xdef:D
1056 \cs_set:Npn \@@_exp_not:NN ##1 { \exp_not:N ##1 \exp_not:N }
1057 }
1058 % \end{macrocode}
1059 % Before redefining, we need to also get the prefixes used when
1060 % defining the command. Here we ensure that the \tn{escapechar} is
1061 % printable, otherwise a macro defined with prefixes
1062 % |\protected \long| will have it \tn{meaning} printed as
1063 % |protectedlong|, making life unnecessarily complicated. Here the
1064 % \tn{escapechar} is changed to |/|, then we loop between pairs of
1065 % |/|\ldots|/| extracting the prefixes.
1066 % \begin{macrocode}
1067 \group_begin:
1068 \int_set:Nn \tex_escapechar:D { `\/ }
1069 \use:e
1070 {
1071 \group_end:
1072 \tl_set:Ne \exp_not:N \l_@@_patch_prefixes_tl
1073 { \exp_not:N \@@_make_prefixes:w \cs_prefix_spec:N #2 / / }
1074 }
1075 % \end{macrocode}
1076 % Here we redefine the hook to have the right number of arguments.
1077 % Disabling the hook, undefining the \verb|parameter| token list then
1078 % calling \cs{@@_make_usable:nn} are enough to redefine the hook to
1079 % the extent we want. Code stored in the hook and other metadata
1080 % about it are not lost in the process.
1081 % \changes{v1.0h}{2023/05/21}
1082 % {Changes to allow support arguments in cmd hooks (cmd-args)}
1083 % \begin{macrocode}
1084 \@@_disable:n { cmd / #3 / #4 }
1085 \cs_undefine:c { c_@@_cmd / #3 / #4_parameter_tl }
1086 \@@_make_usable:nn { cmd / #3 / #4 } { \l_@@_patch_num_args_int }
1087 % \end{macrocode}
1088 % Now call \cs{@@_redefine_with_hooks:Nnnn} with the macro being
1089 % redefined in |#1|, then \cs{UseHook}|{cmd/<name>/before}| in |#2| or
1090 % \cs{UseHook}|{cmd/<name>/after}| in |#3| (one is always empty), and
1091 % in |#4| the \meta{replacement text} of the macro.
1092 % \begin{macrocode}
1093 \use:e
1094 {
1095 \@@_redefine_with_hooks:Nnnn \exp_not:N #2
1096 \str_if_eq:nnTF {#4} { after }
1097 { \use_ii_i:nn }
1098 { \use:nn }
1099 { {
1100 \@@_exp_not:NN \exp_not:N \UseHookWithArguments
1101 { cmd / #3 / #4 } { \int_use:N \l_@@_patch_num_args_int }
1102 \@@_braced_parameter:n { cmd / #3 / #4 }
1103 } }
1104 { { } }
1105 { \@@_exp_not:NN \exp_not:V \l_@@_replace_text_tl }
1106 }
1107 % \end{macrocode}
1108 % Finally, update the hook code.
1109 % \begin{macrocode}
1110 \@@_update_hook_code:n { cmd / #3 / #4 }
1111 }
1112 %<latexrelease>\EndIncludeInRelease
1113 %<latexrelease>\IncludeInRelease{2021/06/01}{\@@_patch_expand_redefine:NNnn}
1114 %<latexrelease> {cmd~hooks~with~args}
1115 %<latexrelease>\cs_gset_protected:Npn \@@_patch_expand_redefine:NNnn #1 #2 #3 #4
1116 %<latexrelease> {
1117 %<latexrelease> \@@_patch_debug:e { ++~command~can~be~patched~without~rescanning }
1118 %<latexrelease> \int_set:Nn \l_@@_patch_num_args_int
1119 %<latexrelease> {
1120 %<latexrelease> \exp_args:Nf \str_count:n { \__kernel_cs_parameter_spec:N #2 } / 2
1121 %<latexrelease> \bool_if:NT #1 { -1 }
1122 %<latexrelease> }
1123 %<latexrelease> \int_compare:nNnTF { \l_@@_patch_num_args_int } > { \c_zero_int }
1124 %<latexrelease> {
1125 %<latexrelease> \tl_set:Nx \l_@@_tmpa_tl { \bool_if:NTF #1 { [ ] } { { } } }
1126 %<latexrelease> \int_step_inline:nnn { 2 } { \l_@@_patch_num_args_int }
1127 %<latexrelease> { \tl_put_right:Nn \l_@@_tmpa_tl { { } } }
1128 %<latexrelease> \exp_args:NNo \exp_args:No \@@_if_has_hash:nTF
1129 %<latexrelease> { \exp_after:wN #2 \l_@@_tmpa_tl }
1130 %<latexrelease> { \cs_set_eq:NN \@@_exp_not:n \exp_not:n }
1131 %<latexrelease> { \cs_set_eq:NN \@@_exp_not:n \use:n }
1132 %<latexrelease> \cs_set_protected:Npn \@@_tmp:w ##1 ##2
1133 %<latexrelease> {
1134 %<latexrelease> ##1 \l_@@_param_text_tl { \use:n ##2 }
1135 %<latexrelease> ##1 \l_@@_replace_text_tl { \@@_exp_not:n {##2} }
1136 %<latexrelease> }
1137 %<latexrelease> \bool_if:NTF #1
1138 %<latexrelease> { \@@_tmp:w \tl_set:Nx { [ \c_@@_hash_tl 1 ] } }
1139 %<latexrelease> { \@@_tmp:w \tl_set:Nx { { \c_@@_hash_tl 1 } } }
1140 %<latexrelease> \int_step_inline:nnn { 2 } { \l_@@_patch_num_args_int }
1141 %<latexrelease> { \@@_tmp:w \tl_put_right:Nx { { \c_@@_hash_tl ##1 } } }
1142 %<latexrelease> \tl_set:Nx \l_@@_replace_text_tl
1143 %<latexrelease> { \exp_not:N #2 \exp_not:V \l_@@_replace_text_tl }
1144 %<latexrelease> \tl_set:Nx \l_@@_replace_text_tl
1145 %<latexrelease> {
1146 %<latexrelease> \token_if_eq_meaning:NNTF \@@_exp_not:n \exp_not:n
1147 %<latexrelease> { \exp_args:NNV \exp_args:No \@@_double_hashes:n }
1148 %<latexrelease> { \exp_args:NV \exp_not:o }
1149 %<latexrelease> \l_@@_replace_text_tl
1150 %<latexrelease> }
1151 %<latexrelease> \cs_set_eq:NN \@@_def_cmd:w \tex_gdef:D
1152 %<latexrelease> \cs_set_eq:NN \@@_exp_not:NN \prg_do_nothing:
1153 %<latexrelease> }
1154 %<latexrelease> {
1155 %<latexrelease> \tl_clear:N \l_@@_param_text_tl
1156 %<latexrelease> \tl_set_eq:NN \l_@@_replace_text_tl #2
1157 %<latexrelease> \cs_set_eq:NN \@@_def_cmd:w \tex_xdef:D
1158 %<latexrelease> \cs_set:Npn \@@_exp_not:NN ##1 { \exp_not:N ##1 \exp_not:N }
1159 %<latexrelease> }
1160 %<latexrelease> \group_begin:
1161 %<latexrelease> \int_set:Nn \tex_escapechar:D { `\/ }
1162 %<latexrelease> \use:x
1163 %<latexrelease> {
1164 %<latexrelease> \group_end:
1165 %<latexrelease> \tl_set:Nx \exp_not:N \l_@@_patch_prefixes_tl
1166 %<latexrelease> { \exp_not:N \@@_make_prefixes:w \cs_prefix_spec:N #2 / / }
1167 %<latexrelease> }
1168 %<latexrelease> \use:x
1169 %<latexrelease> {
1170 %<latexrelease> \@@_redefine_with_hooks:Nnnn \exp_not:N #2
1171 %<latexrelease> \str_if_eq:nnTF {#4} { after }
1172 %<latexrelease> { \use_ii_i:nn }
1173 %<latexrelease> { \use:nn }
1174 %<latexrelease> { { \@@_exp_not:NN \exp_not:N \UseHook { cmd / #3 / #4 } } }
1175 %<latexrelease> { { } }
1176 %<latexrelease> { \@@_exp_not:NN \exp_not:V \l_@@_replace_text_tl }
1177 %<latexrelease> }
1178 %<latexrelease> }
1179 %<latexrelease>\EndIncludeInRelease
1180 % \end{macrocode}
1181 %
1182 % Now that all the needed tools are ready, without further ado we'll
1183 % redefine the command. The definition uses the prefixes gathered in
1184 % \cs{l_@@_patch_prefixes_tl}, a primitive \cs{@@_def_cmd:w} (which is
1185 % \cs{tex_gdef:D} or \cs{tex_xdef:D}) to avoid adding extra prefixes,
1186 % and the \meta{parameter text} from \cs{l_@@_param_text_tl}.
1187 %
1188 % Then finally, in the body of the definition, we insert |#2|, which
1189 % is \hook{cmd/\#1/before} or empty, |#4| which is the
1190 % \meta{replacement text}, and |#3| which is \hook{cmd/\#1/after} or
1191 % empty.
1192 %
1193 % \changes{v1.0e}{2021/09/28}
1194 % {Make patching of commands a global operation (gh/674)}
1195 % \begin{macrocode}
1196 \cs_new_protected:Npn \@@_redefine_with_hooks:Nnnn #1 #2 #3 #4
1197 {
1198 \l_@@_patch_prefixes_tl
1199 \exp_after:wN \@@_def_cmd:w
1200 \exp_after:wN #1 \l_@@_param_text_tl
1201 { #2 #4 #3 }
1202 }
1203 % \end{macrocode}
1204 %
1205 % Here's the auxiliary that makes the prefix control sequences for the
1206 % redefinition. Each item has to be \cs{tl_trim_spaces:n}'d because
1207 % the last item (and not any other) has a trailing space.
1208 % \begin{macrocode}
1209 \cs_new:Npn \@@_make_prefixes:w / #1 /
1210 {
1211 \tl_if_empty:nF {#1}
1212 {
1213 \exp_not:c { tex_ \tl_trim_spaces:n {#1} :D }
1214 \@@_make_prefixes:w /
1215 }
1216 }
1217 % \end{macrocode}
1218 % \end{macro}
1219 % \end{macro}
1220 % \end{macro}
1221 %
1222 %
1223 % Here are some auxiliaries for the contraption above.
1224 %
1225 % \begin{macro}[pTF]{\@@_if_has_hash:n}
1226 % \begin{macro}{\@@_if_has_hash:w,\@@_if_has_hash_check:w}
1227 % \cs{@@_if_has_hash:nTF} searches the token list |#1| for a catcode~6
1228 % token, and if any is found, it returns |true|, and |false|
1229 % otherwise. The searching doesn't care about preserving groups or
1230 % spaces: we can ignore those safely (braces are removed) so that
1231 % searching is as fast as possible.
1232 % \begin{macrocode}
1233 \prg_new_conditional:Npnn \@@_if_has_hash:n #1 { TF }
1234 { \@@_if_has_hash:w #1 ## \s_@@_mark }
1235 \cs_new:Npn \@@_if_has_hash:w #1
1236 {
1237 \tl_if_single_token:nTF {#1}
1238 {
1239 \token_if_eq_catcode:NNTF ## #1
1240 { \@@_if_has_hash_check:w }
1241 { \@@_if_has_hash:w }
1242 }
1243 { \@@_if_has_hash:w #1 }
1244 }
1245 \cs_new:Npn \@@_if_has_hash_check:w #1 \s_@@_mark
1246 { \tl_if_empty:nTF {#1} { \prg_return_false: } { \prg_return_true: } }
1247 % \end{macrocode}
1248 % \end{macro}
1249 % \end{macro}
1250 %
1251 %
1252 % \begin{macro}[rEXP]{\@@_double_hashes:n}
1253 % \begin{macro}[rEXP]{
1254 % \@@_double_hashes:w,
1255 % \@@_double_hashes_output:N,
1256 % \@@_double_hashes_output_aux:N,
1257 % \@@_double_hashes_stop:w,
1258 % \@@_double_hashes_group:n,
1259 % \@@_double_hashes_space:w,
1260 % }
1261 % \cs{@@_double_hashes:n} loops through the token list |#1| and
1262 % duplicates any catcode~6 token, and expands tokens \cs{ifx}-equal to
1263 % \cs{c_@@_hashes_tl}, and leaves all other tokens \cs{notexpanded} with
1264 % \cs{exp_not:N}. Unfortunately pairs of explicit catcode~1 and
1265 % catcode~2 character tokens are normalised to |{|$_1$ and |}|$_1$
1266 % because it's not feasible to expandably detect the character code
1267 % (\emph{maybe} it could be done using something along the lines of
1268 % \url{https://tex.stackexchange.com/a/527538}, but it's far too much
1269 % work for close to zero benefit).
1270 %
1271 % \cs{@@_double_hashes:w} is the tail-recursive loop macro, that tests
1272 % which of the three types of item is in the head of the token list.
1273 % \begin{macrocode}
1274 \cs_new:Npn \@@_double_hashes:n #1
1275 { \@@_double_hashes:w #1 \q_@@_recursion_tail \q_@@_recursion_stop }
1276 \cs_new:Npn \@@_double_hashes:w #1 \q_@@_recursion_stop
1277 {
1278 \tl_if_head_is_N_type:nTF {#1}
1279 { \@@_double_hashes_output:N }
1280 {
1281 \tl_if_head_is_group:nTF {#1}
1282 { \@@_double_hashes_group:n }
1283 { \@@_double_hashes_space:w }
1284 }
1285 #1 \q_@@_recursion_stop
1286 }
1287 % \end{macrocode}
1288 %
1289 % \cs{@@_double_hashes_output:N} checks for the end of the token list,
1290 % then checks if the token is \cs{c_@@_hashes_tl}, and if so just leaves
1291 % it.
1292 % \changes{v1.0g}{2023/04/06}
1293 % {Add case for \cs{c__hook_hashes_tl} (hook-args)}
1294 % \begin{macrocode}
1295 \cs_new:Npn \@@_double_hashes_output:N #1
1296 {
1297 \if_meaning:w \q_@@_recursion_tail #1
1298 \@@_double_hashes_stop:w
1299 \fi:
1300 \if:w ?
1301 \if_meaning:w \c_@@_hash_tl #1 ! \fi:
1302 \if_meaning:w \c_@@_hashes_tl #1 ! \fi:
1303 ?
1304 \else:
1305 % \end{macrocode}
1306 % (this \cs{use_i:nnnn} uses \cs{fi:} and consumes \cs{use:n}, the
1307 % whole \cs{if_catcode:w} block, and the \cs{exp_not:N}, leaving just
1308 % |#1| which is \cs{c_@@_hashes_tl}.)
1309 % \begin{macrocode}
1310 \use_i:nnnn
1311 \fi:
1312 \use:n
1313 {
1314 % \end{macrocode}
1315 % \changes{v1.0m}{2025-11-10}{Support \cs{alignmark}}
1316 % If |#1| is not \cs{c_@@_hashes_tl}, then check if its catcode is~6,
1317 % and if so, leave it doubled in \cs{exp_not:n} and consume the
1318 % following |\exp_not:N #1|.
1319 % \begin{macrocode}
1320 \@@_double_hashes_output_aux:N #1
1321 \use_none:n
1322 { \exp_not:n { #1 #1 } }
1323 }
1324 % \end{macrocode}
1325 % If both previous tests returned |false|, then leave the token
1326 % unexpanded and resume the loop.
1327 % \begin{macrocode}
1328 \exp_not:N #1
1329 \@@_double_hashes:w
1330 }
1331 % \end{macrocode}
1332 % \changes{v1.0m}{2025-11-10}{Support \cs{alignmark}}
1333 % Lua\TeX{} has a primitive equivalent to |#|, which is replaced in a
1334 % dedicated path. That code is not needed for other engines, so we avoid the
1335 % hit on performance by using an auxiliary.
1336 % \begin{macrocode}
1337 \cs_new:Npn \@@_double_hashes_output_aux:N #1
1338 {
1339 \if_catcode:w ## \exp_not:N #1
1340 \exp_after:wN \use_ii:nnnn
1341 \fi:
1342 }
1343 \sys_if_engine_luatex:T
1344 {
1345 \cs_gset:Npn \@@_double_hashes_output_aux:N #1
1346 {
1347 \if_catcode:w ## \exp_not:N #1
1348 \exp_after:wN \use_ii:nnnn
1349 \else:
1350 \if_meaning:w \tex_alignmark:D \tex_alignmark:D #1
1351 \exp_after:wN \exp_after:wN \exp_after:wN \use_ii:nnnn
1352 \fi:
1353 \fi:
1354 }
1355 }
1356 \cs_new:Npn \@@_double_hashes_stop:w #1 \q_@@_recursion_stop { \fi: }
1357 % \end{macrocode}
1358 %
1359 % Dealing with spaces and grouped tokens is trivial:
1360 % \begin{macrocode}
1361 \cs_new:Npn \@@_double_hashes_group:n #1
1362 { { \@@_double_hashes:n {#1} } \@@_double_hashes:w }
1363 \exp_last_unbraced:NNo
1364 \cs_new:Npn \@@_double_hashes_space:w \c_space_tl
1365 { ~ \@@_double_hashes:w }
1366 % \end{macrocode}
1367 % \end{macro}
1368 % \end{macro}
1369 %
1370 %
1371 % \subsubsection{Patching by retokenization}
1372 %
1373 % At this point we've drained the possibilities of patching a command by
1374 % expansion-and-redefinition, so we have to resort to patching by
1375 % retokenizing the command. Patching by retokenization is done by
1376 % getting the \tn{meaning} of the command, doing the necessary
1377 % manipulations on the generated string, and the retokenizing that again
1378 % by using \tn{scantokens}.
1379 %
1380 % Patching by retokenization is definitely a riskier business, because
1381 % it relies that the tokens printed by \tn{meaning} produce the exact
1382 % same tokens as the ones in the original definition. That is, the
1383 % catcode régime must be exactly(ish) the same, and there is no way of
1384 % telling except by trial and error.
1385 %
1386 % \begin{macro}{\@@_retokenize_patch:Nnn}
1387 % This is the macro that will control the whole process. First we'll
1388 % try out one final, rather trivial case, of a command with no
1389 % arguments; that is, a token list. This case can be patched with
1390 % the expand-and-redefine routine but it has to be the very last case
1391 % tested for, because most (all?) robust commands start with a
1392 % top-level macro with no arguments, so testing this first would
1393 % short-circuit \tn{robust@command@act} and the top-level macros would
1394 % be incorrectly patched. In that case, we just check if the
1395 % \cs{cs_parameter_spec:N} is empty, and call
1396 % \cs{@@_patch_expand_redefine:NNnn}.
1397 % \begin{macrocode}
1398 \cs_new_protected:Npn \@@_retokenize_patch:Nnn #1 #2 #3
1399 {
1400 \str_if_eq:eeTF { \__kernel_cs_parameter_spec:N #1 } { }
1401 { \@@_patch_expand_redefine:NNnn \c_false_bool #1 {#2} {#3} }
1402 {
1403 \@@_patch_debug:e { ..~command~can~only~be~patched~by~rescanning }
1404 % \end{macrocode}
1405 %
1406 % Otherwise, we start the actual patching by retokenization job. The
1407 % code calls \cs{@@_try_patch_with_catcodes:Nnnnw} with a different
1408 % catcode setting:
1409 % \begin{itemize}
1410 % \item The current catcode setting;
1411 % \item Switching the catcode of |@|;
1412 % \item Switching the \pkg{expl3} syntax on or off;
1413 % \item Both of the above.
1414 % \end{itemize}
1415 %
1416 % If patching succeeds, \cs{@@_try_patch_with_catcodes:Nnnnw} has the
1417 % side-effect of patching the macro |#1| (which may be an internal
1418 % from the command whose name is~|#2|).
1419 % \changes{v1.0l}{2025/10/12}{Reset the catcode of space when patching}
1420 % \begin{macrocode}
1421 \tl_set:Ne \l_@@_tmpa_tl
1422 {
1423 \int_compare:nNnTF { \char_value_catcode:n {`\@ } } = { 12 }
1424 { \exp_not:N \makeatletter } { \exp_not:N \makeatother }
1425 }
1426 \tl_set:Ne \l_@@_tmpb_tl
1427 {
1428 \bool_if:NTF \l__kernel_expl_bool
1429 { \ExplSyntaxOff }
1430 { \ExplSyntaxOn \char_set_catcode_space:n { 32 }}
1431 }
1432 \use:e
1433 {
1434 \exp_not:N \@@_try_patch_with_catcodes:Nnnnw
1435 \exp_not:n { #1 {#2} {#3} }
1436 { \prg_do_nothing: }
1437 { \exp_not:V \l_@@_tmpa_tl } % @
1438 { \exp_not:V \l_@@_tmpb_tl } % _:
1439 {
1440 \exp_not:V \l_@@_tmpa_tl % @
1441 \exp_not:V \l_@@_tmpb_tl % _:
1442 }
1443 }
1444 \q_recursion_tail \q_recursion_stop
1445 % \end{macrocode}
1446 %
1447 % If no catcode setting succeeds, give up and raise an error. The
1448 % command isn't changed in any way in that case.
1449 % \begin{macrocode}
1450 {
1451 \msg_error:nnee { hooks } { cant-patch }
1452 { \c_backslash_str #2 } { retok }
1453 }
1454 }
1455 }
1456 % \end{macrocode}
1457 % \end{macro}
1458 %
1459 %
1460 %
1461 % \begin{macro}{\@@_try_patch_with_catcodes:Nnnnw}
1462 % This function is a simple wrapper around
1463 % \cs{@@_cmd_if_scanable:NnTF} and \cs{@@_patch_retokenize:Nnnn} if
1464 % the former returns \meta{true}, plus some debug messages.
1465 % \begin{macrocode}
1466 %<latexrelease>\IncludeInRelease{2023/06/01}{\@@_try_patch_with_catcodes:Nnnnw}
1467 %<latexrelease> {cmd~hooks~with~args}
1468 \cs_new_protected:Npn \@@_try_patch_with_catcodes:Nnnnw #1 #2 #3 #4
1469 {
1470 \quark_if_recursion_tail_stop_do:nn {#4} { \use:n }
1471 \@@_patch_debug:e { ++~trying~to~patch~by~retokenization }
1472 \@@_cmd_if_scanable:NnTF {#1} {#4}
1473 {
1474 \@@_patch_debug:e { ++~macro~can~be~retokenized~cleanly }
1475 \@@_patch_debug:e { ==~retokenizing~macro~now }
1476 \@@_patch_retokenize:Nnnn #1 { cmd / #2 / #3 } {#3} {#4}
1477 \use_i_delimit_by_q_recursion_stop:nw \use_none:n
1478 }
1479 {
1480 \@@_patch_debug:e { --~macro~cannot~be~retokenized~cleanly }
1481 \@@_try_patch_with_catcodes:Nnnnw #1 {#2} {#3}
1482 }
1483 }
1484 %<latexrelease>\EndIncludeInRelease
1485 %<latexrelease>\IncludeInRelease{2021/06/01}{\@@_try_patch_with_catcodes:Nnnnw}
1486 %<latexrelease> {cmd~hooks~with~args}
1487 %<latexrelease>\cs_gset_protected:Npn \@@_try_patch_with_catcodes:Nnnnw #1 #2 #3 #4
1488 %<latexrelease> {
1489 %<latexrelease> \quark_if_recursion_tail_stop_do:nn {#4} { \use:n }
1490 %<latexrelease> \@@_patch_debug:e { ++~trying~to~patch~by~retokenization }
1491 %<latexrelease> \@@_cmd_if_scanable:NnTF {#1} {#4}
1492 %<latexrelease> {
1493 %<latexrelease> \@@_patch_debug:e { ++~macro~can~be~retokenized~cleanly }
1494 %<latexrelease> \@@_patch_debug:e { ==~retokenizing~macro~now }
1495 %<latexrelease> \@@_patch_retokenize:Nnnn #1 {#2} {#3} {#4}
1496 %<latexrelease> \use_i_delimit_by_q_recursion_stop:nw \use_none:n
1497 %<latexrelease> }
1498 %<latexrelease> {
1499 %<latexrelease> \@@_patch_debug:e { --~macro~cannot~be~retokenized~cleanly }
1500 %<latexrelease> \@@_try_patch_with_catcodes:Nnnnw #1 {#2} {#3}
1501 %<latexrelease> }
1502 %<latexrelease> }
1503 %<latexrelease>\EndIncludeInRelease
1504 % \end{macrocode}
1505 % \end{macro}
1506 %
1507 %
1508 %
1509 %
1510 % \begin{macro}[int]{\kerneltmpDoNotUse}
1511 % This is an oddity required to be safe (as safe as reasonably
1512 % possible) when patching the command. The entirety of
1513 % \begin{quote}
1514 % \meta{prefixes} \tn{def} \meta{cs} \meta{parameter text}
1515 % |{|\meta{replacement text}|}|
1516 % \end{quote}
1517 % will go through \tn{scantokens}. The \meta{parameter text} and
1518 % \meta{replacement text} are what we are trying to retokenize, so not
1519 % much worry there. The other items, however, should ``just work'',
1520 % so some care is needed to not use too fancy catcode settings.
1521 % Therefore we can't use an \pkg{expl3}-named macro for \meta{cs}, nor
1522 % the \pkg{expl3} versions of \tn{def} or the \meta{prefixes}.
1523 % That is why the definitions that will eventually go into
1524 % \tn{scantokens} will use the oddly (but hopefully clearly)-named
1525 % \cs{kerneltmpDoNotUse}:
1526 % \begin{macrocode}
1527 \cs_new_eq:NN \kerneltmpDoNotUse !
1528 % \end{macrocode}
1529 % \phoinline{Maybe this can be avoided by running the \meta{parameter text}
1530 % and the \meta{replacement text} separately through \tn{scantokens}
1531 % and then putting everything together at the end.}
1532 % \end{macro}
1533 %
1534 %
1535 %
1536 % \begin{macro}{\@@_patch_required_catcodes:}
1537 % Here are the catcode settings that are \emph{mandatory} when
1538 % retokenizing commands. These are the minimum necessary settings to
1539 % perform the definitions: they identify control sequences, which
1540 % must be escaped with |\|$_0$, delimit the definition with |{|$_1$
1541 % and |}|$_2$, and mark parameters with |#|$_6$. Everything else may
1542 % be changed, but not these.
1543 % \begin{macrocode}
1544 \cs_new_protected:Npn \@@_patch_required_catcodes:
1545 {
1546 \char_set_catcode_escape:N \\
1547 \char_set_catcode_group_begin:N \{
1548 \char_set_catcode_group_end:N \}
1549 \char_set_catcode_parameter:N \#
1550 % \int_set:Nn \tex_endlinechar:D { -1 }
1551 % \int_set:Nn \tex_newlinechar:D { -1 }
1552 }
1553 % \end{macrocode}
1554 % \phoinline{\pkg{etoolbox} sets the \tn{endlinechar} and \tn{newlinechar}
1555 % when patching, but as far as I tested these didn't make much of
1556 % a difference, so I left them out for now. Maybe
1557 % \tn{newlinechar}|=-1| avoids a space token being added after the
1558 % definition.}
1559 % \phoinline{If the patching is split by \meta{parameter text} and
1560 % \meta{replacement text}, then only \# will have to stay in that
1561 % list.}
1562 % \phoinline{Actually now that we patch
1563 % \texttt{\cs{UseHook}\{cmd/foo/before\}}, all the tokens there need
1564 % to have the right catcodes, so this list now includes all
1565 % lowercase letters, U and H, the slash, and whatever characters in
1566 % the command name\ldots sigh\ldots}
1567 % \end{macro}
1568 %
1569 %
1570 %
1571 %
1572 % \begin{macro}[TF]{\@@_cmd_if_scanable:Nn}
1573 % Here we'll do a quick test if the command being patched can in fact
1574 % be retokenized with the specific catcode setting without changing
1575 % in meaning. The test is straightforward:
1576 % \begin{enumerate}
1577 % \item apply \tn{meaning} to the command;
1578 % \item split the \meta{prefixes}, \meta{parameter text} and
1579 % \meta{replacement text} and arrange them as
1580 % \begin{quote}
1581 % \meta{prefixes}\tn{def}\cs{kerneltmpDoNotUse}%^^A
1582 % \meta{parameter text}|{|\meta{replacement text}|}|
1583 % \end{quote}
1584 % \item rescan that with the given catcode settings, and do
1585 % the definition; then finally
1586 % \item compare \cs{kerneltmpDoNotUse} with the original command.
1587 % \end{enumerate}
1588 % If both are \tn{ifx}-equal, the command can be safely patched.
1589 % \begin{macrocode}
1590 \prg_new_protected_conditional:Npnn \@@_cmd_if_scanable:Nn #1 #2 { TF }
1591 {
1592 \cs_set_eq:NN \kerneltmpDoNotUse \scan_stop:
1593 \cs_set_eq:NN \@@_tmp:w \scan_stop:
1594 \use:e
1595 {
1596 \cs_set:Npn \@@_tmp:w
1597 ##1 \tl_to_str:n { macro: } ##2 -> ##3 \s_@@_mark
1598 { ##1 \def \kerneltmpDoNotUse ##2 {##3} }
1599 \tl_set:Ne \exp_not:N \l_@@_tmpa_tl
1600 { \exp_not:N \@@_tmp:w \token_to_meaning:N #1 \s_@@_mark }
1601 }
1602 \tl_rescan:nV { #2 \@@_patch_required_catcodes: } \l_@@_tmpa_tl
1603 \token_if_eq_meaning:NNTF #1 \kerneltmpDoNotUse
1604 { \prg_return_true: }
1605 { \prg_return_false: }
1606 }
1607 % \end{macrocode}
1608 % \end{macro}
1609 %
1610 %
1611 % \begin{macro}{\@@_guess_arg_count:NN}
1612 % \begin{macro}{\@@_guess_arg_count:wN}
1613 % \begin{macro}{\@@_guess_arg_count:nw}
1614 % Looks at the parameter text of a macro, and counts the parameters
1615 % by looking at the number after a \verb|#|, and checking if they are
1616 % sequential. This macro assumes that all parameters are marked with
1617 % hashes, and not other characters, and that there is no
1618 % \enquote{trick parameter}.
1619 % \changes{v1.0h}{2023/05/21}
1620 % {Macro added (cmd-args)}
1621 % \begin{macrocode}
1622 %<latexrelease>\IncludeInRelease{2023/06/01}{\@@_guess_arg_count:NN}
1623 %<latexrelease> {cmd~hooks~with~args}
1624 \cs_new_protected:Npn \@@_guess_arg_count:NN #1
1625 {
1626 \exp_after:wN \@@_guess_arg_count:wN
1627 \token_to_meaning:N #1 \s_@@_mark
1628 }
1629 \exp_last_unbraced:NNNNo
1630 \cs_new_protected:Npe \@@_guess_arg_count:wN
1631 #1 { \tl_to_str:n { macro: } } #2 \s_@@_mark #3
1632 {
1633 \int_set:Nn #3
1634 {
1635 \exp_not:N \@@_guess_arg_count:nw { 0 } #2
1636 \c_hash_str 0 \s_@@_mark
1637 }
1638 }
1639 \use:e
1640 { \cs_new:Npn \exp_not:N \@@_guess_arg_count:nw #1 #2 \c_hash_str #3 }
1641 {
1642 \int_compare:nNnTF { #1 + 1 } = {#3}
1643 { \@@_guess_arg_count:nw {#3} }
1644 { #1 \@@_use_none_delimit_by_s_mark:w }
1645 }
1646 %<latexrelease>\EndIncludeInRelease
1647 %<latexrelease>\IncludeInRelease{2021/06/01}{\@@_guess_arg_count:NN}
1648 %<latexrelease> {cmd~hooks~with~args}
1649 %<latexrelease>\cs_undefine:N \@@_guess_arg_count:NN
1650 %<latexrelease>\EndIncludeInRelease
1651 % \end{macrocode}
1652 % \end{macro}
1653 % \end{macro}
1654 % \end{macro}
1655 %
1656 %
1657 % \begin{macro}{\@@_patch_retokenize:Nnnn}
1658 % Then, if \cs{@@_cmd_if_scanable:NnTF} returned true, we can go on
1659 % and patch the command.
1660 % \begin{macrocode}
1661 %<latexrelease>\IncludeInRelease{2023/06/01}{\@@_patch_retokenize:Nnnn}
1662 %<latexrelease> {cmd~hooks~with~args}
1663 \cs_new_protected:Npn \@@_patch_retokenize:Nnnn #1 #2 #3 #4
1664 {
1665 % \end{macrocode}
1666 % Here, when patching by retokenization, we can only guess the number
1667 % of arguments of the macro.
1668 % \changes{v1.0h}{2023/05/21}
1669 % {Changes to allow support arguments in cmd hooks (cmd-args)}
1670 % \begin{macrocode}
1671 \@@_guess_arg_count:NN #1 \l_@@_patch_num_args_int
1672 % \end{macrocode}
1673 %
1674 % Then we redefine the hook to have the right number of arguments.
1675 % Disabling the hook, undefining the \verb|parameter| token list then
1676 % calling \cs{@@_make_usable:nn} are enough to redefine the hook to
1677 % the extent we want. Code stored in the hook and other metadata
1678 % about it are not lost in the process.
1679 % \begin{macrocode}
1680 \@@_disable:n {#2}
1681 \cs_undefine:c { c_@@_#2_parameter_tl }
1682 \@@_make_usable:nn {#2} { \l_@@_patch_num_args_int }
1683 \tl_set:Ne \l_@@_tmpa_tl
1684 { \exp_args:Ne \tl_to_str:n { \@@_braced_parameter:n {#2} } }
1685 \use:e
1686 {
1687 \str_replace_all:Nnn \exp_not:N \l_@@_tmpa_tl
1688 { ## } { \c_hash_str }
1689 }
1690 % \end{macrocode}
1691 % Then, make some things \tn{relax} to avoid lots of
1692 % \tn{noexpand} below.
1693 % \begin{macrocode}
1694 \cs_set_eq:NN \kerneltmpDoNotUse \scan_stop:
1695 \cs_set_eq:NN \@@_tmp:w \scan_stop:
1696 \use:e
1697 {
1698 % \end{macrocode}
1699 % Now we'll define \cs{@@_tmp:w} such that it splits the \tn{meaning}
1700 % of the macro (|#1|) into its three parts:
1701 % \begin{enumerate}
1702 % \def\makelabel#1{\texttt{\#\#\#\##1}}
1703 % \item \meta{prefixes}
1704 % \item \meta{parameter text}
1705 % \item \meta{replacement text}
1706 % \end{enumerate}
1707 % and arrange that a complete definition, then place the |before|
1708 % or |after| hooks around the \meta{replacement text}:
1709 % accordingly.
1710 % \begin{macrocode}
1711 \cs_set:Npn \@@_tmp:w
1712 ##1 \tl_to_str:n { macro: } ##2 -> ##3 \s_@@_mark
1713 {
1714 ##1 \def \kerneltmpDoNotUse ##2
1715 {
1716 \str_if_eq:nnT {#3} { before }
1717 {
1718 \token_to_str:N \UseHookWithArguments {#2}
1719 { \int_use:N \l_@@_patch_num_args_int }
1720 \l_@@_tmpa_tl
1721 }
1722 ##3
1723 \str_if_eq:nnT {#3} { after }
1724 {
1725 \token_to_str:N \UseHookWithArguments {#2}
1726 { \int_use:N \l_@@_patch_num_args_int }
1727 \l_@@_tmpa_tl
1728 }
1729 }
1730 }
1731 % \end{macrocode}
1732 % Now we just have to get the \tn{meaning} of the command being
1733 % patched and pass it through the meat grinder above.
1734 % \begin{macrocode}
1735 \tl_set:Ne \exp_not:N \l_@@_tmpa_tl
1736 { \exp_not:N \@@_tmp:w \token_to_meaning:N #1 \s_@@_mark }
1737 }
1738 % \end{macrocode}
1739 % Now rescan with the given catcode settings (overridden by the
1740 % \cs{@@_patch_required_catcodes:}), and implicitly (by using the
1741 % rescanned token list) carry out the definition from above.
1742 % \begin{macrocode}
1743 \tl_rescan:nV { #4 \@@_patch_required_catcodes: } \l_@@_tmpa_tl
1744 % \end{macrocode}
1745 % And to close, copy the newly-defined command into the old name and
1746 % the patching is finally completed:
1747 %
1748 % \changes{v1.0e}{2021/09/28}
1749 % {Make patching of commands a global operation (gh/674)}
1750 % \begin{macrocode}
1751 \cs_gset_eq:NN #1 \kerneltmpDoNotUse
1752 % \end{macrocode}
1753 % Finally, update the hook code.
1754 % \begin{macrocode}
1755 \@@_update_hook_code:n {#2}
1756 }
1757 %<latexrelease>\EndIncludeInRelease
1758 %<latexrelease>\IncludeInRelease{2021/06/01}{\@@_patch_retokenize:Nnnn}
1759 %<latexrelease> {cmd~hooks~with~args}
1760 %<latexrelease>\cs_gset_protected:Npn \@@_patch_retokenize:Nnnn #1 #2 #3 #4
1761 %<latexrelease> {
1762 %<latexrelease> \cs_set_eq:NN \kerneltmpDoNotUse \scan_stop:
1763 %<latexrelease> \cs_set_eq:NN \@@_tmp:w \scan_stop:
1764 %<latexrelease> \use:x
1765 %<latexrelease> {
1766 %<latexrelease> \cs_set:Npn \@@_tmp:w
1767 %<latexrelease> ####1 \tl_to_str:n { macro: } ####2 -> ####3 \s_@@_mark
1768 %<latexrelease> {
1769 %<latexrelease> ####1 \def \kerneltmpDoNotUse ####2
1770 %<latexrelease> {
1771 %<latexrelease> \str_if_eq:nnT {#3} { before }
1772 %<latexrelease> { \token_to_str:N \UseHook { cmd / #2 / #3 } }
1773 %<latexrelease> ####3
1774 %<latexrelease> \str_if_eq:nnT {#3} { after }
1775 %<latexrelease> { \token_to_str:N \UseHook { cmd / #2 / #3 } }
1776 %<latexrelease> }
1777 %<latexrelease> }
1778 %<latexrelease> \tl_set:Nx \exp_not:N \l_@@_tmpa_tl
1779 %<latexrelease> { \exp_not:N \@@_tmp:w \token_to_meaning:N #1 \s_@@_mark }
1780 %<latexrelease> }
1781 %<latexrelease> \tl_rescan:nV { #4 \@@_patch_required_catcodes: } \l_@@_tmpa_tl
1782 %<latexrelease> \cs_gset_eq:NN #1 \kerneltmpDoNotUse
1783 %<latexrelease> }
1784 %<latexrelease>\EndIncludeInRelease
1785 % \end{macrocode}
1786 % \end{macro}
1787 %
1788 % \subsection{Messages}
1789 %
1790 % \begin{macrocode}
1791 %<latexrelease>\IncludeInRelease{2023/06/01}{wrong-cmd-hook}%
1792 %<latexrelease> {Standardise~generic~hook~names}
1793 %<latexrelease>\EndIncludeInRelease
1794 %<latexrelease>\IncludeInRelease{2021/06/01}{wrong-cmd-hook}%
1795 %<latexrelease> {Standardise~generic~hook~names}
1796 %<latexrelease>\msg_new:nnnn { hooks } { wrong-cmd-hook }
1797 %<latexrelease> {
1798 %<latexrelease> Generic~hook~`cmd/#1/#2'~is~invalid.
1799 %<latexrelease>% The~hook~should~be~`cmd/#1/before'~or~`cmd/#1/after'.
1800 %<latexrelease> }
1801 %<latexrelease> {
1802 %<latexrelease> You~tried~to~add~a~generic~hook~to~command~\iow_char:N \\#1,~but~`#2'~
1803 %<latexrelease> is~an~invalid~component.~Only~`before'~or~`after'~are~allowed.
1804 %<latexrelease> }
1805 %<latexrelease>\EndIncludeInRelease
1806 \msg_new:nnnn { hooks } { cant-patch }
1807 {
1808 Generic~hooks~cannot~be~added~to~'#1'.
1809 }
1810 {
1811 You~tried~to~add~a~hook~to~'#1',~but~LaTeX~was~unable~to~
1812 patch~the~command~because~it~\@@_unpatchable_cases:n {#2}.
1813 }
1814 \cs_new:Npn \@@_unpatchable_cases:n #1
1815 {
1816 \str_case:nn {#1}
1817 {
1818 { undef } { doesn't~exist }
1819 { macro } { is~not~a~macro }
1820 { expl3 } { is~a~private~expl3~macro }
1821 { retok } { can't~be~retokenized~cleanly }
1822 }
1823 }
1824 % \end{macrocode}
1825 %
1826 %
1827 % \begin{macrocode}
1828 %<latexrelease>\IncludeInRelease{0000/00/00}{ltcmdhooks}%
1829 %<latexrelease> {The~hook~management~system~for~commands}
1830 %<latexrelease>
1831 % \end{macrocode}
1832 % The command \cs{@@_cmd_begindocument_code:} is used in an
1833 % internal hook, so we need to make sure it has a harmless
1834 % definition after rollback as that will not remove it from the
1835 % kernel hook.
1836 % \begin{macrocode}
1837 %<latexrelease>\cs_set_eq:NN \@@_cmd_begindocument_code: \prg_do_nothing:
1838 %<latexrelease>
1839 %<latexrelease>\EndModuleRelease
1840 \ExplSyntaxOff
1841 %</2ekernel|latexrelease>
1842 % \end{macrocode}
1843 %
1844 % \begin{macrocode}
1845 %<@@=>
1846 % \end{macrocode}
1847 %
1848 % \Finale
1849 %
1850 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1851 \endinput
1852
1853 ^^A Needed for emacs
1854 ^^A
1855 ^^A Local Variables:
1856 ^^A mode: latex
1857 ^^A coding: utf-8-unix
1858 ^^A End: