3

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?
user202729
  • 7,143
  • (I can't find an existing question/answer, and I feel that having a summary of the documentation is beneficial for me before reading the source code documentation. The source code documentation is quite long and contains some uninteresting details such as how to parse verbatim balanced argument) – user202729 Nov 14 '21 at 06:02

1 Answers1

4

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.

user202729
  • 7,143
  • There's also a little detail that it append ^^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
  • (similar to how if you write \a \b then the space between is gobbled by \a, because a is a letter. – user202729 Apr 10 '22 at 09:03