3

I would like links to be coloured in general, but not the cleveref links in section titles.

MWE:

\documentclass{article}

\usepackage[colorlinks]{hyperref}
\usepackage[nameinlink]{cleveref}

\begin{document}

% The section to reference
\section{Section Title}\label{sec:A}

% Colour links in normal text, like this one
Reference to \cref{sec:A}.

% This colours the link even in the section title, which I don't want
\section{Reference to \Cref{sec:A}}

% This hides the link in normal text, so...
Reference to {\hypersetup{hidelinks}\cref{sec:A}}.

% ... this should do what I want, but doesn't work.
% \section{Reference to {\hypersetup{hidelinks}\Cref{sec:A}}}

\end{document}

1 Answer 1

5

The problem with commands in section titles is that they must either be expandable or robust. Both \Cref and \hypersetup are neither.

Since \hypersetup will change the setting only when typesetting text, it doesn't need to be expandable (and it's impossible to make it so). Thus you make it robust with:

\let\ORGhypersetup\hypersetup
\protected\def\hypersetup{\ORGhypersetup}

Now \Cref is different. It could be made robust, but then in the PDF bookmarks you would see Reference to sec:A which is not that good. You can, however, make it expandable when hyperref will set up the PDF bookmarks by loading the crossreftools package and doing:

\pdfstringdefDisableCommands{%
  \def\hypersetup#1{}%
  \let\Cref\crtCref
  \let\cref\crtcref
}

(I also disabled \hypersetup or you would get Reference to hidelinksSection 1 :).

Working code:

\documentclass{article}

\usepackage[colorlinks]{hyperref}
\usepackage[nameinlink]{cleveref}
\usepackage{crossreftools}

\let\ORGhypersetup\hypersetup
\protected\def\hypersetup{\ORGhypersetup}
\pdfstringdefDisableCommands{%
  \def\hypersetup#1{}%
  \let\Cref\crtCref
  \let\cref\crtcref
}

\begin{document}

% The section to reference
\section{Section Title}\label{sec:A}

% Colour links in normal text, like this one
Reference to \cref{sec:A}.

% This colours the link even in the section title, which I don't want
\section{Reference to \Cref{sec:A}}

% This hides the link in normal text, so...
Reference to {\hypersetup{hidelinks}\cref{sec:A}}.

% ... this should do what I want, but doesn't work.
\section{Reference to {\hypersetup{hidelinks}\Cref{sec:A}}}

\end{document}

output:

enter image description here

1
  • This answer solves also the wrong pdf bookmarks that the code from the question would produce. (Only solving the color-problem would be much easier, but your solution is much better.)
    – Jakob
    Aug 20, 2019 at 15:34

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .