## Sunday, June 29, 2008

### LaTeX clever references

When you're referencing a section in LaTeX, you'd usually write something like
… as we saw in section \ref{sec:cake}.
But this is somewhat inconvenient. LaTeX knows that it's a section, right? So why the need to specify this? Worse, if you ever change it into a subsection, your reference will be wrong.

Luckily there's the command \autoref from the hyperref package. However, this too has some drawbacks, mainly that it does not provide a capitalised version. A better alternative is to use the package cleveref. It is not in the Ubuntu repositories, but you can simply download and extract the archive, then run latex cleveref.ins to obtain cleveref.sty and dump it in the directory along with your document.

\usepackage{cleveref}
and make sure it's the last package to load; that is, even laster that hyperref.

Using \cref the previous example becomes:
… as we saw in \cref{sec:cake}.
This will produce the text “… as we saw in section 3.”. At the start of a sentence you'd use the capitalised version \Cref:
\Cref{sec:cake} gives the recipe …
You can even write:
See also \cref{sec:cake,sec:lie,eq:recipe,thm:delicious}.
This produces “See also sections 2 and 3, eq. 5 and theorem 1.” Although I doubt that anyone would use this very often, it's still pretty cool.

You can customize the word that is printed before the number. For example, some people like them to be always capitalised. (I don't, but my supervisor does, and who am I to argue?)
\crefname{chapter}{Chapter}{Chapters} \crefname{section}{Section}{Sections} \crefname{subsection}{Section}{Sections} \crefname{subsubsection}{Section}{Sections} \crefname{figure}{Figure}{Figures} \crefname{table}{Table}{Tables}
Etcetera. Note that subsections and subsubsections are usually all referenced to as sections.

Finally, as a bonus, here's how you make it work with references to \subfloats from the subfig package:
\crefname{subfigure}{Figure}{Figures}
(Capitalise according to taste, or even write “subfigure” if you like.)

For more options, see the cleveref documentation.

Georg Muntingh said...

I believe that whether you use a capitol or not depends on if you are referring to it as a proper noun (as in "see Chapter 1") or as a common noun (as in "see the previous chapter").

Anyway, nice tip!

Anonymous said...

Please also note that you can capitalise specific instances by using the \Cref command instead of \cref:

\crefname{assump}{assumption}{assumptions}

...

\Cref{assump_blabla} lalilala.

=> Assumption 4 lalilala.