5

Suppose I defined an environment with an optional argument (using xparse) as in

\documentclass{article}
\usepackage{hyperref,xparse}
\newcounter{exercisecounter}
\stepcounter{exercisecounter}
\DeclareDocumentEnvironment{exercise}{o}
{\IfNoValueTF{#1}{Exercise \theexercisecounter:}{Exercise \theexercisecounter (#1):}}
{}
\begin{document}
\begin{exercise}[My Exercise]
This is my exercise.
\end{exercise}
Above is \nameref{my exercise}, which is Exercise \ref{my exercise}.
\end{document}

If I'd like to reference the exercise's title and the exercise counter using nameref and ref, respectively, how would I go about doing it? In general, given an arbitrary environment with an optional argument, how would I got about telling hyperref to use the optional argument as the title and a specified counter?

I understand that a solution would likely be based on using xpatch, but this is the extent of my knowledge.

2
  • You can get into trouble, as \nameref is not expandable!
    – user31729
    Commented Dec 27, 2014 at 20:00
  • @ChristianHupfer Thanks, I guess I need to learn a little more about the importance about expandability.
    – Hayden
    Commented Dec 27, 2014 at 20:23

1 Answer 1

6

You have to set the title using nameref's \NR@gettitle macro:

enter image description here

\documentclass{article}
\usepackage{hyperref,xparse}% hyperref also loads nameref
\newcounter{exercisecounter}
\makeatletter
\DeclareDocumentEnvironment{exercise}{o}
  {\par\refstepcounter{exercisecounter}%
   Exercise \theexercisecounter
   \IfNoValueF{#1}{ (#1)\NR@gettitle{#1}}%
   :\quad}
  {\par}
\makeatother
\begin{document}
\begin{exercise}[My Exercise]
This is my exercise.\label{my exercise}
\end{exercise}
Above is \nameref{my exercise}, which is Exercise \ref{my exercise}.
\end{document}

Also note, for reference purposes, you need \refstepcounter (inside the environment). Also, the above setup doesn't do much when you don't supply an optional argument. That can be adopted, but then again you won't use \nameref when it doesn't have an optional argument...

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .