# How to force a label to be a given string?

Normally I issue a command like \label{foo}, and this means that foo gets entered into a symbol table somewhere that says that it equals 14, or xiv, or aa, or whatever. These symbols are generated and incremented automatically, and to change the numbering system, I can use packages like alphalph.

Suppose I want to force foo to evaluate to some arbitrary string, such as "Socrates." E.g., I want something like \mynameis{Socrates}\label{foo}, and then when I say \ref{foo}, the result will not be "14" but "Socrates."

I want to completely bypass the normal system involving counters. If Socrates is the name of a chapter, then I don't expect LaTeX to be smart enough to automatically name the next chapter Plato. So, e.g.:

\chapter{The life of Socrates}\mynameis{Socrates}\label{foo}
...
\chapter{The life of Plato}\label{bar}
...


This is an error on my part. It's OK with me if bar is set to garbage, or if LaTeX chokes, or if bar is set to some arbitrary string such as Socrates2.

Is there some way to do this?

-

## 1 Answer

This is fairly easy:

\documentclass{article}
\makeatletter
\makeatother
\begin{document}
\mynameis{Socrates}\label{foo}%

Do you know about \ref{foo}?
\end{document}


\@currentlabel is the macro that is stored when you use \label (in addition to \thepage). So, all we do is update this to our liking before calling \label.

If you wish for this to be compatible with hyperref, you could issue an additional \phantomsection so the hyperlink is correct (and perhaps also update \@currentlabelname)

\documentclass{article}
\usepackage{hyperref}
\makeatletter
\newcommand{\mynameis}[1]{%
\phantomsection#1% Mark hyperlink
\renewcommand{\@currentlabel}{#1}%
\renewcommand{\@currentlabelname}{#1}}
\makeatother
\begin{document}
\mynameis{Socrates}\label{foo}%

Do you know about \ref{foo} or \nameref{foo}?
\end{document}


For more on cross-referencing, see Understanding how references and labels work.

-