I would like to configure a custom command so that it only affects the document environment. Because the command changes a number of catcodes, it has to be included after the begin{document} tag in order to work properly. However, I would prefer to set it up so that I can include it in its own .sty file. Is there some way to define a command so that it is only active within the document environment?

The type of code that I am trying to use is similar to the following:

    \catcode`\_=13  \def_#1_{\emph{#1}}

When I typeset the document with the \AtBeginDocument command, the console stops at the \begin{document} line and notes the following:

Missing control sequence inserted.
<inserted text>

If I include the code (without the \AtBeginDocument{} rule) after the \begin{document} command, however, the document will process correctly.

  • 2
    Can you give an example?
    – egreg
    Oct 23, 2012 at 6:31

2 Answers 2


You can use \AtBeginDocument to execute code at the start of the \document environment. If you attempt to use \SomeNewCommand before \begin{document} you get an error.




    \newcommand*{\SomeNewCommand}{The command SomeNewCommand is now defined.}%

%\SomeNewCommand% Undefined


The code you propose

    \catcode`\_=13  \def_#1_{\emph{#1}}

can't work, because the _ is read as an argument to \AtBeginDocument and so its category code is frozen.

You can do it in an indirect way:


This works because ~ is active, so the \lowercase instruction will produce an active _. The \endgroup will revert the \lccode assignment, but when the change to the lowercase counterpart has already been performed.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .