# Nested parameters lost when generating new macros from package options

I've created a package which I would like to take in options and turn these into new macros (one new macro for each option). I also want these new macros to produce new macros in turn. For example, calling my package thus:

\usepackage[foo]{mypackage}


Should effectively run the following:

\newcommand{\foo}[1]{%
\def\fooMagic{some handling of #1}
}


My attempt thus far is below - in an example form.

\ProvidesPackage{mypackage}

\RequirePackage{xkeyval}

% Create a macro to create the macro that will create the macros:
\expandafter\newcommand\expandafter{\csname #1\endcsname}[1]{%
% Point A is here (for explanatory reasons that will become apparent)
\expandafter\def\csname #1Magic\endcsname{some handling of ##1}
}
}

% Interpret (unrecognised) options supplied to the package as new macro names:
\DeclareOptionX*{%
}

% Process the options:
\ProcessOptionsX*


Running this:

\documentclass{report}

\usepackage[foo]{mypackage}

\foo{bar}

\begin{document}

\fooMagic

\end{document}


Should have printed:

some handling of bar


But instead it results in an error (in the log):

Undefined control sequence.\fooMagic


If the following is inserted at Point A:

\PackageWarning{mypackage}{'#1','##1'}


The log shows that #1 is empty, printing:

'','bar'


I'm not really sure why this is happening. My guess is that it might be something to do with defining all the options and then processing them afterwards, at which point the original #1 values have been dropped. Although regardless of the cause, any help to get around/fix this would be much appreciated.

-

If you insert \show\foo into your document you will see that it is defined as

 \foo=\long macro:
#1->\expandafter \def \csname \CurrentOption Magic\endcsname {some handling of
#1} .


So not defined in terms of "foo" but of \CurrentOption which doesn't have a useful definition by the time you execute this.

On the grounds that a few extra \expandafter cure all known ills, I suggest:

\DeclareOptionX*{%

That works beautifully thank you very much! Plus a handy command to boot - I've never encountered \show before, I shall have to remember it. Cheers David ^^ –  Staves Feb 19 '12 at 0:49