# How to include a labelled item only if referenced?

In the text, I have some \ref{a}...

At the end, I have a list of

\item first \label{a}
...
\item last \label{z}


I want to show only the first item. I tried defining a custom ref such that it also defines a variable and ref, like so:

mycustomref[1] -> \newcommand{#1} \ref{#1}

mycustomlabel -> if a is defined, show the item a


But it turns out \newcommand{#1} is not valid, as it literally interprets it as #1. Thanks so much.

• \newcommand{#1} is no valid syntax of course. If understand your question correctly, you need a test whether a label is referred to already and then show the content, otherwise hide it. – user31729 Jan 17 '19 at 21:56
• Yes! I couldn't find custom package for it – Mong H. Ng Jan 17 '19 at 21:59
• Do you not want to show \ref{z} because it is undefined, or because you have never used \ref{z} before? If the former, you can use \@ifundefined{r@#1}{...}{...}. – John Kormylo Jan 18 '19 at 17:42

The easiest way is to use a \@namedef each time \mycustomref is used and a wrapper for \item, checking whether the name is already used.

However, this does work this way only if the reference is done in advance, i.e. before the custom item macro is applied.

\documentclass{article}

\makeatletter
\newcommand{\mycustomref}[1]{%
\@namedef{referred::#1}{#1}%
\ref{#1}%
}

\newcommand{\mycustomitem}[2]{%
\@ifundefined{referred::#2}{%
}{\item #1 \label{#2}}
}
\makeatother

\begin{document}

See \mycustomref{foo} %but also \mycustomref{foobar}

\begin{enumerate}
\mycustomitem{Foo}{foo}
\mycustomitem{Foobar}{foobar}
\end{enumerate}

\end{document}

• This will also fail, if none of the items is referred to as well → the enumerate environment will complain then – user31729 Jan 17 '19 at 22:06