# \AtBeginChapter?

Are there any hooks that work like \AtBeginDocument for chapters, sections, etc.? Something like \AtBeginChapter? I would like to have the following code:

\AtBeginChapter{%
\setcounter{mycounter}{2}%
. . .
}


Yes—I know that I can create my counter so as reset itself whenever a new chapter starts, with

\newcounter{mycounter}[chapter]


but I would like to have more control as to what happens when a new chapter, section, etc. starts.

-
perhaps the apptocmd from the etoolbox? – cmhughes Dec 23 '12 at 6:01

You can redefine \chapter to perform the specified tasks before calling the original \chapter macro:

\documentclass{memoir}% http://ctan.org/pkg/memoir
\let\oldchapter\chapter% Store \chapter in \oldchapter
\newcounter{mycounter}
\renewcommand{\chapter}{%
\oldchapter%
}
\begin{document}
\chapter{A chapter}
\themycounter
\end{document}


This works because the \chapter macro doesn't gobble its arguments right away (avoiding the choice of using \LetLtxMacro from letltxmacro, although it wouldn't hurt). It conditions on a * first, allowing one to interject your requirements first. Note that the original \chapter issues a page break before setting the title (if "your content" should be influenced by this).

The above should hold for the regular \chapter-defining document classes as well (report and book).

Sections are a little easier, since they are provided with a "hook" in memoir: \setsechook{<stuff>} would execute <stuff> before \section. It also provides \setsubsechook for \subsections and \setsubsubsechook for \subsubsections.

-
Don't you need \LetLtxMacro to take care of all optional parameters? – NVaughan Dec 23 '12 at 4:57
How about chapter[header-title][toc-title]{title}? – NVaughan Dec 23 '12 at 14:52
@NVaughan: See When to use \LetLtxMacro? regarding your choices for using \LetLtxMacro. \chapter in memoir technically does not take any arguments, so it's safe to use only \let. – Werner Dec 23 '12 at 15:47
@NVaughan: I'm not sure I understand your second comment. \chapter does not gobble the arguments (2 option + 1 mandatory). That is done by a different set of macros: \@m@mchapter (that captures the first [header-title] optional argument) and \@chapter (that captures the second [toc-title] optional argument, as well as the mandatory {title} argument). – Werner Dec 23 '12 at 15:52