2

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?
1
  • (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, 2021 at 6:02

1 Answer 1

2

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.

2
  • 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, 2022 at 8: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, 2022 at 9:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.