6

i was idly wondering instead of having see Section \ref{labelname} produces

see Section 4.1.1

i could make it so that see Section \ref{labelname} produces

see Section 4.1.1 (p65)

is this possible? Would using hyperref mess this up?

lockstep
  • 250,273
GreyCloud
  • 409

3 Answers3

10

The cleaner way would be a new macro like in the answer of goodluck. But also \ref can be redefined. It should be done as late as possible, because many packages redefines it. In the solution it is done in \AtBeginDocument at the end of the preamble, especially after package hyperref is loaded.

Also package hyperref supports a star form that generates the reference without the link. For example, this is useful if the reference is part of another reference to avoid nested links.

\documentclass{article}
\usepackage{hyperref}

\makeatletter
\AtBeginDocument{%
  \newcommand*{\original@ref}{}%
  \let\original@ref\ref
  \@ifpackageloaded{hyperref}{%
    \renewcommand*{\ref}{%
      \@ifstar\newrefstar\newref
    }%
    \newcommand*{\newrefstar}[1]{%
      \original@ref*{#1} \textbf{(p\pageref*{#1})}%
    }%
    \newcommand*{\newref}[1]{%
      \hyperref[#1]{\newrefstar{#1}}%
    }%
  }{%
    \renewcommand*{\ref}[1]{%
      \original@ref{#1} \textbf{(p\pageref{#1})}%
    }%
  }%
}
\makeatother

\begin{document}
\section{Introduction}
\section{Foo bar}
\subsection{Hello World}
\label{sec:hello}
This is subsection \ref{sec:hello}.
\end{document}

Reference link with page

Heiko Oberdiek
  • 271,626
6

Maybe you would like to take a look at the varioref package with its command \vref. This will generate your demanded output. In addition, this does not have an effect on your hyperref settings.

lockstep
  • 250,273
6

You can define a command, like \myref

\newcommand{\myref}[1]{\ref{#1} (p\pageref{#1})}

Then you can use \myref{xxx}

goodluck
  • 321