# re-define \ref and \label to include source filename?

I have a set of documents each with references that look like:

\ref{figure1}


and so on. This is no problem when building each document separately,but creates many duplicate references when using \include{} to create a composite document. Is is possible to redefine the \ref and \label commands to automatically include the source filename in the reference and label. Otherwise, I would have to hand-edit all my source files with new references to solve the duplicate references problem in the composite document. For example, document1.tex would have references like

\ref{figure1_document1}


and document2.tex would likewise have the following:

\ref{figure1_document2}


But I would like this to happen automatically by re-defining the commands instead of having to hand-edit each of the source files.

Any tips appreciated!

-
–  Werner Mar 12 '13 at 17:18

You can indeed redefine locally (in each included .tex file) the \ref and \label commands. Here is an example:

\documentclass{article}
\usepackage{filecontents}
\let\oldref\ref
\let\oldlabel\label

\begin{filecontents}{file1.tex}
\renewcommand{\ref}[1]{\oldref{#1-stuff}}
\renewcommand{\label}[1]{\oldlabel{#1-stuff}}

$$\label{eq} E=mc^2$$
Eq. \ref{eq}
\end{filecontents}

\begin{filecontents}{file2.tex}
\renewcommand{\ref}[1]{\oldref{#1-stuff2}}
\renewcommand{\label}[1]{\oldlabel{#1-stuff2}}

$$\label{eq} E=mc^2$$
Eq. \ref{eq}
\end{filecontents}

\begin{document}

\include{file1}
\include{file2}

\end{document}


In your case you can put the first two lines (which save the original \ref and \label commands) in your main file, and then put the \renewcommand at the beginning of each included file, as I was trying to mimic here using filecontents. Here I am giving manually the text to append to each label in the included file. Replacing stuff with \jobname will not automatically append the name of the included file, because \jobname will be the name of the main file, but perhaps it can be patched (Maybe this can help you). There are probably cleaner solutions, but this seems to work.

-
Thanks! That gets me part of the way there. –  reckoner Mar 13 '13 at 13:27