3

Using the book class equations, tables, figures and sections have the chapter number as first number of the label (e.g. the first equation of chapter 2 is equation 2.1).

I want to remove the chapter number from the label but I want to keep it when I refer to it (the best would be keeping it if and only if the reference is outside the chapter where the label is)

lockstep
  • 250,273
dPol
  • 253

1 Answers1

1

Here is how I would go:

\documentclass{book}

\usepackage{hyperref}
\usepackage{refcount}
\usepackage{xstring}

\newcommand\Ref{}
\newcommand\RefNum[1]{%
  \StrBehind{\getrefnumber{#1}}{.}[\Ref]
  \hyperref[#1]{\Ref}}

\newcommand\ChapNum[1]{%
  \StrBefore{\getrefnumber{#1}}{.}[\result]}

\newcommand{\myref}[1]{\ChapNum{#1}%
\ifnum\result=\thechapter \RefNum{#1}\else\ref{#1}\fi}

\begin{document}

\chapter{First}

\begin{figure}
\caption{\label{fig1}Figure chap 1}
\end{figure}

\begin{equation}
x+y=z
\label{eq1}
\end{equation}

\myref{eq1}

\chapter{Second}

\begin{figure}
\caption{\label{fig2}Figure chap 2}
\end{figure}

Here see the Figure \myref{fig1}.

\noindent
Here see the Figure \myref{fig2}.

\noindent
Here for the equation \myref{eq1}
\end{document}

The command \myref acts as the \ref command if you are referring to something in another chapter and suppress the chapter number if you are referring to something in the same chapter.

Ludovic C.
  • 8,888