11

Is there a way to combine the \ref and \nameref commands into a single command? I want to show the section number before the title. Right now I am doing it like this:

\ref{sec:optimizations} \nameref{sec:optimizations}

The problem is I am duplicating references. I would rather have it as one command. For example:

\myref{sec:optimizations}
Ludovic C.
  • 8,888
Mads
  • 143

1 Answers1

11

For drivers that do not support line breaks inside links (dvips/pdfmark driver) you can use the definition that jon has given in the comment:

\newcommand*{\myref}[1]{\ref{#1} \nameref{#1}}

or without line break after \ref:

\newcommand*{\myref}[1]{\ref{#1}~\nameref{#1}}

For the other drivers the full expression can be made into one link:

\newcommand*{\myref}[1]{%
  \hyperref[{#1}]{\ref*{#1} \nameref*{#1}}%
  %\hyperref[{#1}]{\ref*{#1}~\nameref*{#1}}%
}

Remarks:

  • The star form of \ref and \nameref prevents nested links. The link is already done by \hyperref. The optional argument takes a label name.
Heiko Oberdiek
  • 271,626