0

My document has chapters and sections. When I refer to sections in the same chapter I write \ref{section_label} when I refer to section in a different chapter I write \ref{chapter_label}.\ref{section_label}. On paper this has the desired effect.

Unfortunately, hyperref produce (of course) two different links in place o one. So replace the latter reference with

\hyperref[section_label]{\ref{chapter_label}.\ref{section_label}}

This produces the desired behavior in some viewer (Okular, Evince) but it has no effect on others (PDF.js).

I don't think the 'hack' above is a correct use of hyperref. Any suggestion?

  • 3
    did you check cleverref or varioref? – Johannes_B Apr 30 '17 at 9:32
  • 1
    Not a solution, but I really find it confusing to mix and match the reference. You should be consistent and use the same notation throughout your paper, possibly with varioref which integrates the page number in the reference, or with the customizations of cleveref – Moriambar Apr 30 '17 at 9:39
  • Something like here? tex.stackexchange.com/questions/356248/… or here: tex.stackexchange.com/questions/353491/… ? – user31729 Apr 30 '17 at 9:40
  • 2
    I'd say \ref*{chapter_label}.\ref{section_label} – egreg Apr 30 '17 at 9:44
  • Why do you want that? Doesn't \ref{section_label} already contain the chapter number? – Arzigoglu Apr 30 '17 at 9:59
3

Normally formatting is done by \label (actually \refstepcounter). One could use multiple labels depending on how one wanted the reference to look. This uses the same \mylabel macro used here.

Hyperref uses its own labels which can be found using \getrefbykeydefault. Also, \ref is protected (will not expand until printed), so if you want to use it in a macro you need to use \getrefnumber instead. See refcount manual.

I threw in egreg's solution for comparison.

\documentclass{report}
\usepackage{hyperref}

\renewcommand{\thesection}{\arabic{section}}% non-standard definition

\makeatletter
\@ifpackageloaded{hyperref}%
  {\newcommand{\mylabel}[2]% #1=name, #2 = contents
    {\protected@write\@auxout{}{\string\newlabel{#1}{{#2}{\thepage}%
      {\@currentlabelname}{\@currentHref}{}}}}}%
  {\newcommand{\mylabel}[2]% #1=name, #2 = contents
    {\protected@write\@auxout{}{\string\newlabel{#1}{{#2}{\thepage}}}}}
\makeatother

\newcommand{\getrefanchor}[1]% #1 = label
  {\getrefbykeydefault{#1}{anchor}{Doc-Start}}

\begin{document}

One can use \ref*{chapter}.\ref{section}, \ref{mylabel} or 
\hyperlink{\getrefanchor{section}}{\getrefnumber{chapter}.\getrefnumber{section}}.

\chapter{chapter}\label{chapter}
\section{dummy}
\section{section}\label{section}\mylabel{mylabel}{\thechapter.\thesection}%
\end{document}
  • @egreg 's solution is what I was looking for. Thank you! – Primo Petri Apr 30 '17 at 18:55

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.