[Tex/LaTex] Conditional loading of tocloft causes errors

table of contentstocloft

Looking for a way to customise a table of contents, I came across this recommendation to use tocloft. As per the suggestion (and the documentation), I've put a conditional in place which tests for the presence of subfig and loads the package appropriately.

This Minimum [non-]Working Example:

\documentclass{article}
\@ifpackageloaded{subfig}
    {\usepackage[titles,subfigure]{tocloft}}
    {\usepackage[titles]{tocloft}}

\begin{document}
    \tableofcontents
    \section{Section 1}
    Hello 1
    \section{Section 2}
    Hello 2
    \section{Section 3}
\end{document}

Produces several errors including:

./tocloft.tex:3: You can't use `\spacefactor' in vertical mode.
\@->\spacefactor 
Removing the call to `\@ifpackageloaded` and explicitly specifying 

and

Missing character: There is no รจ in font cmex10!
/usr/local/texlive/2011/texmf-dist/tex/latex/tocloft/tocloft.sty:35: You can't 
use `\spacefactor' in vertical mode.
\@->\spacefactor 

Looking around for a solution, the TeX FAQ suggests this is the result of the package using "… an internal command without taking 'precautions'". Explicitly calling either \usepackage[titles,subfigure]{tocloft} or \usepackage[titles]{tocloft} works as advertised and is how I'm currently working around the problem. I would, however, like to implement the conditional loading as a safety precaution.

In an effort to learn more about (La)TeX internals, I'd like to know what's the root cause of this error. Is this a problem specific to my (MacTeX 2011) installation, or can others reproduce it? Also, what can be done to fix it in this particular incidence? Maybe the package's current maintainer could provide some insight into this.

Best Answer

The problem here is a common one. The use of @ is restricted to style files. If you want to use it in your document preamble (or elsewhere), you need to encompass it using the

\makeatletter
...
\makeatother

pair. So, in your preamble, use

\makeatletter
\@ifpackageloaded{subfig}
    {\usepackage[titles,subfigure]{tocloft}}
    {\usepackage[titles]{tocloft}}
\makeatother

Read the entries @ and @ in macro names and \spacefactor complaints on the UK TeX FAQ, as well as the discussion What do \makeatletter and \makeatother do?