I want to provide two solutions. The first works without using the package hyperref
. The second answer supports hyperlinks.
\documentclass{article}
\usepackage{etoolbox,xstring,xspace}
\makeatletter
\let\origref\ref
\renewcommand*\ref[1]{%
\origref{#1}\xlabel{#1}}
\def\xlabel#1{%
\ifcsdef{siteref@doc@#1}{}{\csgdef{siteref@doc@#1}{,}}%
\@bsphack%
\csxdef{siteref@doc@#1}{\csuse{siteref@doc@#1},\thepage}%
\protected@write\@auxout{}%
{\string\SiteRef{siteref@#1}{\csuse{siteref@doc@#1}}}%
\@esphack%
}
\newrobustcmd*\SiteRef[2]{\csgdef{#1}{#2}}
\newrobustcmd*\xref[1]{%
\ifcsundef{siteref@#1}{%
\@latex@warning@no@line{Label `#1' not defined}
}{%
[\StrGobbleLeft{\csuse{siteref@#1}}{2}]\xspace%
}%
}
\makeatother
\usepackage{lipsum}
\begin{document}
\ref{tab:table}
\lipsum[1]
\begin{table}[!ht]
\begin{tabular}{ll}
\textbf{Name} & \textbf{Description} \\
Foo & bar \\
Foo & bar
\end{tabular}
\caption{Nice Table. Used on pages \xref{tab:table}.}
\label{tab:table}
\end{table}
\lipsum
\ref{tab:table}
\end{document}
Modifications to work with hyperref
\documentclass{article}
\usepackage{etoolbox,xstring,xspace}
\usepackage[colorlinks=true]{hyperref}
\makeatletter
\AtBeginDocument{%
\let\origref\ref
\renewcommand*\ref[1]{%
\origref{#1}\xlabel{#1}}
}
\newrobustcmd*\xlabel[1]{%
\ifcsdef{siteref@doc@#1}{}{\csgdef{siteref@doc@#1}{,}}%
\@bsphack%
\begingroup
\csxdef{siteref@doc@#1}{\csuse{siteref@doc@#1},\thepage}%
\protected@write\@auxout{}%
{\string\SiteRef{siteref@#1}{\csuse{siteref@doc@#1}}}%
\endgroup
\@esphack%
}
\newrobustcmd*\SiteRef[2]{\csgdef{#1}{#2}}
\newrobustcmd*\xref[1]{%
\ifcsundef{siteref@#1}{%
\@latex@warning@no@line{Label `#1' not defined}
}{%
\begingroup
\StrGobbleLeft{\csuse{siteref@#1}}{2}[\@tempa]\relax%
\def\@tempb{}%
\@tempcnta=0\relax%
\@tempcntb=\@ne\relax%
\def\do##1{\advance\@tempcnta\@ne}%
\expandafter\docsvlist\expandafter{\@tempa}%
\def\do##1{%
\ifnum\@tempcntb=\@tempcnta\relax%
\hyperpage{##1}%
\else
\hyperpage{##1},%
\fi%
\advance\@tempcntb\@ne
}%
[\expandafter\docsvlist\expandafter{\@tempa}]\xspace%
\endgroup
}%
}
\makeatother
\usepackage{lipsum}
\begin{document}
\ref{tab:table}
\lipsum[1]
\begin{table}[!ht]
\begin{tabular}{ll}
\textbf{Name} & \textbf{Description} \\
Foo & bar \\
Foo & bar
\end{tabular}
\caption{Nice Table. Used on pages \xref{tab:table}.}
\label{tab:table}
\end{table}
\lipsum
\ref{tab:table}
\end{document}
The package crossreference
defines the command \xref
too. So if you are load the package you have to rename the command \xref
.