[Tex/LaTex] Why doesn’t \renewcommand{\ref}{\autoref} change \ref into \autoref

cross-referencinghyperref

First off, I'm very grateful of the help this community has provided me so far. Anyway, to my problem:

I feel like I'm missing something obvious here. I want…

\documentclass{article}

\usepackage{hyperref} 
\renewcommand{\ref}{\autoref}

\begin{document}
\section{Section Title} \label{anchor}
Blah Blah Blah. \ref{anchor}
\end{document}

to print as…

1 Section Title

Blah Blah Blah. section 1

but instead I get …

1 Section Title

Blah Blah Blah. 1

… so \ref is not being replaced with \autoref. How can I correct this? Do I have no option but to do a find-and-replace to change \ref to \autoref?

Best Answer

Ok, figured out a solution:

enter image description here

Notes:

  • None of the usual tricks of using:

    1. \renewcommand{\ref}[1]{\autoref{#1}}
    2. \def\ref#1{\autoref{#1}}
    3. \let\ref\autoref
    4. \LetLtxMacro\ref\autoref

    seem to work in this case.

    I suspect it is because hyperref does an \AtBeginDocument, so that some things get defined at the the start of the document. So using \AtBeginDocument puts our redefinition at the end of queue of commands that get executed \AtBeginDocument.

    And since placing the \AtBeginDocument to be before \usepackage{hyperref} does not work, this confirms that the suspicion was correct.

Code:

\documentclass{article}

\usepackage{hyperref} 


\AtBeginDocument{\renewcommand{\ref}[1]{\autoref{#1}}}

\begin{document}
\section{Section Title} \label{anchor}
Blah Blah Blah.  \autoref{anchor}  \ref{anchor}
\end{document}