I'm trying renew \ref command to auto detect equation and figure. All my labels of equations start with "eq:" and all labels of figures with "fig:".

So I try this way, but it isn't works for me:

\documentclass[a4paper, 12pt]{article}

% Is it equation? => add brackets
\newcommand\myref[1]{\in@{eq:}{#1} \ifin@ (\ref{#1}) \else \ref{#1} \fi }


Cite to eq: \cite{eq:test}, cite to fig: \cite{fig:test} % WORK FINE, add brackets
Ref to eq: \ref{eq:test}, ref to fig: \ref{fig:test}     % DOESN'T WORK :-(


 a = b


The output is, that \cite behave as I want (add brackets, if label starts with "eq"), but \ref doesn't. It is ignoring me:-(

(I inspired in thread \renewcommand{\cite} does not work ; so I tried command \let too)

I know about \eqref, but I have in many documents \ref and now I want to highlight equations with brackets.

Some idea?


  • hyperref's \autoref can probably do what you are trying to do with this command...
    – Seamus
    Oct 29, 2010 at 16:49

4 Answers 4


Something (eg hyperref) is likely redefining \ref in the \AtBeginDocument hook. You can try moving your definitions out of the preamble. For the kind of thing you are trying to do I would recommend checking into the cleveref package, which can do many intelligent things with referencing commands.


It seems that Lev is right. In the document you posted, your \ref macro is never called since it is redefined again at \begin{document}. If you move your definitions out of the preamble, then you'll get what I expected: \ref calls \myref, this calls again \ref, and you'll get a closed loop that'll produce a "TeX capacity exceeded" error. You indeed have to use \let in order to avoid this:

\newcommand\myref[1]{\in@{eq:}{#1} \ifin@ (\oldref{#1}) \else \oldref{#1} \fi }

Put this after \begin{document}, and everything will be as you wanted. Explanation: \let saves the original definition of \ref to \oldref, and the original definition can then be used in your \myref. This can't be done with \newcommand.


Don't reinvent the wheel; instead, use fncylab.

After I wrote this I noticed that you wanted to redefine \cite also. Why? It does not serve the same function as \ref and has its own style already.

  • No, I don't want redefine \cite, it was only example that my \myref works fine. Problem solved (see below), thank you very much.
    – Aznoh
    Oct 20, 2010 at 17:32

Great, it works, thanks a lot!

But if I use my \myref with calling \ref, I obtain this error:

TeX capacity exceeded, sorry.

I don't know why, but maybe it makes cycle \ref-->\myref-->\ref-->\myref...

So I use directly this way (cref gives brackets arround the equation automaticaly):

\begin{document} \let\ref\cref

And can use \ref for figure, tables, equation and for equation brackets are automaticaly added.

If you want change name of label, simply add to preambule:


See Manual for cleveref (PDF)

You must log in to answer this question.