[Tex/LaTex] insert code before chapter title

chapterssectioningtitlesec

I would like to insert some code before the chapter title appears. I have defined:

\newcommand{\toptitle}[2]{\itshape #1 \hfill #2 \par}

Then, if I am writing for example:

\begin{document}
\toptitle{Quantum Mechanics}{15.10.2011}
\chapter{My Chapter}
\end{document}

the chapter title does not appear because this code precedes it. I am using the titlesec package but couldn't find a command to append code before the chapter title. Is it possible?

Best Answer

Without using titlesec, you can redefine the \@makechapterhead command (defined in book.cls) which actually typesets the chapter title; you could do something along these lines:

\documentclass{book}
\usepackage{lipsum}

\newcommand\toptitle{}
\makeatletter
\def\@makechapterhead#1{%
  \vspace*{50\p@}%
  {\parindent \z@ \raggedright \normalfont
    \ifnum \c@secnumdepth >\m@ne
      \if@mainmatter
        \toptitle\par
        \huge\bfseries \@chapapp\space \thechapter
        \par\nobreak
        \vskip 20\p@
      \fi
    \fi
    \interlinepenalty\@M
    \Huge \bfseries #1\par\nobreak
    \vskip 40\p@
  }}
\makeatother

\begin{document}

\renewcommand\toptitle{{\itshape Quantum Mechanics\hfill 15.10.2011}}
\chapter{Test chapter}
\lipsum

\end{document}

enter image description here

Using the etoolbox package, the above redefinition can be done in a shorter way:

\documentclass{book}
\usepackage{etoolbox}
\usepackage{lipsum}

\newcommand\toptitle{}
\makeatletter
\patchcmd{\@makechapterhead}{\if@mainmatter}{\if@mainmatter\toptitle\par}{}{}
\makeatother

\begin{document}

\renewcommand\toptitle{{\itshape Quantum Mechanics\hfill 15.10.2011}}
\chapter{Test chapter}
\lipsum

\end{document}