We know that cprotect package can be used to include verbatim content in title/section: \cprotect\section{\verb+123+}.
- How does it work?
- If I want to do something similar that the package cannot do by itself, how can I?
We know that cprotect package can be used to include verbatim content in title/section: \cprotect\section{\verb+123+}.
See cprotect source code documentation (on CTAN) for details how it works.
In short:
To understand how \cprotect works, we first have to understand how \protect works.
Recall that \protect ensures that the macro following it remains unexpanded, until
it's in a normal context.
For \verb and similar, we need a stronger requirement, that is, the argument following it
must not be read (tokenized) until \verb is executed in a normal context.
So to do that, \cprotect essentially (*) transforms
\cprotect\section{\verb+abc+}
to
\section{\protect\input{a-1.cpt}}
after writing \verb+abc+ to the file a-1.cpt.
This works, because \protect ensures that the file fed to \input is only tokenized in a normal context.
Of course, this (as well as \protect) relies on the content being eventually executed in a normal context.
If the argument is, for example, passed directly to \detokenize after only being expanded/never expanded at all,
it will not result in the final expected value. Example.
(*): actually the result is \protect\input a-1.cpt\relax.
^^E^^L at the end of the cpt file (just read the generated cpt file to see it.) to gobble the new line at the end of the file.
– user202729
Apr 10 '22 at 08:55
\a \b then the space between is gobbled by \a, because a is a letter.
– user202729
Apr 10 '22 at 09:03