# Turning working code into macro causes “Missing number, treated as zero — \let”

Here's a minimal working example (MWE):

\documentclass{scrartcl}

\usepackage{listings}

\begin{document}

\noindent\minipage[t]{0.45\linewidth}
\lstlisting
foo
\endlstlisting
\lstlisting
bar
\endlstlisting
\endminipage

\end{document}


Since I'm using this pattern a lot (code on left transforms into code on right), like a good programmer I encapsulate it in a macro:

\newcommand{\twocol}[2]{
\noindent\minipage[t]{0.45\linewidth}
#1
#2
\endminipage
}


And try this in my document:

\twocol{
\lstlisting
foo
\endlstlisting
}{
\lstlisting
bar
\endlstlisting
} %% line 33, see below


At which point LaTeX is unhappy:

! Missing number, treated as zero.
\let
l.33 }


Line 33 is the closing bracket of the twocol. This is just a simple textual substitution (I copy-pasted the listings commands) so what's going wrong, and how do I fix it?

Note: using the \begin{} ... \end{} forms everywhere doesn't help.

• You can't put lstlisting and its content in the argument of a command. lstlisting has to do a lot of catcode magic. – Ulrike Fischer Apr 30 '13 at 9:28
• Why are you using environments via their underlying macros? You should use \begin and \end unless you're trying to build a new environment around them. If for no other reason than that the envrionment may set local variables that it expects not to be global because \begin...\end protects them in a group. – Ryan Reich Apr 30 '13 at 14:42
• Thanks - no-one's ever pointed that out to me; according to some TeX tutorial I read "the two forms are equivalent" so I chose the shorter one - apparently not! – Bristol May 27 '13 at 14:36

How about building this up piece by piece as follows:

\documentclass{scrartcl}

\usepackage{listings}

\newenvironment{twocol}{\noindent\minipage[t]{0.45\linewidth}}{\endminipage}

\begin{document}

\begin{twocol}
\lstlisting
foo
\endlstlisting
\twcbr
\lstlisting
bar
\endlstlisting
\end{twocol}

\end{document}

• That works (but looks weird!) Is there a reason that endtwocol is a \def rather than a \newcommand ? – Bristol Apr 30 '13 at 10:00
• \newcommand doesn't allow you to define commands starting with end as these are meant for ends of environments. However, I have now rephrased my answer using a standard \newenironment instead. – Andrew Swann Apr 30 '13 at 10:04