2

Here's a minimal working example (MWE):

\documentclass{scrartcl}

\usepackage{listings}

\begin{document}

\noindent\minipage[t]{0.45\linewidth}
\lstlisting
  foo
\endlstlisting
\endminipage \qquad \minipage[t]{0.45\linewidth}
\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
\endminipage \qquad \minipage[t]{0.45\linewidth}
  #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.
<to be read again> 
    \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.

3
  • 2
    You can't put lstlisting and its content in the argument of a command. lstlisting has to do a lot of catcode magic. Apr 30, 2013 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, 2013 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!
    – user16880
    May 27, 2013 at 14:36

1 Answer 1

2

How about building this up piece by piece as follows:

\documentclass{scrartcl}

\usepackage{listings}

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

\begin{document}

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

\end{document}
2
  • That works (but looks weird!) Is there a reason that endtwocol is a \def rather than a \newcommand ?
    – user16880
    Apr 30, 2013 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. Apr 30, 2013 at 10:04

You must log in to answer this question.