[Tex/LaTex] Highlight a prompt with the listings package

highlightinglistings

I use the listings package to typeset a series of commands in the language Octave (a free clone of Matlab) in my lecture notes. Most of the command lines look like this:

octave:1> A=eye(4)
A =

Diagonal Matrix

   1   0   0   0
   0   1   0   0
   0   0   1   0
   0   0   0   1

octave:2> det(A)
ans =  1
octave:3> 

As you can see, each command is prefixed by a prompt in the form octave:N>, where N is the number of the command in the session (may have more than one character). I do not skip this prompt because I want my notes to look exactly like the students' screens. Output lines have no prefix.

I would like this command prefix to be formatted in a different color (grayed out, to mean that it is not as important as what follows).

How can I do that with listings? In the manual I find only an option gobble to ignore the first k characters of every line, but this does not work in my case since only some lines have this prefix.

Best Answer

Is this what you want?

Code

\documentclass{article}
\usepackage{listings,xcolor}
\lstset{
    language=Octave,
    moredelim=[s][\color{gray}]{octave:}{>}
}
\begin{document}
\begin{lstlisting}
octave:1> A=eye(4)
A =

Diagonal Matrix

   1   0   0   0
   0   1   0   0
   0   0   1   0
   0   0   0   1

octave:2> det(A)
ans =  1
octave:3>
\end{lstlisting}
\end{document}

Output

Output of posted code

moredelim

The moredelim key defines new delimiters that are used to format text manually between them. In this case the delimiters are octave: and > and they are not thrown away (that would happen if you use [is] instead of [s]).
Confer to manual section 3.3 and 4.5 to read more about the use of delimiters.