# Can \subref and xr work together?

With xr I can cross-reference labels in another document. With subcaption I can refer to subfigures (or similar). But if I try to combine them both, it seems they don't recognise each other:

a.tex:

\documentclass{article}
\usepackage{subcaption}
\begin{document}
\section{Main}
\begin{figure}
\begin{subfigure}{0.5\textwidth}
A
\caption{}\label{fig:A}
\end{subfigure}
\begin{subfigure}{0.5\textwidth}
B
\caption{}\label{fig:B}
\end{subfigure}
\caption{A figure}\label{fig}
\end{figure}
See \ref{fig}, panels \subref{fig:A} and \subref{fig:B}.
\end{document}


b.tex

\documentclass{article}
\usepackage{subcaption}
\usepackage{xr}
\externaldocument[A-]{a}
\begin{document}
\section{Main}
See \ref{A-fig}, panels \subref{A-fig:A} and \subref{A-fig:B}.
\end{document}


After compiling a.tex, b.tex says:

LaTeX Warning: Reference sub@A-fig:A' on page 1 undefined on input line 7.

LaTeX Warning: Reference sub@A-fig:B' on page 1 undefined on input line 7.


If I change the \subref{A-fig:A} to \ref{A-sub@fig:B}, it seems to work as expected. Can the definition of \subref be modified to make it compatible with xr?

• Probably, but it would still use \ref{A-sub@fig:A} internally. Easiest solution would be to give \subref two arguments, as in \subref[A-]{fig:A}. Nov 22, 2022 at 2:27

well the problem is that both add a prefix to the label name.

You could change the xr prefix to a suffix

\documentclass{article}
\usepackage{subcaption}
\usepackage{xr}
\usepackage{etoolbox}
\makeatletter
\patchcmd\XR@test{\XR@prefix#2}{#2\XR@prefix}{}{\fail}
\externaldocument[-A]{a}
\begin{document}
\section{Main}
See \ref{fig-A}, panels \subref{fig:A-A} and \subref{fig:B-A}.
\end{document}


The alternative is to patch the subcaption commands (in both documents!) to switch to a suffix:

\usepackage{etoolbox}

\makeatletter
\patchcmd\subcaption@@label{sub@#2}{#2@sub}{}{\fail}
\patchcmd\subcaption@ref{sub@#2}{#2@sub}{}{\fail}
\makeatother