Debian Codegraph @

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

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