Assume there is defined a macro \foo:
\def\foo{\bar\space A hash {in {braces: \string##}\string##}}
Expanding a control word token/macro token \foo yields:
\bar\spaceA11␣10h11a11s11h11␣10{1i11n11␣10{1b11r11a11c11e11s11:12␣10\string#6}2\string#6}2
Assume none of the control sequence tokens ocurring within this is \outer.
How to post-process to have each hash/each explicit character token of category 6/parameter doubled in order to get
\bar\spaceA11␣10h11a11s11h11␣10{1i11n11␣10{1b11r11a11c11e11s11:12␣10\string#6#6}2\string#6#6}2 ?
That in turn can be used as (a component of) the ⟨replacement text⟩ of another macro that is to be defined via \def and where I don't like to change to defining via \edef\AnotherMacro{\unexpanded{..}}/where I don't like to change to \edef\AnotherMacro{\the\tokenregister} as the code that carries out the \def and that would need to be changed comes from a macro package which is not mine and where I don't know if users rely on things not being changed/not being patched.
(Unfortunately, within replacement texts of many macros of pgfkeys, where a thing like \edef\macro{\unexpanded{#1}} could be used to allow hashes as components of the argument denoted by the parameter #1, \def\macro{#1} is used. This seems to be the case, e.g., with routines underlying handlers like .store in and .search also. In case this is already rectified in most recent pgfkeys: One of my colleagues still uses TeX Live 2018 and won't update until retiring.)
I know that \meaning, \write and \scantokens and \detokenize double hashes, but with these you loose information about categories of character tokens. And in case of flipping category codes of characters between 11 and s.th. else, you also don't know what characters belong to the names of what control sequences. And in case \escapechar is changed or not positive, you don't even know what characters belong to the names of control sequences at all.


\DoubleEveryHashis not bound to things being expanded. But as a side effect it replaces any explicit character tokens of category 1/2 by curly braces of category 1/2. This might be a problem with macros defined using#{-notation,{being an explicit character token of category 1 other than curly left brace. Double hashes inside macro definition? might be of interest, too. – Ulrich Diez Feb 12 '24 at 23:00