# bug in listings package?

It seems as if the listings package can not be loaded after all other packages using \AtBeginDocument

\documentclass[]{scrbook} %
\AtBeginDocument{\RequirePackage{listings}}
\begin{document}
\end{document}


This raises the error

! Undefined control sequence.

<argument> ... \iffalse }{}\lst@ifnumberbychapter


In the code sequence

\AtBeginDocument{
\@ifundefined{thechapter}{\let\lst@ifnumberbychapter\iffalse}{}
\lst@ifnumberbychapter
\newcounter{lstlisting}[chapter]
\gdef\thelstlisting%
{\ifnum \c@chapter>\z@ \thechapter.\fi \@arabic\c@lstlisting}
\else
\newcounter{lstlisting}
\gdef\thelstlisting{\@arabic\c@lstlisting}
\fi}


Is this a bug or am I misusing \AtBeginDocument ?

-
You probably are misusing \AtBeginDocument :-)
I had no idea packages can be loaded then; but it seems they can be. listings, however, uses \AtBeginDocument itself. I'd say that's why your code doesn't work.
Actually, I have checked: yes, listings \lets \lst@ifnumberbychapter in \AtBeginDocument.
I had problems with options clashes which could most easily be resolved by loaded the code of a whole package using \AtBeginDocument. since listings does not really depend on other packages and itself has no options clash problem I can load it directly at the loading of my package. –  Matthias Pospiech Jan 29 '13 at 16:17
@MatthiasPospiech with etoolbox you have AtEndPreamble. –  jfbu Jan 29 '13 at 20:59