# Why does enumitem need the macro to exist already?

I'm using pgf and enumitem to define a hexadecimal enumeration scheme as follows:

\documentclass{article}
\usepackage{pgf,enumitem}

\makeatletter

\newcommand*{\Hex}[1]{%
\expandafter\@Hex\csname c@#1\endcsname
}
\newcommand*{\@Hex}[1]{%
\pgfmathdectoBase\The@Hex{#1}{16}\The@Hex
}

%------------------------------------------------------------
% Why does cutting this line cause it to fail?
%------------------------------------------------------------
\AtBeginDocument{\pgfmathdectoBase\The@Hex{1}{16}}
%------------------------------------------------------------

\makeatother

\begin{document}

\begin{enumerate}[label=\Hex*]
\item First
\item Letters
\item More
\item Another
\item Ten!
\end{enumerate}
\end{document}

Now if I remove the highlighted line, the compilation fails and I can't understand why. It tells me:

! Undefined control sequence.
<argument> \The@Hex

I'm trying to understand why it needs this macro to already be defined for the enumeration to work, especially since the value of \The@Hex isn't actually used until it is redefined by the use of enumerate...

-
Smells after an \edef context where the \The@Hex in \pgfmathdectoBase\The@Hex{.. is expanded. A typical fragility issue. It works when you use \DeclareRobustCommand to define \Hex. The question is: why does it work anyway then? – Martin Scharrer Jul 3 '11 at 22:13
@Martin: Never use \DeclareRobustCommand for things to which you would apply \label and \ref. – egreg Jul 3 '11 at 22:26
@egreg: you are totally right; I agree. However, Seamus code is fragile and therefore doesn't work with these macros anyway. – Martin Scharrer Jul 3 '11 at 22:28

There's a way that avoids assignments, making conversion to hexadecimal completely expandable:

\input{binhex}
\newcommand*{\Hex}[1]{\expandafter\hex\csname c@#1\endcsname}

binhex.tex is by David Kastrup.

As partly explained by Martin, one problem with \pgfmathdectoBase that performs assignments and so it's unusable in defining number representations for \ref, because the system has to use \edef (in the form of \protected@edef) in order to write in the aux file the actual number and not a command. With your definition, assigning \label to an item and trying \ref with it would result in an error.

Since an enumerate is probably not too long, one can use

\newcommand{\Hex}[1]{\expandafter\@Hex\csname c@#1\endcsname}
\newcommand{\@Hex[1]{\ifnum#1>15 \@ctrerr\else\hexnumber@{#1}\fi}

maybe extending the definition of \hexnumber@ to cover more cases.

-
Nice. I was just going to point out that LaTeX provides \def\hexnumber@#1{\ifcase\number#1 0\or 1\or 2\or 3\or 4\or 5\or 6\or 7\or 8\or 9\or A\or B\or C\or D\or E\or F\fi} which could also be expanded to number larger than 15. – Martin Scharrer Jul 3 '11 at 22:32