TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Can you define a macro that would take a listings code as a parameter and insert it inside a \begin{lstlistings} \end{lstlistings} block?

My idea is something like this:

\def\blist#1{\begin{lstlisting} #1 \end{lstlisting}}

so I could just write

\blist{ "this code is inside listings block" }
share|improve this question
You can't to that in full generality in any case. The problem is that lstlisting is a (smart) variant of verbatim and such environments can never be the argument to a command. – egreg Nov 4 '12 at 12:11
I see. And would something like this \def\blist{\begin{lstlisting}} \def\elst{\end{lstlisting}} work? \blist TEXT TEXT \elst gives me an error on \elst – Dwelle Nov 4 '12 at 12:57
Like verbatim, LaTeX must see an explicit \end{lstlisting} to end the job; so hiding it in a macro is not helpful. – egreg Nov 4 '12 at 13:14
So, where's the advantage of using \blist{<long series of statements>} instead of the clearer \begin{lstlisting}...\end{lstlisting}? – egreg Nov 4 '12 at 13:51
@DavidL: Did you know that listings provides an inline version: \lstinline, which works similar to your requested \blist. Alternatively, use \let\blist\lstinline and use \blist. – Werner Nov 4 '12 at 15:17
up vote 2 down vote accepted

At first an input such as


can seem more appealing than


but eventually it doesn't reveal such. For one thing: \end{lstlisting} is much more evident in the input than a single brace.

Besides, there are technical reasons why the "macro with argument" is difficult to implement for lstlisting: this environment is pretty much like verbatim (but does more complicated things) and so it can't go inside the argument to another command, if you want that it treats correctly all the characters which are special to LaTeX (braces, #, $ and %, in particular).

A good text editor can help, but also listings features: if you want to give particular options for typesetting chunks of code, you can define a new environment:

  {\lstset{<common options>,#1}}

and then


will be typeset applying the <common options>. Not very harder to type and good for marking your input and making it easy to find the chunks of code that use that common setting. You can also add "local options" by saying

\begin{blist}[<local options>]
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.