0

I am using hyperref in conjunction with nameref and cleveref, and the objective is for \nameref{label} to be type-set in the link color (which it seems by default is red), but for \cref{label} to be typeset normally.

I tried the following, but unfortunately, it doesn't work. Can this be modified to work? If not, how to best achieve this behavior?

\documentclass{article}

\usepackage{etoolbox}
\usepackage{nameref}
\usepackage{hyperref}


\pretocmd{\nameref}{\begingroup\hypersetup{colorlinks}}{}{}
\apptocmd{\nameref}{\endgroup}{}{}

\begin{document}

\section{Section 1}\label{sct1}
Content of section 1.


\section{Section 2}\label{sct2}
Content of section 2.  Reference to \nameref{sct1}.

\end{document}
  • You're not loading cleveref in your example code... – Werner Jun 30 '16 at 7:07
  • @Werner I know. That's because the default is to not display the links, and so I already have the desired behavior for cleveref. The objective then is to modify the default behavior so as to obtain the correct behavior for nameref as well. The point of mentioning cleveref is that putting \hyersetup{colorlinks} in the preamble is not a viable solution. – Jonathan Gleason Jun 30 '16 at 7:10
  • \hypersetup is from hyperref, not cleveref – Runar Jun 30 '16 at 7:19
  • @RunarTrollet Yes it is. Sorry . . . I do not understand what you're getting at. I mean to say that if I put \hypersetup{colorlinks} in the preamble it would affect \crefs in my document (and I don't want it to). The idea was then to have \nameref turn on colorlinks when it was used, and then immediately turn it off again (using the \endgroup). As cleveref is not used directly for this method of solution, I didn't include it. – Jonathan Gleason Jun 30 '16 at 7:25
2

nameref does lots of redefinitions of its commands when\begin{document} is issued, in case this or that package is loaded. Therefore, we have to change its definition after all that.

Output

enter image description here

Code

\documentclass{article}

\usepackage{nameref}
\usepackage{xcolor}

\begin{document}
\makeatletter
\DeclareRobustCommand*{\nameref}{%
\color{red}%
        \@ifstar\T@nameref\T@nameref
        }%
\makeatother
\section{Section 1}\label{sct1}
Content of section 1.


\section{Section 2}\label{sct2}
Content of section 2.  Reference to \nameref{sct1}.

\end{document}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.