# Define a command so that it is only active within the document environment

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:

\AtBeginDocument{
\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>
\inaccessible


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

-
Can you give an example? – egreg Oct 23 '12 at 6:31

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.

## Code:

\documentclass{article}

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

%\SomeNewCommand% Undefined

\begin{document}
\SomeNewCommand
\end{document}

-

The code you propose

\AtBeginDocument{
\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:

\AtBeginDocument{
\begingroup\lccode~=_
\lowercase{\endgroup\def~#1~}{\emph{#1}}%
\catcode_=\active
}


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.

-