# Reference to items with section number, if in another section

Consider the document

\documentclass{scrartcl}
\begin{document}
\section{A}
\begin{enumerate}
\item\label{a} a
\end{enumerate}

\section{B}
\begin{enumerate}
\item\label{b} b
\end{enumerate}
Items \ref{b} and \ref{a}.
\end{document}


It prints out "Items a and a".

Instead, I'd like it to print out "Items a and 1.a"; i.e., I want the section number included in the reference, but, unlike this question, only if the reference is in another section.

How easily is this achieved?

You can put before the reference a (robust) macro that checks the current value of section against the value stored when the \label was issued.

\documentclass{article}
\usepackage{pdftexcmds,etoolbox}

\makeatletter
\labelformat{enumi}{\maybe{section}{\thesection}#1}
\renewcommand{\theenumi}{\alph{enumi}}
\newrobustcmd{\maybe}[2]{%
\ifnum\pdf@strcmp{\csname the#1\endcsname}{#2}=\z@
\else
#2.%
\fi
}
\makeatother

\begin{document}
\section{A}
\begin{enumerate}
\item\label{a} a
\end{enumerate}

\section{B}
\begin{enumerate}
\item\label{b} b
\end{enumerate}
Items \ref{b} and \ref{a}.
\end{document}


A slightly different version from a suggestion by frougon:

\documentclass{article}
\usepackage{etoolbox}

\makeatletter
\labelformat{enumi}{\maybe{section}{\arabic{section}}{\thesection}#1}
\renewcommand{\theenumi}{\alph{enumi}}
\newrobustcmd{\maybe}[3]{%
\ifnum#2=\value{#1}%
\else
#3.%
\fi
}
\makeatother

\begin{document}
\section{A}
\begin{enumerate}
\item\label{a} a
\end{enumerate}

\section{B}
\begin{enumerate}
\item\label{b} b
\end{enumerate}
Items \ref{b} and \ref{a}.
\end{document}

• This is smart! Maybe the following: \labelformat{enumi}{\maybe{section}{\number\value{section}}#1} and, for the test, \ifnum\number\value{#1}=#2  would be desirable in case the document author does things like \renewcommand{\thesection}{\textbf{\arabic{section}}}? Apr 7 '20 at 17:01
• @frougon If the user adds formatting to \thesection, they do at their own risk. One is free to shoot one's own foot, but can't blame the weapon. Anyway, that's a good idea. Apr 7 '20 at 17:08
• Ah... thanks for your reply! I thought \thefoobar was for formatting counter foobar. So, if I understand what you mean, \thefoobar would be reserved to expandable formatting like \roman, \alph and similar? And \p@〈type〉 and \@seccntformat would be for “non-expandable formatting”? Apr 7 '20 at 17:12
• @frougon The idea was good, but now \maybe needs three arguments, because I have to store also \thesection (which might be nonnumeric). Apr 7 '20 at 17:13
• You're right, this makes sense, thanks! Apr 7 '20 at 17:19