4

I found the etoolbox package that allows me to add commands at the beginning of another command.

I tried the following but this does not work:

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

I want to reset a certain value at the beginning of every chapter with the call to \exewidth. How can this be done?

Stefan Müller
  • 6,901
  • 3
  • 29
  • 61

1 Answers1

5

The definition of \chapter in the book class is

% book.cls, line 365:
\newcommand\chapter{\if@openright\cleardoublepage\else\clearpage\fi
                    \thispagestyle{plain}%
                    \global\@topnum\z@
                    \@afterindentfalse
                    \secdef\@chapter\@schapter}

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.

You're also adding unwanted spaces, but that's a minor detail.

The proper place to add \exewidth is at the start:

\pretocmd{\chapter}{% <--- IMPORTANT
    \exewidth{(34)}% <--- IMPORTANT
}{}{}

but, of course, this would add the setting also when \chapter* is called. In case you want it only for numbered chapters, the right command to patch is \@chapter, again with \pretocmd.


Suppose you add \exewidth{(34)} at the end. When \secdef is executed, it absorbs its two arguments (in this case \@chapter and \@schapter) and looks for a following *; there's no *, because the next token is \exewidth, so, according to its definition, \secdef delivers \@dblarg{\@chapter}. Note that \exewidth has only been examined, but is still in the input stream.

Now \@dblarg is executed; its action consists first in looking whether [ follows. No, there's \exewidth; good, so look for an argument (represented by #1) and do \@chapter[#1]{#1}.

What's #1? Usually it would be the chapter title, if you type \chapter{Title}. But here there's still the \exewidth token pending. No brace, so \exewidth becomes #1.

Is this what you want? ;-)

egreg
  • 1,121,712