[Tex/LaTex] Reference range of sections with a dash

cross-referencing

In my document, I reference a string of sections within a sentence. A representative example would be:

I am referencing Sections \ref{A}, \ref{B}, \ref{C}.

This then comes out t something like:

I am referencing Sections 6.1, 6.2, 6.3.

How can I get it to display:

I am referencing Sections 6.1-3

without hard-coding it?

Best Answer

Using the cleveref package you can compress a range and using \crefstripprefix (recent versions of the package), you can remove the common prefixes from reference range:

\documentclass{book}
\usepackage{cleveref}

\crefrangelabelformat{section}{#3#1#4--#5\crefstripprefix{#1}{#2}#6}

\begin{document}

\setcounter{chapter}{5}
\chapter{Test chapter}

As we see in \cref{sec:testa,sec:testb,sec:testc}...

\section{Test section}
\label{sec:testa}
\section{Test section}
\label{sec:testc}
\section{Test section}
\label{sec:testb}

\end{document}

enter image description here

Using \crefrangelabelformat you can customize the format for a range of references. It has the syntax:

\crefrangelabelformat{<type>}{<format>}

The first argument specifies the <type> of references that will be customized; for the second argument, the cleveref documentation explains:

The argument should contain six arguments: #1, #2, #3, #4, #5, #6. The first two (#1 and #2) are the formatted versions of the two label counters defining the reference range. The next two (#3 and #4) denote the beginning and end of the hyperlink for the first reference, the final two (#5 and #6), the hyperlink for the second reference. The hyperlink arguments must appear in order.

\crefstripprefix simply removes the prefix (the chapter number, in this case) from the second part of the range.

Here's an enhanced example in which the prefix has been stripped out for cross-references to ranges of sections, subsections and equations:

\documentclass{book}
\usepackage{cleveref}

\crefrangelabelformat{section}{#3#1#4--#5\crefstripprefix{#1}{#2}#6}
\crefrangelabelformat{subsection}{#3#1#4--#5\crefstripprefix{#1}{#2}#6}
\crefrangelabelformat{equation}{(#3#1#4--#5\crefstripprefix{#1}{#2}#6)}

\begin{document}

\setcounter{chapter}{5}
\chapter{Test chapter}

As we see in \cref{sec:testa,sec:testb,sec:testc}...

As we see in \cref{ssec:testa,ssec:testb,ssec:testc}...

As we see in \cref{equ:testa,equ:testb,equ:testc}...

\section{Test section}
\begin{equation}
\label{equ:testa}
a = b.
\end{equation}
\begin{equation}
\label{equ:testb}
a = b.
\end{equation}
\begin{equation}
\label{equ:testc}
a = b.
\end{equation}
\label{sec:testa}
\section{Test section}
\label{sec:testc}
\subsection{Test ssubection}
\label{ssec:testa}
\subsection{Test ssubection}
\label{ssec:testb}
\subsection{Test ssubection}
\label{ssec:testc}
\section{Test section}
\label{sec:testb}

\end{document}

enter image description here