# Setting a common prefix for macro names

Is it possible to set a common prefix for all macros in a package? Something like:

\def\prefix{mypackage}

\newcommand{{\prefix}macroone}{ ... } % does not work, of course
\newcommand{{\prefix}macrotwo}{ ... }


One would then call the macros as mypackagemacroone and mypackagemacrotwo.

-
– Peter Grill Jul 10 '11 at 16:53

You can use \csname <name> \endcsname to build a \<name> macro. You need to expand it first before you feed it to \newcommand:

\def\prefix{mypackage}
\expandafter\newcommand\csname\prefix macroone\endcsname{ ... }%


There is also \@namedef{<name>}<parameter text>{<expansion text>} which is simply a \expandafter\def\csname #1\endcsname. You could define your own macro like that which also inserts the prefix:

\def\prefix{mypackage}
\def\@pnamedef#1{\expandafter\def\csname\prefix #1\endcsname}
\@pnamedef{macroone}#1{Hello #1 World}


If you want to use \newenvironment instead to use its does-already-exists check and optional argument use:

\@ifstar
{\expandafter\newcommand\expandafter*\csname\prefix #1\endcsname}%
{\expandafter\newcommand\csname\prefix #1\endcsname}%
}%
\pnewcommand{macroone}[2][]{Hello #2 World #1}


Note that names here are only intended as examples and you should be careful which user-level macros (no @) you define.

-
\makeatletter
\def\Pnewcommand{\@star@or@long\Pnew@command}
\def\Pnew@command#1{%
\expandafter\@testopt\expandafter{%
\expandafter\@newcommand\csname\prefix#1\endcsname}0}
\makeatother

\def\prefix{my}
\Pnewcommand{macro}[1][!]{\message{Argument is #1}}
\Pnewcommand*{macrotwo}[1]{\message{Argument is #1}}

\mymacro
\mymacro[1]

\mymacrotwo{X}
\mymacrotwo{\par} % invalid



\makeatletter
\def\Prenewcommand{\@star@or@long\Prenew@command}
\def\Prenew@command#1{%
\begingroup \escapechar\m@ne
\xdef\@gtempa{{\expandafter\string\csname\prefix#1\endcsname}}%
\endgroup
\expandafter\@ifundefined\@gtempa
{\@latex@error{\expandafter\noexpand\csname\prefix#1\endcsname undefined}\@ehc}%
\relax
\let\@ifdefinable\@rc@ifdefinable
\Pnew@command{#1}}
\makeatother


It's a more or less straightforward rewriting of \renewcommand and \renew@command. For \newenvironment we can say

\newcommand{\Pnewenvironment}[1]{\newenvironment{\prefix#1}}


and so \Pnewenvironment{env}{start}{end} would define the environment myenv, if \prefix expands to \my.

-