2

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?

2

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}

enter image description here

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}
6
  • 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}}}?
    – frougon
    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.
    – egreg
    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”?
    – frougon
    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).
    – egreg
    Apr 7 '20 at 17:13
  • You're right, this makes sense, thanks!
    – frougon
    Apr 7 '20 at 17:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.