4

Given sample code

\section{One}
\begin{enumerate}
\item\label{li:one}
\end{enumerate}

\section{Two}
\begin{enumerate}
\item\label{li:two}
\end{enumerate}

I am referencing \ref{li:one} and \ref{li:two}

I would like this to render as

I am referencing (A.1) and (1)

That is, I want to include the section number when referencing labels from another section, but omit it for labels within the same section. How can I do this?

EDIT: I am using enumitem as well as hyperref

1 Answers1

2

If you are not using hyperref, you can use the following:

\documentclass{article}
\usepackage{enumitem}% to demonstrate compatability
\usepackage{xstring}

\renewcommand{\thesection}{\Alph{section}}% is this the default?

\makeatletter
\newcommand{\refitem}[1]% #1 = label name
{\@ifundefined{r@#1}{??}{\begingroup%
  \edef\temp{\expandafter\detokenize\ref{#1}}%
  \StrCut{\temp}{.}\tempsection\tempitem%
  \if\thesection\tempsection\relax(\tempitem)%
  \else(\tempsection.\tempitem)%
  \fi
\endgroup}}
\makeatother

\begin{document}
\section{One}
\begin{enumerate}[ref=\thesection.\arabic*]
\item\label{li:one}
\end{enumerate}

\noindent I am referencing  \refitem{li:one} and \refitem{li:two}.

\section{Two}
\begin{enumerate}[ref=\thesection.\arabic*]
\item\label{li:two}
\end{enumerate}


\noindent I am referencing \refitem{li:one} and \refitem{li:two}.
\end{document}

cropped page

If you are using hyperref, you will need to replace the above \refitem with:

\usepackage{hyperref}
\makeatletter
\def\autoref#1#2#3#4#5\@nil{\edef\anchor{#3}}
\newcommand{\getrefanchor}[1]{\expandafter\expandafter\expandafter\expandafter
    \expandafter\expandafter\expandafter\autoref
    \expandafter\expandafter\expandafter\@gobble
    \csname r@#1\endcsname{}\@nil}

\newcommand{\refitem}[1]% #1 = label name
{\@ifundefined{r@#1}{??}{\begingroup%
  \edef\temp{\expandafter\detokenize\getrefnumber{#1}}%
  \StrCut{\temp}{.}\tempsection\tempitem%
  \getrefanchor{#1}% saves as \anchor
  \if\thesection\tempsection\relax\hyperlink{\anchor}{(\tempitem)}%
  \else\hyperlink{\anchor}{(\tempsection.\tempitem)}%
  \fi
\endgroup}}
\makeatother
John Kormylo
  • 79,712
  • 3
  • 50
  • 120
  • You define \getrefnummber but later call \getrefnumber --- which should it be? When I change it to \getrefnummber I get the error "Argument of @car has an extra }" – Yuri Sulyma Aug 26 '15 at 08:04
  • @Yuri Sulyma - Thank you, I didn't even notice. It seems that hyperref provides its own \getrefnumber (presumably due to http://tex.stackexchange.com/questions/140849/strange-output-of-getrefnumber-refcount-package-with-custom-enumeration…) – John Kormylo Aug 26 '15 at 13:05