12

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.

1
  • perhaps the apptocmd from the etoolbox?
    – cmhughes
    Commented Dec 23, 2012 at 6:01

1 Answer 1

10

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

enter image description here

\documentclass{memoir}% http://ctan.org/pkg/memoir
\let\oldchapter\chapter% Store \chapter in \oldchapter
\newcounter{mycounter}
\renewcommand{\chapter}{%
  \setcounter{mycounter}{2}% Insert "your content" here
  \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.

4
  • 1
    Don't you need \LetLtxMacro to take care of all optional parameters?
    – NVaughan
    Commented Dec 23, 2012 at 4:57
  • 1
    How about chapter[header-title][toc-title]{title}?
    – NVaughan
    Commented Dec 23, 2012 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
    Commented Dec 23, 2012 at 15:47
  • 1
    @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
    Commented Dec 23, 2012 at 15:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .