I would like to have the solution of highlighting a line in listings-package as a command or environment. To bad I cannot get it working. I tried:

  • a simple newenvironment: compile errors
  • \newcommand: also compile errors
  • the environ-package, see below


Also, same kind of errors. missing {, missing number, threaded a zero etc.

I try to use it with the beamer-package and pdflatex.


2 Answers 2


The lstlisting environment is like all verbatim environments special and doesn't work (well) inside another environments. You need to use \lstnewenvironment as described in the listings manual in section 4.16 Environments, p.40:

    {<name>}[<number>][<opt. default arg.>]
    {<starting code>}
    {<ending code>}

Applied to your code:


Note the % at the end of lines to avoid spurious spaces.

You need to use the fragile option of the frame environment (or command) if you use listings or any other verbatim code.


In addition to Martin's answer, you need to take special care within the beamer class, because that class also drastically alters LaTeX's expansion habits. See section 2.6 of the beamer manual.




20 GOTO 10
\end{listingh} }


% or
for (;;) {
    cout << "Hello, world!";


This looks bad but keep in mind you can redefine \mycode over and over again before each frame.

  • Why not just use the fragile option for the frame? It works fine in my test. Apr 26, 2011 at 13:01
  • Good point, I've edited. Is there a situation where fragile doesn't work? Or is this workaround in the manual vestigial? Apr 26, 2011 at 13:06
  • The section 2.6 referenced by you mentions a couple of times: "[...] either add the fragile option to the frame or use the \defverbatim command". So it seems that both are equal. For listings it says "tread it like a verbatim environment` and then "When using \defverbatim that contains a colored lstlisting, use the colored option of \defverbatim". It doesn't explicitly state that fragile can or cannot be used, just tells you that colored is required for colors. Apr 26, 2011 at 13:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .