Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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.

share|improve this question

2 Answers 2

up vote 12 down vote accepted

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
share|improve this answer
    
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}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.