[Tex/LaTex] How to cross-reference text with a custom label/reference text

cross-referencinglabelsnaming

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?

Best Answer

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}
Related Question