0

I would like to redefine \ref to behave like \cref while still allowing \ref* to be used for the standard behavior of \ref. Here is my attempt to achieve this; I would like to use the commented lines instead of the uncommented lines, but unfortunately I get an error. My reference for creating starred commands was the following: https://texfaq.org/FAQ-cmdstar

\documentclass{article}
    \usepackage{cleveref}
\let\oldref\ref
\renewcommand{\ref}{%
    \makeatletter
        \@ifstar
            \oldref%
            \cref%
    \makeatother
}

\begin{document}

\begin{equation} \label{eqn:2.2.4} 2 + 2 = 4 \end{equation}

\oldref{eqn:2.2.4}

\cref{eqn:2.2.4}

% \ref{eqn:2.2.4}

% \ref*{eqn:2.2.4}

\end{document}

David Carlisle
  • 757,742
Stirling
  • 1,419
  • 1
    Do not put \makeatletter and \makeatother inside the \renewcommand (which fails for two different reasons) but outside of it: \makeatletter\renewcommand{\ref}{\@ifstar\oldref\cref}\makeatother. – Qrrbrbirlbel Jul 07 '13 at 09:48
  • Note that the package hyperref defines \ref* to not produce a link, so you could be in trouble if you load this package. – egreg Jul 07 '13 at 10:01
  • Why would you want to use \ref instead of \cref? The semantics are clearly different, someone not familiar with your change will have a difficult time parsing your LaTeX code. – krlmlr Jul 12 '13 at 00:35

1 Answers1

2

Do not put \makeatletter and \makeatother inside the \renewcommand. This fails for two reasons:

  1. \@ifstar sees \makeatother as the next character and not a * which may or may not follow.

  2. When TeX processes the contents of the definition the catcodes of @ are already read (and set to 12 (other)). (So you actually define it as \@ followed by the letters ifstar.

The correct definition would be

\makeatletter
\renewcommand*{\ref}{\@ifstar\oldref\cref}
\makeatother

(For the * used here refer to What's the difference between \newcommand and \newcommand*?)

Qrrbrbirlbel
  • 119,821