6

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.

4
  • You might be interested in the matlab-prettifier package; see this answer.
    – jub0bs
    Apr 28, 2014 at 15:43
  • @Jubobs thanks, looks cool. Any reason why this is a separate package and not included natively in listings? Apr 28, 2014 at 17:56
  • That's a good question that I probably should have addressed in the documentation... The main reason is that matlab-prettifier actually does quite a lot behind the scenes (to keep track of the context); I'm not sure the maintainer of listings would have accepted it as a patch.
    – jub0bs
    Apr 28, 2014 at 18:01
  • 1
    Off topic here, but people landing here may be actually looking for How can I automatically prepend a prompt (e.g. $) to each line of a listing?. Oct 15, 2020 at 10:27

1 Answer 1

8

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.

0

You must log in to answer this question.

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