# Restrict macro to an environment

I am quite a noob when it comes to customising LaTeX/XeLaTeX. I would like to know if there's a way to limit the usage of a macro to a specific environment.

Consider the following macro and environment:

\newcommand\myMacro[2]{#1 ... #2}
\newenvironment{myEnv}{...}{...}


I would like the following:

\begin{myEnv}
% The following two calls to \myMacro are valid.
\myMacro{...}{...} .... \myMacro{...}{...}
\end{myEnv}
% This one should not be valid and throw an error.
\myMacro{...}{...}


I know this might not be the best design. I just want to make sure that I can't use \myMacro outsite of myEnv.

-

All definitions inside an environment are local, so you can just define the macro at the begin of the environment. You need to double all # when doing so:

\newenvironment{myEnv}{%
\newcommand\myMacro[2]{##1 ... ##2}%
}{...}


Another alternative is to define the macro with a different name outside the environment and copy it to the official name using \let. Such internal macro normally use @ in their names so that users can't accidentally define macro with the same name.

\makeatletter
\newcommand\my@Macro[2]{#1 ... #2}
\newenvironment{myEnv}{%
\let\myMacro\my@Macro
}{...}
\makeatother

-
Thank you! I feel so stupid when I don't need some obscure TeX hack and the answer's so simple... Thank you! –  Minustar Apr 28 '11 at 7:22

You can also write:

\def\my@private@macro{code}


in the preamble, and then, when you define the environment:

\newenvironment{myenv}{\let\mymacro\my@private@macro + begin env code}{end env code}

-