nameref Doesn’t Work Properly with Theorem Environment

I came across not-so-expected behavior in nameref, the package responsible for creating named references, when used in conjunction with theorem environments such as the one provided by amsthm. For example take a look at the following LaTeX document.

\documentclass{article}
\usepackage{amsmath,hyperref}

\begin{document}
\section{My Section}
\newtheorem{theorem}{Theorem}
\begin{theorem}[My Theorem]
\label{theo:My}0=0
\end{theorem}
This is a named reference: \nameref{theo:My}
\end{document}

You would expect the named reference to refer to the theorem’s name. However in reality it refers to the section’s name.


While searching for a solution I came across the following answer by Catalin in StackOverflow, which suggest it’s an old bug in nameref that (according to the mailing list conversation he linked to) should have been resolved in nameref-2.37. This is a conversation from 2010, but my Ubuntu 12.04 still has nameref-2.31 from 2007.

It seems like Ubuntu is a bit behind at updating TeXLive. I’m considering at installing off-the-repo TeXLive so I would have up-to-date TeX installation. I think I had in my two years ago more up-to-date version of TeXLive. Migrating to the official distribution would probably fix the Debian bug causing the installation of culmus-latex to fail as well.

But in the meantime I’ve looked for a workaround. After reading the nameref documentation, I concluded that the problem is that nameref doesn’t properly hook the theorem-like environments to set the \@currentlabelname. A possible workaround requires defining the theorem environment using thmtools. The thmtools gives us the \thmt@optarg command which expands to the name passed to the theorem environment, so we’re able to set \@currentlabelname properly. Basically, you need to add the following line after the \begin{theorem}[some name] and before the \label part:

\makeatletter \let\@currentlabelname\thmt@optarg\makeatother

A full example this looks like this:

\documentclass{article}
\usepackage{amsmath,thmtools,hyperref}
\declaretheorem{theorem}

\begin{document}
\section{My Section}
\begin{theorem}[My Theorem]
\makeatletter \let\@currentlabelname\thmt@optarg\makeatother
\label{theo:My}0=0

\end{theorem}

This is a named reference: \nameref{theo:My}
\end{document}

I think a better solution would be to automatically hook after the \begin{theorem} to add the fix. This is maybe possible using \addtotheorempostheadhook, but I haven’t figured it out yet.

Update 2012-12-16: I’ve installed the offical TeXLive 2012, and it was easier than I thought. It also, as expected, fixed the problem.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.