Following a LaTeX beginners’ tutorial, I am toying around with custom environments and commands. The following is supposed to be the logical markup for (for instance) a student task:
\newenvironment{task}{
\newcommand{\subtask}[1]{
\begin{enumerate}[label={\alph*)},resume]\item{##1}\end{enumerate}}
}{}
(Note that this is a minimal example. I do realize that defining the environment like this is quite pointless.)
However, this setup breaks a listings environment if it is passed as a subtask, as the following MWE shows:
\documentclass{article}
\usepackage{enumitem}
\usepackage{listings}
\newenvironment{task}{
\newcommand{\subtask}[1]{
\begin{enumerate}[label={\alph*)},resume]\item{##1}\end{enumerate}}
}{}
\begin{document}
\begin{task}
\subtask{{0, 1}, with unescaped braces, becomes \lstinline!{0, 1}!.}
\subtask{{0, 1}, with escaped braces, becomes \lstinline!{0, 1}!.}
\subtask{{0}, with unescaped braces, becomes \lstinline!{0}!.}
\subtask{{0}, with escaped braces, becomes \lstinline!{0}!.}
\end{task}
Typing the environment commands by hand:
\begin{enumerate}[label={\alph)}, resume]\item{{0, 1}, with unescaped braces, becomes \lstinline!{0, 1}!.}\end{enumerate}
\begin{enumerate}[label={\alph)}, resume]\item{{0, 1}, with escaped braces, becomes \lstinline!{0, 1}!.}\end{enumerate}
\begin{enumerate}[label={\alph)}, resume]\item{{0}, with unescaped braces, becomes \lstinline!{0}!.}\end{enumerate}
\begin{enumerate}[label={\alph)}, resume]\item{{0}, with escaped braces, becomes \lstinline!{0}!.}\end{enumerate}
\end{document}
Note the moving around of the “1“, the comma and a space in the first a). This does not happen if I escape the braces inside the listing (which is usually unnecessary, as exemplified by the text between the lists) or if I type the environment’s exact commands by hand, as shown in the second list.
My questions after lots of text are now:
- Why is it necessary to escape the braces inside the environment?
- How come the listing’s contents are moved around and doubled if I don’t do that?
- How can I fix this?
