5

I am using my own solution to this question to create custom cross-references.

\documentclass{article}

\usepackage{hyperref}
\usepackage{lipsum}

\title{My notes for Bla}
\author{myself}

\newcommand{\thingnamestyle}[1]{\textsc{#1}}
\newcommand{\thingnamerefstyle}[1]{[\textsc{#1}]}
% This works, but is unnecessarily complicated
% \newcounter{thing}
%     \newcommand{\thing}[1]{%
%       \thingnamestyle{#1}%
%        \renewcommand{\thething}{\thingnamerefstyle{#1}}%
%        \refstepcounter{thing}%
%     }
\makeatletter
\newcommand{\thing}[1]{%
  \thingnamestyle{#1}%
  \def\@currentlabel{\thingnamerefstyle{#1}}%
}
\makeatother

\begin{document}
\section{Bla}
\lipsum[1]
  \thing{thing-Quick} \label{quick}
\lipsum[1]
  \thing{Task-Brown}  \label{brown}
\lipsum[1]
And \ref{quick} has been completed.
\end{document}

This works but hyperref inserts the wrong link in the \ref: clicking on it would jump to the section title, which, I suppose, is the last thing that sets \@currentlable other than my \thing macro.

If one defines \thing using ref counters as in the commented code above, the link seems to work properly.

What's missing to make \thing compatible with hyperref?

Bordaigorl
  • 15,135

1 Answers1

5

In order to yield an appropriate hyperlink, issue \phantomsection at the end of \thing:

\makeatletter
\newcommand{\thing}[1]{%
  \thingnamestyle{#1}%
  \def\@currentlabel{\thingnamerefstyle{#1}}%
  \phantomsection%
}
\makeatother

Note that if \thingnamerefstyle is expanded what written to the .aux file. It is sometimes more customary to \protect this:

  ...
  \def\@currentlabel{\protect\thingnamerefstyle{#1}}$
  ...
Werner
  • 603,163
  • Excellent! The \protect comment is also helpful. – Bordaigorl Sep 01 '14 at 11:07
  • 1
    The name \phantomsection is not very suggestive of its effect though. Could you expand a little on its meaning? – Bordaigorl Sep 01 '14 at 11:08
  • 1
    @Bordaigorl: Fundamentally documents are broken into compartments, or sectional units. These sectional units represent the only points of reference and are typically marked using \section. As such, since hyperlinks could be used for things other than jumps to sectional units, the author decided to create a "phantom section" to mark these locations. Look at the code for \phantomsection and you'll see that it's just an abbreviation for setting an appropriately-raised (to avoid jumping to the baseline of where it's called) hyperlink anchor. – Werner Sep 02 '14 at 05:10