SystemTap Syntax Highlighting in LaTeX listings

While writing a report about SystemTap in LaTeX I had to figure out how to get LaTeX to nicely color my listings, because the report featured some source code.

By default, the Listings package does not support SystemTap (see chapter 2.4 of the Listings Package user guide). Since SystemTap syntax is very similar to C, I first tried that option, but alas no luck. The problem lies in the fact that SystemTap does not use semicolons to end a statement, therefore the C syntax highlighter gets very confused.

However, it is quite simple to extend the Listings package with custom syntax highlighting (defining a new language, to be precise). Here is the snippet I used:

\lstdefinelanguage{SystemTap}{
  morekeywords={probe,begin,end,call,count,avg,min,max,global,return},
  sensitive=false,
  morecomment=[l]{//},
  morecomment=[s]{/*}{*/},
  morecomment=[l]{\#},
  morestring=[b]",
}

After also setting some colors for keywords, comments et cetera:

\lstset{
  showspaces=false,
  showstringspaces=false,
  title=\lstname,
  basicstyle=\ttfamily\footnotesize,
  frame=single,
  basicstyle=\footnotesize\ttfamily,
  keywordstyle=\bfseries\color{green},
  commentstyle=\itshape\color{gray},
  identifierstyle=\color{blue},
  stringstyle=\color{orange},
}

I got some nice results:

latex-listing-systemtap

Here is a full example:

\documentclass[11pt,a4paper]{article}
\usepackage[english]{babel}
\usepackage{listings}
\usepackage[dvipsnames]{xcolor}

\title{SystemTap Listing}
\author{Jack Henschel}

\definecolor{darkgreen}{rgb}{0.0, 0.5, 0.0}

\lstset{
  showspaces=false,
  showstringspaces=false,
  title=\lstname,
  basicstyle=\ttfamily\footnotesize,
  frame=single,
  basicstyle=\footnotesize\ttfamily,
  keywordstyle=\bfseries\color{darkgreen},
  commentstyle=\itshape\color{gray},
  identifierstyle=\color{blue},
  stringstyle=\color{orange},
}

\lstdefinelanguage{SystemTap}{
  morekeywords={probe,begin,end,call,count,avg,min,max,global,return},
  sensitive=false,
  morecomment=[l]{//},
  morecomment=[s]{/*}{*/},
  morecomment=[l]{\#},
  morestring=[b]",
}

\newcommand*{\Lcode}{\lstinline[{breaklines=true}]}

\begin{document}

Here is an example of a basic stap script:
\begin{lstlisting}[language=SystemTap]
  #!/usr/bin/stap

  probe kernel.module("vfs").function("read") {
    printf("read from the virtual filesystem\n")
    exit()
  }
\end{lstlisting}

\end{document}

Don’t forget to include the xcolor package for colored listings, too!

By the way, this is a nice way to create inline source code listings in LaTeX (put the newcommand in your preamble):

\newcommand*{\Lcode}{\lstinline[{breaklines=true}]}
...
\Lcode|process.function("factor").return|

latex-inline-listing

Happy TeX’ing!