# Error with color package and \AtBeginDocument in cls file

I have myclass.cls with the following content:

\NeedsTeXFormat{LaTeX2e}
\ProvidesClass{myclass}
\AtBeginDocument{
\tableofcontents
\clearpage
}
\endinput


I also have mydoc.tex in the same folder with the following content:

\documentclass{myclass}
\usepackage{color}
\begin{document}
mydocument
\end{document}


Compiling gives me the error

Undefined control sequence. \begin{document}.

It would be fine if I do any of the following:

• move \AtBeginDocument{...} to mydoc.tex
• remove \tableofcontents
• remove \clearpage
• remove \usepackage{color}

Is this a bug?

• please show the actual error from ! to ? from the log file in a code block in the question, the form you show is just a misleading summary from your editor which does not show which command is undefined – David Carlisle Sep 29 '16 at 17:41

From the LaTeX Companion, 2nd edition, to \AtBeginDocument:

Note, however, that code in the \AtBeginDocument hook is part of the preamble. Thus, restrictions limit what can be put there; in particular, no typesetting can be done.

A better hook is provided as \AfterEndPreamble of package etoolbox, which is executed at the very end of \begin{document}, after the \AtBeginDocument stuff.

Short example as standalone file:

\documentclass{article}
\RequirePackage{etoolbox}
\AfterEndPreamble{
\tableofcontents
\clearpage
}
\usepackage{color}
\begin{document}
\section{Hello World}
\end{document}


The error is

! Undefined control sequence.
\set@color ...\@pdfcolorstack push{\current@color
}\aftergroup \reset@color
l.3 \begin{document}

?


That is \current@color which is not yet defined as colour (as well as fonts and many other things) are set up in \begin{document} and \AtBeginDocument is mainly aimed for loading preamble commands at the end of the preamble, it can not reliably be used for typesetting commands as it is executed too early.