In this question I have already been given a sophisticated way of achieving what I set out to do. This question is not a "how do I do this" question - I already have an answer to that - it is a "explain for me what is the flaw in the approach I attempted" question.
The original problem was that the \crefname
macro provided by the cleveref package was not having any effect within a \foreach
. It was pointed out by jfbu (in an answer) and egreg (in a comment) that the problem was that \crefname
has an effect only locally, and the changes are discarded at the end of every loop iteration. In the time before egreg posted an answer providing a solution, it occurred to me to use the \foreach
to build a command to perform the \crefname
changes, then call that command after the loop had ended. I used the \global
macro to make the changes global. Unfortunately, the \global
causes error messages to appear, and I don't know why. Here is my attempt:
\documentclass[a4paper]{amsart}
\def\myTheoremEnvironments{%
theorem/theorems,%
cobblestone/cobblestones,%
toybox/toyboxes%
}
\usepackage{tikz, titlecaps, cleveref}
% Number all definition, theorem, etc. environments using the same counter.
% Start counting again at the start of each section.
% Style these environments using LaTeX's "definition" style.
\theoremstyle{definition}
\newtheorem{baseTheorem}{Base Theorem}[section]
\def\mycrefnamecommands{}
\foreach \x/\y in \myTheoremEnvironments {
\edef\tmp{\noexpand\newtheorem{\x}[baseTheorem]{\noexpand\titlecap{\x}}}\tmp
\global\edef\mycrefnamecommands{\mycrefnamecommands\noexpand\crefname{\x}{\x}{\y}}
}
\mycrefnamecommands
\begin{document}
\section{Hello, and welcome to my document.}
\begin{cobblestone}
\label{csref}
Hello. I am an ``cobblestone'' environment.
\end{cobblestone}
\begin{toybox}
\label{tbref}
I am a ``toybox'' environment. What a strange name that is for an environment.
\end{toybox}
\begin{theorem}
\label{thmref}
People trying to do strange things with ``foreach'' should expect trouble.
\end{theorem}
Here are some references to \cref{csref}, \cref{tbref} and \cref{thmref}.
I could have tried using just one call to ``cref'' here,
but it's best not to run before you can walk.
\end{document}
Here is the error message. I tried googling it, but I don't see any particularly useful results.
! Argument of \@ynthm has an extra }.
<inserted text>
\par
l.66 }
\gdef
is global\def
,\xdef
is global\edef
\global\edef
to\xdef
, it results in the same error message.;-)