Home > hyperref > glossaries package: hyperlink only on first use of acronym

glossaries package: hyperlink only on first use of acronym

April 15Hits:1
Advertisement

By default, the glossaries package creates a link to the glossary for each occurrence of an entry (e.g. each time I use \gls{entry}). With the links visualized (e.g. using hyperref colorlinks). This becomes really cluttered if an entry is used many times.

I would rather prefer that only the first occurrence of an entry is hyperlinked. Is this possible?

Answers

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 \@[email protected]:

\documentclass[a4paper,10pt]{article}

\usepackage[colorlinks]{hyperref}
\usepackage{glossaries}

\usepackage{etoolbox}
\makeatletter
%% patch first occurence of "\@[email protected][#1]{#2}{\@[email protected]}", as this is the one for \glsused{#2}
\patchcmd{\@[email protected]}
  {\@[email protected][#1]{#2}{\@[email protected]}}
  {\@[email protected][#1,hyper=false]{#2}{\@[email protected]}}
  {}{}
\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 \@[email protected] and \@[email protected] need similar patching:

\patchcmd{\@[email protected]}
  {\@[email protected][#1]{#2}}
  {\@[email protected][#1,hyper=false]{#2}}
  {}{}

\patchcmd{\@[email protected]}
  {\@[email protected][#1]{#2}{\MakeUppercase{\@[email protected]}}}
  {\@[email protected][#1,hyper=false]{#2}{\MakeUppercase{\@[email protected]}}}
  {}{}

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:

glossaries package: hyperlink only on first use of acronym

Related Articles

Copyright (C) 2018 ceus-now.com, All Rights Reserved. webmaster#ceus-now.com 14 q. 0.330 s.