Consider the following example, the same \xpatchcmd works outside ExplSyntax, but doesn't work inside. Why is this happening?




\def\bar{with a macro \foo}





% \xpatchcmd{\bar}{\foo}{bar}{}{\FAIL}


  • you have spaces in the \bar command and they have a different catcode in expl3. Mar 1, 2022 at 8:44
  • @UlrikeFischer But why would the space in \bar matters? The patched part {\foo} doesn't contain any space so I thought it should be able to get matched.
    – Jinwen
    Mar 1, 2022 at 8:48
  • patching has to reassemble the definition after the patch and that fails if the catcode regime is not the same. Mar 1, 2022 at 9:14

1 Answer 1


TeX provides only two ways of accessing the replacement text of a macro: either by expanding it or by using \meaning.

In some cases a patch can be made with the first method, but it's not a really general possibility.

The method used by etoolbox/xpatch and regexpatch exploits \meaning. The problem with \meaning is that the replacement text is delivered as a “string”: all characters of category code 12 (including the backslash) except for spaces that retain category code 10.

A successful patch needs a few steps:

  1. the obtained string is passed through \scantokens in order to see whether reconstruction is possible;
  2. the reconstructed token list is compared with the original;
  3. the “find” token list is looked for in the reconstructed token list;
  4. if it is found, it is replaced.

Failure of the second step will result in the patch not being applied. You must remember that \scantokens (or its expl3 wrapper) uses the category code regime current at the moment it is applied; in the scope of \ExplSyntaxOn, spaces have category code 9 and you don't want to reconstruct a macro ignoring spaces in the original one.

This is the reason why your \bar is not patchable inside the scope of \ExplSyntaxOn.

A possible improvement of regexpatch could be using category code tables, but it's major work. But the main idea is that extensive patching is bad.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .