# using \nameref only if there is a name

I am referencing some sections (actually those will be custom defined in the end) by number, type and name. But it happens that there is no name. So I want to leave it out. How can I test for that?

A MWE:

\documentclass{article}

\usepackage{xcolor}
\definecolor{darkred}{rgb}{0.5,0,0}
\newcommand\doubleref[1]{\autoref{#1} (\nameref{#1})}

\begin{document}

Some text.

\section{}\label{sec:two}
Like meantioned in \doubleref{sec:thisthat} and \doubleref{sec:two}.

\end{document}


So in this example the second reference should automatically only be section 2 and not section 2 ().

I tried

\newcommand\doubleref[1]{\autoref{#1}\edef\nae@tmp{\nameref{#1}}\ifx\empty\name@tmp\relax\else\ (\name@tmp)\fi}


but \nameref does not seem to return an expandable version of the name.

-

When you say \label{x}, LaTeX stores the data in a macro called \r@x; the title (available when using hyperref) is the third of five token lists. In your case we want to test whether the title is empty, which means that the relevant token list contains only \relax, that hyperref always appends to the title.

\documentclass{article}

\usepackage{xcolor}
\definecolor{darkred}{rgb}{0.5,0,0}

\makeatletter
\long\def\cana@extract#1#2#3#4#5{\unexpanded{#3}}
\def\cana@relax{\relax}
\newcommand\doubleref[1]{\autoref{#1}%
\@ifundefined{r@#1}\relax{\edef\cana@temp{%
\expandafter\expandafter\expandafter\cana@extract\csname r@#1\endcsname}%
\ifx\cana@temp\cana@relax\else~(\nameref{#1})\fi}}
\makeatother

\begin{document}

Some text.

\section{}\label{sec:two}
Like meantioned in \doubleref{sec:thisthat} and \doubleref{sec:two}.

\end{document}


I use \edef, but protecting the title with \unexpanded, so that it won't be expanded completely, which could cause big problems. This is tested only when the macro associated to the label has already been read in from the .aux file.

-

Reimplementation of Gregorio's solution using package refcount. \getrefbykeydefault{#1}{name}{} extracts the nameref part of the reference #1. The command is full expandable. If there is not a name, then the test becomes \if\vcenter\vcenter. Otherwise the name expands to something non-expandable that differ from \vcenter. Instead of \vcenter also other non-expandable tokens can be used, it should be a token that does not occur at the start of a name.

\documentclass{article}

\usepackage{xcolor}
\definecolor{darkred}{rgb}{0.5,0,0}

\usepackage{refcount}
\newcommand*{\doubleref}[1]{%
\autoref{#1}%
\if\vcenter\getrefbykeydefault{#1}{name}{}\vcenter
\else
~(\nameref{#1})%
\fi
}

\begin{document}

Some text.

\section{}\label{sec:two}
Like meantioned in \doubleref{sec:thisthat} and \doubleref{sec:two}.

\end{document}


\newcommand*{\doubleref}[1]{%