2

I would like to add code at the beginning of every chapter. In particular, the \minitoc command. I hoped \appto would do the trick. But no luck.

\usepackage{etoolbox}
\appto\chapter{Test}

Just uses T as the chapter title and est after the chapter.

Using \apptocmd does not work either. I looked, for example, at Is it possible to add a command at the beginning of a chapter?. Unfortunately, its title is misleading, I think.

Here is a complete example:

\documentclass{book}

\usepackage{etoolbox}
\appto\chapter{Test}

\begin{document}

\chapter{One}

\end{document}

Which renders as

enter image description here

Daniel
  • 1,787

1 Answers1

5

\chapter is just a top level command, it actually doesn't take any argument, neither does it typeset anything. It just takes LaTeX to the correct page (recto/verso) and sets the page style and some other minor things, then it calls \@chapter or \@schapter, depending if you used \chapter or \chapter* (all of this for the book class; other classes might behave differently). The fact that \chapter doesn't take arguments, make so that if you append Test to its definition, is the same as if you did:

\chapter Test{One}

and that's why the chapter title becomes T and the rest (estOne) is typeset below it. Which is what egreg meant in his answer (in the post you linked) with:

If you do

\apptocmd{\chapter}{
    \exewidth{(34)}
}{}{}

(note the two trailing arguments, look at the documentation of etoolbox for a description), you make the command \secdef to fail.

He also gives a thorough explanation of what happens at the end of his answer.

You need to patch the inner \@chapter (and \@schapter if you want \chapter* too), which writes stuff to the table of contents and sets page headings, or yet, to \@makechapterhead (and \@makeschapterhead) which is the macro which does the actual typesetting of the chapter heading, depending on what exact effect do you want.

You were also missing the success and failure branches of \apptocmd which are used if the patching succeeded or failed.

\documentclass{book}
\usepackage{etoolbox}
\makeatletter
\apptocmd\@chapter % or \@makechapterhead
  {Test}
  {}{\FAILED}
% \apptocmd\@schapter % or \@makeschapterhead
%   {Test}
%   {}{\FAILED}
\makeatother
\begin{document}
\chapter{One}
\end{document}

enter image description here