Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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.

share|improve this question
2  
Can you give an example? –  egreg Oct 23 '12 at 6:31
add comment

2 Answers

up vote 6 down vote accepted

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.

References:

Code:

\documentclass{article}

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

%\SomeNewCommand% Undefined

\begin{document}
    \SomeNewCommand
\end{document}
share|improve this answer
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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