James A. Rosen
James A. Rosen

Reputation: 65232

How do I emit the text content of a reference in LaTeX?

I have a section:

\section{Introduction} \label{sec:introduction}

I'd like a link to the section where the link text is the name of the section. I can use hyperref:

The \hyperrf[sec:introduction]{Introduction} introduces the paper.

But that requires repeating the section title ("Introduction"). Is there a way to grab that? ref yields the section number, which isn't right. autoref yields "section " and then the section number, which isn't right, either.

Upvotes: 6

Views: 7369

Answers (3)

Will Robertson
Will Robertson

Reputation: 64510

There are a couple of packages that provide this for you. nameref is distributed as part of hyperref to do this:
https://ctan.org/pkg/nameref

There is a more general package for cross-referencing basically anything, called zref: https://ctan.org/pkg/zref

It's by the same author as hyperref, Heiko Oberdiek; it's the one that I would choose. Here's an example:

\documentclass[oneside,12pt]{article}
\usepackage[user,titleref]{zref}
\begin{document}
\section{Introduction of sorts.}\zlabel{sec:intro}
Hello
\subsection{Structure}
We begin in `\ztitleref{sec:intro}'.
\end{document}

Note that it even removes the trailing period in the section title.

Upvotes: 13

kquinn
kquinn

Reputation: 10740

As far as I know, there's no standard way to do this. Simply put, the sectioning commands don't store the names of the sections anywhere they can be easily retrieved. Yes, they're inserted into the Table of Contents (and associated auxiliary file) and marks are set, but access to those is unreliable at best and usually impossible without additional context, which is almost always unavailable by the time you need to refer back to the section.

The code sample you posted looks like what I would write. There might be a package to automate this, but if one exists it's probably pretty hairy code since this is really not a particularly common use case. Actually, to go all grammar nazi on you the final text you're creating is incorrect; the word "introduction" should be lowercase inside the sentence, and this can't be achieved (in general) with backreferences to the actual section titles.

I'd just suck it up and write out references like this manually. There won't be enough of them to justify automation. Of course, if you're doing something more involved than your example suggests (many auto-generated sections or something) things might be different, but if that's the case it's really a different question entirely.

Upvotes: 1

You could try using

  • \newsavebox
  • \savebox
  • \usebox

which won't save you any typeing but will give you a single authoritative source for each title


And you might search ctan.org, I suspect this has been done already.

Upvotes: 0

Related Questions