3

How can we give a name to a label so that when we do the cross-reference, instead of displaying the number of the section, we have the name of the label?

For example,

\underline{homogeneity in preferences(HP)\phantomsection\label{hyp3}}

When I use \ref{hyp3} I would like the shown reference text to be HP and not e.g. 5.1 that is the number of the section.

Can someone help me?

nox
  • 4,160
  • 12
  • 26

2 Answers2

6

Taking the excellent answer by egreg (Labeling a text and referencing it later) and modifying it to take an additional optional argument I could come up with the solution below. It creates a new command \labeltext that can be referenced to. It takes two parameters and one optional parameter:

\labeltext[optional short ref]{the labeled text}{label name}

If you want to, you can set the markup or highlighting of the label and (optionally) the reference, too. I set it to \emph rather than \underline as underlining looks bad to me and is considered bad practice.

result

MWE:

\documentclass{article}
%\usepackage{underlin}
%\usepackage{hyperref}

\makeatletter
\newcommand{\labeltext}[3][]{%
    \@bsphack%
    \csname phantomsection\endcsname% in case hyperref is used
    \def\tst{#1}%
    \def\labelmarkup{\emph}% How to markup the label itself
    %\def\refmarkup{\labelmarkup}% How to markup the reference
    \def\refmarkup{}%
    \ifx\tst\empty\def\@currentlabel{\refmarkup{#2}}{\label{#3}}%
    \else\def\@currentlabel{\refmarkup{#1}}{\label{#3}}\fi%
    \@esphack%
    \labelmarkup{#2}% visible printed text.
}
\makeatother

\begin{document}
Some text. This is text. \labeltext{This is the labeled text with lab1}{lab1}. More text.\\
\labeltext[shorter text 2]{Long labeled text 2}{lab2}\\
\labeltext[HP]{homogeneity in preferences (HP)}{hyp3}

This reference shows lab1: \ref{lab1}.\\
This reference shows lab2: \ref{lab2}.\\
Reference to \ref{hyp3}.
\end{document}
nox
  • 4,160
  • 12
  • 26
3

It seems like you’re using the ref-mechanism for something like acronyms so you might want consider using the glossaries package instead. That'll give you also the opportunity to automatically create a list of uses acronyms/abbreviations.

Here’s an example how to use the package to print the acronym: first time the full text and from there one only the abbreviation/acronym.

\documentclass[
   english,
]{scrartcl}

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{babel}

\usepackage{glossaries}

\newacronym{hp}{HP}{homogeneity in preferences}

\begin{document}

This is the first sentence about \gls{hp}.

Somewhere later in the doc it is used again as \gls{hp}.

\end{document}

enter image description here

And by the way: Please do not use underlining!

Tobi
  • 56,353