[Tex/LaTex] Hyperref breaks the all-caps ToC entries

etoolboxhyperrefmemoirtable of contents

I started out on this earlier question. I now have a simple and elegant etoolbox solution to making all-caps chapter entries, but leaving appendix entries untouched. Simple, elegant, and incompatible with hyperref, it seems.

MWE:

\documentclass{memoir}
\usepackage{etoolbox}
%\usepackage{hyperref}

\makeatletter
\ifpatchable*{\@chapter}{\typeout{Chapter can be patched}}{\typeout{Chapter cannot be patched}}
\patchcmd{\@chapter}%
{\addcontentsline{toc}{chapter}}%
{\let\f@rtocold\f@rtoc \def\f@rtoc{\uppercase\expandafter{\f@rtocold}} \addcontentsline{toc}{chapter}}%
{\typeout{Succeeded}}%
{\typeout{Failed}}
\makeatother

\begin{document}
\tableofcontents*

\chapter{One}
\chapter{Two}
\appendix \appendixpage
\chapter{Alpha}
\end{document}

which indicates that the \@chapter command can be patched, my patch succeeds, and I get the PDF output I wanted:

ToC with all-caps chapters, normal appendices, and no hyperrefs

Enabling the hyperref package reverts my changes to the ToC format, somehow:

ToC with normal chapters and appendices, plus hyperrefs


EDIT: After adding \tracingpatches to the preamble, the working version puts the following in the logs:

Chapter can be patched
[debug] tracing \patchcmd on input line 8
[debug] analyzing \@chapter
[debug] ++ control sequence is defined
[debug] ++ control sequence is a macro
[debug] ++ macro can be retokenized cleanly
[debug] ++ search pattern found in replacement text
[debug] ++ patching possible
[debug] == retokenizing macro now
Succeeded

and the failing version puts instead:

Chapter can be patched
[debug] tracing \patchcmd on input line 8
[debug] analyzing \@chapter
[debug] ++ control sequence is defined
[debug] ++ control sequence is a macro
[debug] ++ macro can be retokenized cleanly
[debug] -- search pattern not found in replacement text
Failed

I don't see any obvious places where hyperref modifies \@chapter, but I could have certainly missed something.


Final Working Example (including hyperref):

\documentclass{memoir}
\usepackage{etoolbox}
\ifpatchable*{\@chapter}{\typeout{Chapter can be patched}}{\typeout{Chapter cannot be patched}}
\patchcmd{\@chapter}%
{\addcontentsline{toc}{chapter}}%
{\let\f@rtocold\f@rtoc \def\f@rtoc{\uppercase\expandafter{\f@rtocold}} \addcontentsline{toc}{chapter}}%
{\typeout{Succeeded}}%
{\typeout{Failed}}
\makeatother
\usepackage{hyperref}

\begin{document}
\tableofcontents*
\chapter{One}
\chapter{Two}
\appendix \appendixpage
\chapter{Alpha}
\end{document}

ToC with hyperrefs, and in all caps

Best Answer

Load hyperref immediately before \begin{document} -- i.e., after all packages and after all macro redefinitions.

EDIT: This is not a general rule, only a solution for your minimal example.

Related Question