Skip to content

Instantly share code, notes, and snippets.

@carandraug
Created August 24, 2024 01:29
Show Gist options
  • Save carandraug/056acb11bc9a99aabbfcaf36c9d90aa6 to your computer and use it in GitHub Desktop.
Save carandraug/056acb11bc9a99aabbfcaf36c9d90aa6 to your computer and use it in GitHub Desktop.
Latex scoped \label and \ref
\documentclass[12pt,a4paper,twoside,openright]{report}
%% Scope references to the chapter level. This works by redefining
%% the \label and \ref commands so that all references have their
%% current chapter number (\thechapter) prepended to them, both at
%% label and reference time. This prevents the referencing of things
%% outside the chapter.
%%
%% Refer to https://en.wikibooks.org/wiki/TeX/let for details on \let
%% and \renewcommand.
\let\OriginalLabel\label
\renewcommand{\label}[1]{\OriginalLabel{\thechapter-#1}}
\let\OriginalRef\ref
\renewcommand{\ref}[1]{\OriginalRef{\thechapter-#1}}
\begin{document}
\chapter{Introduction}
The value of the variable \texttt{\textbackslash{}thechapter} is now
\thechapter (it should be the number of the chapter). It will change
each time a new chapter starts.
\chapter{Paper X}
\section{Introduction}
\label{sec:intro}
The value of the variable \texttt{\textbackslash{}thechapter} is now
\thechapter (it should be the number of the chapter).
\section{Results}
The introduction for this chapter is Section \ref{sec:intro}).
\chapter{Paper Y}
\section{Introduction}
\label{sec:intro}
\section{Results}
The introduction for this chapter is Section \ref{sec:intro}).
\chapter{Paper Z}
\section{Introduction}
\label{sec:intro}
The value of the variable \texttt{\textbackslash{}thechapter} is now
\thechapter (it should be the number of the chapter).
\section{Results}
The introduction for this chapter is Section \ref{sec:intro}).
\end{document}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment