4

Consider the following example, what is the correct way to use \csname and \endcsname inside \xpatchcmd?

\documentclass{article}

\usepackage{regexpatch}

\begin{document}

\def\foo{foo} \def\bar{with a macro \foo}

\bar

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

\bar

\end{document}

Jinwen
  • 8,518
  • I don't think that the first two argument of \xpatchcmd are ever expanded. (BTW, at least it should be \csname foo\endcsname, but it does not work either). You need a bit of \expandafter magic, so I let it to other wizards. Are you sure this is not a "XY" problem? (But you can have a look at https://tex.stackexchange.com/questions/104506/expanding-arguments-before-macro-call, so you can see what I mean by \expandafter magic...) – Rmano Mar 01 '22 at 08:41
  • @Rmano When I write the MWE I expected \csname foo\endcsname and \csname\foo\endcsname to be the same since the content of \foo is exactly foo. And true, this is a "XY" problem, I'm trying to patch command inside another command which receives certain names of macros as its argument, so I think using \csname here can be convenient. – Jinwen Mar 01 '22 at 08:46
  • @Rmano Actually I tried to use the o specifier in expl3 without success. I believe an expl3 approach can save us from those terribly many \expandafters. – Jinwen Mar 01 '22 at 08:52
  • Yes I tried but got stuck in the problem of generating a variant \exp_args:Nnonnn – Rmano Mar 01 '22 at 08:58

1 Answers1

4

In the next release of LaTeX there will be \ExpandArgs and you will be able to do

\ExpandArgs{nc}\xpatchcmd{\bar}{\foo}{bar}{}{\FAIL}

This is already possible in the development branch; if you run pdflatex-dev on the code

\documentclass{article}

\usepackage{regexpatch}

\begin{document}

\def\foo{foo} \def\bar{with a macro \foo}

\ShowCommand\bar

\ExpandArgs{nc}\xpatchcmd{\bar}{\foo}{bar}{}{\FAIL}

\ShowCommand\bar

\end{document}

the console will show

> \bar=macro:
->with a macro \foo .
<argument> \bar

l.10 \ShowCommand\bar

? > \bar=macro: ->with a macro bar. <argument> \bar

l.14 \ShowCommand\bar

? ``

egreg
  • 1,121,712
  • Nice! Is \ExpandArgs documented somewhere? I expected that in this case it should be {nnc}... ;-) – Rmano Mar 01 '22 at 10:20
  • @Rmano You always want to jump over the next token, so the initial N is implied, see \exp_args_generate:n – egreg Mar 01 '22 at 10:21
  • Yes, but I thought that N←\xpatchcmd... aaahh, so c is applied to the expanded {\foo}, not to {bar}... (color me confused. I will need a bit of time. And I found the docs, in https://osl.ugr.es/CTAN/macros/latex-dev/base/usrguide3.pdf) – Rmano Mar 01 '22 at 10:24