How can I get cleveref to surround references with parentheses automatically?
Referencing Section 8.2.1 of the cleveref
documention,
Cross-reference formats for single cross-references are defined or redefined using the
\crefformat
and\Crefformat
commands, which are used by the\cref
and\Cref
commands respectively. These take two arguments: the cross-reference type, and the formatting code:\crefformat{type}{format}
For your purposes, we can use, for example:
\crefformat{figure}{(Figure~#2#1#3)}
\Crefformat{figure}{Figure~#2#1#3}
Note that I've used crefformat
for use with the \cref
command (not beginning of sentence), and Crefformat
for use with the Cref
command (beginning of sentence).
This gives
A complete MWE follows
% arara: pdflatex
% arara: pdflatex
\documentclass{article}
\usepackage{cleveref}
\crefformat{figure}{(Figure~#2#1#3)}
\Crefformat{figure}{Figure~#2#1#3}
\begin{document}
\begin{figure}[!h]
\rule{3mm}{2mm}
\caption{August}
\label{fig:foo}
\end{figure}
X exhibits Y \cref{fig:foo}.
\Cref{fig:foo} is a cross reference at the beginning of a sentence
\end{document}
I would not modify the workings of \cref
and friends directly. Instead, I would create a new macro called \pcref
-- short for "parenthetic \cref", I suppose -- as follows:
\newcommand\pcref[1]{(\cref{#1})}
As you can probably guess, \pcref
places round parentheses around the output of \cref
. No need for lots of separate \crefformat
directives. This approach preserves access to the standard definition of \cref
, should the need to do so arise.
For the following screenshot, I loaded the hyperref
package and specified the cleveref
option nameinlink
, in order to make visible what is, and is not, produced by \cref
.
\documentclass{article}
\usepackage[colorlinks,allcolors=blue]{hyperref} % optional
\usepackage[noabbrev,nameinlink]{cleveref}
\newcommand\pcref[1]{(\cref{#1})}
\begin{document}
\begin{figure}[t!] \caption{foo}\label{fig:foo}\end{figure}
\begin{figure}[h!] \caption{bar}\label{fig:bar}\end{figure}
\begin{table}[h!] \caption{foo}\label{tab:foo}\end{table}
\dots\ \pcref{fig:foo}, \pcref{fig:foo,fig:bar}, \pcref{tab:foo,fig:bar}, \dots
\bigskip vs.
\bigskip
\dots\ \cref{fig:foo}, \cref{fig:foo,fig:bar}, \cref{tab:foo,fig:bar}, \dots
\end{document}