Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 7 down vote accepted

This is fairly easy:

enter image description here

\documentclass{article}
\makeatletter
\newcommand{\mynameis}[1]{#1\renewcommand{\@currentlabel}{#1}}
\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)

enter image description here

\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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.