Macro with lstlisting inside

I have been following this topic about using \NewDocuentCommand with lstlisting and the accepted answer is nice except it is too big and it doesn't quite work for me.

I came up with this example to test xparse:

\documentclass{article}
\usepackage{xparse}
\usepackage{listings}

\ExplSyntaxOn
\NewDocumentCommand{\code}{m +v}{
\begin{lstlisting}[style=#1,numbers=none,xleftmargin=0.35cm,framesep=0mm]
#2
\end{lstlisting}
}
\ExplSyntaxOff

\begin{document}

\code{C}{
int x = 200;
unsigned int y = 0;
}

\end{document}


Like stated in the CTAN xparse documentation I first used m as a normal parameter and then +v as a multiline verbatim parameter, but it fails. It looks like I am still missing something...

• You cannot wrap verbatim into macros. This doesn't change with LaTeX3. – Henri Menke Jun 21 '17 at 7:34
• Use \lstnewenvironment instead. – Henri Menke Jun 21 '17 at 7:37
• @Henri Menke I need to create a command and not environment. In the example I provided they did it somehow... – 71GA Jun 21 '17 at 7:53
• @71GA you didn't provide an example: I guess you forgot to add the link… – cgnieder Jun 21 '17 at 7:57
• @71GA »I need to create a command...« Wrong! You want to create a command but what you need and should use is an environment. – Henri Menke Jun 21 '17 at 8:14

1 Answer

You can just use Bruno's solution from the linked question (pretty smart I think).

\documentclass{article}
\usepackage{listings}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\code}{m +v}{
\exp_args:Nx \scantokens
{
\string\begin{lstlisting}[\unexpanded{language=#1,numbers=none,xleftmargin=0.35cm,framesep=0mm}]
#2
\string\end{lstlisting}
}
}
\ExplSyntaxOff

\begin{document}

\code{C}{
int x = 200;
unsigned int y = 0;
}

\end{document}


But please, just use a new environment instead.

\documentclass{article}
\pagestyle{empty}
\usepackage{listings}

\lstnewenvironment{code}[1]{\lstset{language=#1,numbers=none,xleftmargin=0.35cm,framesep=0mm}}{}

\begin{document}

\begin{code}{C}
int x = 200;
unsigned int y = 0;
\end{code}

\end{document}


Output is similar.

• Thank you for the answer. One more thing is bugging me. In either of the cases you provided, code is moved one tab to the right if I move source code \begin{code}...\end{code} one tab right. So source code position affects the compiled code position. Any idea on how to solve this? – 71GA Jun 21 '17 at 8:47
• @71GA See the gobble option in the documentation. – Henri Menke Jun 21 '17 at 9:22