# \AtBeginEnvironment not accepting parameters in the code

etoolbox's docs say in the section on environment hooks:

Parameter characters in the code argument are permissible and need not be doubled.

However, this won't compile:

\documentclass{article}

\usepackage{etoolbox}

\newenvironment{foo}[1]{}{}
\AtBeginEnvironment{foo}{begin hook: #1}

\begin{document}

\begin{foo}{bar}
Lorem ipsum dolor sit amet.
\end{foo}

\end{document}


The error message is

! You can't use macro parameter character #' in horizontal mode.
\@begin@foo@hook ->begin hook: ##
1
l.11 \begin{foo}
{bar}


Am I doing something wrong or the docs are mistaken?

The documentation is referring to a case such as

\documentclass{article}

\usepackage{etoolbox}

\newenvironment{foo}[1]{}{}
\AtBeginEnvironment{foo}{\newcommand\baz[1]{begin hook: #1}}

\begin{document}

\begin{foo}{bar}
\baz{Lorem} ipsum dolor sit amet.
\end{foo}

\end{document}


where we don't need to double the # tokens in the definition of \baz. That's in contrast with say

\documentclass{article}

\usepackage{etoolbox}

\newcommand\foo[1]{%
\newcommand\baz[1]{begin hook: ##1}%
}

\begin{document}

\begin{foo}{bar}
\baz{Lorem} ipsum dolor sit amet.
\end{foo}

\end{document}


where we do need to double # tokens.

The hook cannot access #1 for the environment any more than any other code can (it does not add to the underlying \foo but rather uses a dedicated macro). As such, if you want to access #1 you have to redefine \foo (or the equivalent \renewenviornment{foo}`).

• Thanks a lot! How obvious. It seems that I have spent too much time in normal programming languages recently, where you call functions instead of expanding macros... ;-) (Well, you do expand macros in Lisp, but I haven't used them very often recently). Jul 8 '15 at 11:07