# Undefined control squence \Hy@writebookmark upon patching section command in beamer

I attempted to provide a solution to Renew section command to wrap whole section in an environment and thought the best way was to use etoolbox to patch the \section command. But this leads to:

! Undefined control sequence.
l.1 ...metitle {Text 1}\let \Hy@writebookmark \org
@writebookmark {}


Here is the MWE:

\RequirePackage{etoolbox}
\documentclass{beamer}

\newif\ifInSection%
\global\InSectionfalse%
\makeatletter
\pretocmd\beamer@section{\ifInSection\end{frame}\fi\global\InSectiontrue}{}{}%
\apptocmd\beamer@section{\begin{frame}[fragile]{#1}}{}{}%
\makeatother

%\AtEndDocument{\end{frame}}% Needed to end the frame at \end{document}

\begin{document}
\section{Text 1}% Do a begin{frame} at end of this macro
Some text (1).
%\end{frame}% Start of next \section will do this

\section{Text 2}% Will end previous frame
Some text (2).
\end{frame}% Delete once \AtEndDocument above works
\end{document}


The \pretocmd is used to end the previous frame upon the start of a new \section, if a previous section was started. The \apptocmd is used to start the frame at the end of the \section.

I am not very familiar with beamer so not sure if there is an easier way to do this.

-
I think beamer needs to see \end{frame} in input, because it reads frame contents as an argument. Thus it will be hard to implement your idea. – Andrey Vihrov Sep 9 '11 at 15:35
Andrey is right. Beamer looks for the \end{frame} explicitly. (Actually, it looks for \end something but that still doesn't help you.) What you'd have to do is slurp up everything between the \sections and put it in a frame. The problem is that you don't know if your section will end with a \section or a \end{document} so you have to be careful how things are set up. – Loop Space Sep 11 '11 at 20:14

Beamer's frame-gathering routine works by slurping in stuff up to the next \end, at which it tests the next "thing" to see if it is {frame} or not (there's also some testing for nesting). Therefore at the time that the \begin{frame} is started, the \end{frame} needs to be in the token stream for it to find. The TeX processor won't expand stuff to find it.
Because it looks for the \end it might be possible to hook in to the macro so that there was a test for \end{document} which added in the required \end{frame}, but it would require rewriting the macro as a whole to get it to work with the \section command. There is no reason why \section can't appear inside a frame. And once the \section command is read, beamer has already decided what is and isn't a frame so it's too late to try to persuade it otherwise. The only way to make it reconsider is to allowframebreaks and have \section expand to add a \newpage. But this would involve TeX slurping in the whole document in one go, which is probably Not a Good Idea.