Latex glossaries: Hyperref/Link only the first occurance of an entry in each section?
While you can manually renounce the hyperlink by using \glsentrytext{entry}
, or \glsentryname{entry}
, or \gls*{entry}
instead of \gls{entry}
, this is cumbersome, as one would have to track the place of the first usage oneself.
An automatic approach is to patch \@gls@
:
\documentclass[a4paper,10pt]{article}
\usepackage[colorlinks]{hyperref}
\usepackage{glossaries}
\usepackage{etoolbox}
\makeatletter
%% patch first occurence of "\@gls@link[#1]{#2}{\@glo@text}", as this is the one for \glsused{#2}
\patchcmd{\@gls@}
{\@gls@link[#1]{#2}{\@glo@text}}
{\@gls@link[#1,hyper=false]{#2}{\@glo@text}}
{}{}
\makeatother
\makeglossaries
\newglossaryentry{pear}{
name=pear,
description={an oddly shaped fruit}
}
\begin{document}
\gls{pear}, \gls{pear}, \gls{pear}, \gls{pear}.
\printglossaries
\end{document}
If you also use upper case variants \Gls
and \GLS
, the respective internal macros \@Gls@
and \@GLS@
need similar patching:
\patchcmd{\@Gls@}
{\@gls@link[#1]{#2}}
{\@gls@link[#1,hyper=false]{#2}}
{}{}
\patchcmd{\@GLS@}
{\@gls@link[#1]{#2}{\MakeUppercase{\@glo@text}}}
{\@gls@link[#1,hyper=false]{#2}{\MakeUppercase{\@glo@text}}}
{}{}
There's a hook \glslinkcheckfirsthyperhook
that gets used by commands like \gls
. It's original purpose was to assist with the opposite (don't hyperlink on first use) but it also can be used in this situation:
\documentclass{article}
\usepackage[colorlinks]{hyperref}
\usepackage{glossaries}
\makeglossaries
\renewcommand*{\glslinkcheckfirsthyperhook}{%
\ifglsused{\glslabel}%
{%
\setkeys{glslink}{hyper=false}%
}%
{}%
}
\newglossaryentry{sample}{name={sample},description={an example}}
\newglossaryentry{sample2}{name={another sample},description={another example}}
\begin{document}
First use: \gls{sample}, \gls{sample2}.
Next use: \gls{sample}, \gls{sample2}.
\printglossaries
\end{document}
This produces:
Edit: This works for all the \gls
-like commands that query the first use flag (e.g. \Gls
and \glsdisp
). It doesn't work for the \glstext
-like commands that don't query the first use flag (e.g. \glstext
and \glslink
).