2

I want to create macros defined right after \item of enumerate environment. Those macros must be global in such a way that redefining the same macros in another enumerate must produce error.

I failed to do so in the following MWE because redefining the existing macros is still possible. Could you fix this issue?

\documentclass{article}
\newcommand\factory[2]{\expandafter\gdef\csname#1\endcsname{#2}}

\begin{document}
\begin{enumerate}
    \item \factory{foo}{This is foo.}
    \foo
    \item \factory{boo}{This is boo.}
    \boo
\end{enumerate}

\begin{enumerate}
    \item \factory{foo}{This is foo.}% this line should produce error!
    \foo
    \item \factory{goo}{This is goo.}
    \goo
\end{enumerate}
\end{document}
3
  • Do you mind explaining the first paragraph. I do not understand what it is you are trying to do.
    – daleif
    Commented Nov 10, 2015 at 16:43
  • @daleif: I want to define macros inside enumerates but the scope of their definition are global. In a single input file, there are no 2 identical macros. Commented Nov 10, 2015 at 16:47
  • Then test if foo is already defined before you do the gdef
    – daleif
    Commented Nov 10, 2015 at 16:49

1 Answer 1

1

Use \@ifdefinable:

\documentclass{article}

\makeatletter
\newcommand\factory[2]{%
  \expandafter\@ifdefinable\csname#1\endcsname{%
    \global\@namedef{#1}{#2}%
  }%
}
\makeatother

\begin{document}
\begin{enumerate}
    \item \factory{foo}{This is foo.}
    \foo
    \item \factory{boo}{This is boo.}
    \boo
\end{enumerate}

\begin{enumerate}
    \item \factory{foo}{This is foo.}
    \foo
    \item \factory{boo}{This is boo.}
    \boo
\end{enumerate}
\end{document}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .