Why hyperref's \url may be used in preamble within a macro but not within a box?

The following MWE, where a macro involving hyperref's \url is defined in the preamble, works like a charm:

\documentclass{article}
\usepackage{hyperref}
%
\newcommand\testmacro{\url{http://macro.org}}
%
\newsavebox{\testbox}
%
\begin{document}
\testmacro

\savebox{\testbox}{\url{http://boxes.org}}
\usebox{\testbox}
\end{document}


But, as soon as the box definition \savebox{\testbox}{\url{http://boxes.org}} is as well moved in the preamble, the following error message arises:

! Undefined control sequence.
\@urlcolor #1Hy@xspace@en...


Hence my question: why hyperref's \url may be used in preamble within a macro but not within a box?

• @JosephWright: Did you move the \savebox to the preamble? I get the error Denis mentions and have to use \AtBeginDocument{\savebox{\testbox}{\url{http://boxes.org}}} (and it is not surprising as hyperref delays a lot of definitions to the begin of the document). – Ulrike Fischer Oct 30 '14 at 10:33
• @UlrikeFischer Indeed, \AtBeginDocument does the trick. I agree hyperref delays a lot of definitions to the begin of the document, but why something like \AtBeginDocument is necessary for the box and not for the macro? – Denis Bitouzé Oct 30 '14 at 10:48

A macro definition is not executed at the point of definition, you can go

\newcommand\foo{\any old \rubbish }


and as long as {} match up \foo is defined. You may get an error later if you try to use \foo, but you get no error at this point, and if \any and \rubbish are defined by the time you use \foo there is no error.

Conversely a box is typeset as it is saved (which may expand macros)

 \savebox\mybox{\any old \rubbish }


will generate undefined command errors at that point as it can not typeset the material into a box.

• Is a box really typeset as it is saved? In such a case, \savebox\mybox{any old rubbish} (without any macro) in the preamble should give an error, isn't it? – Denis Bitouzé Oct 30 '14 at 11:03
• @DenisBitouzé yes it is typeset and no if you keep things simple you can usually typeset small amounts in the preamble as most classes at least set up \normalfont to be 10pt cmr, however it may typeset the wrong thing as many packages delay setting up fonts and math and languages to begin{document} – David Carlisle Oct 30 '14 at 11:06