Source code snippets in Latex

In this post I’m going to show you how to include source code snippets in your Latex documents. To perform the task we’re going to use the listings package.

\usepackage{listings}

First we’re going to define the source code’s layout. We’ll define two different styles to show the capabilities of the package. The first style comes in handy for including source code. The second one is better for including, for instance, console commands. Of course you can define different styles to suit your own needs.

\definecolor{gray92}{gray}{.92}
\definecolor{gray75}{gray}{.75}
\definecolor{gray45}{gray}{.45}
 
\lstdefinestyle{source_code}
{
numbers=left,
stepnumber=5, 
basicstyle=\normalsize, 
captionpos = b, %bottom 
keywordstyle=\color[rgb]{0,0,1}, 
commentstyle=\color[rgb]{0.133,0.545,0.133}, 
stringstyle=\color[rgb]{0.627,0.126,0.941}, 
backgroundcolor=\color{gray92}, 
frame=lrtb, 
framerule=0.5pt, 
linewidth = \textwidth 
}
 
\lstdefinestyle{console} 
{ 
numbers=none, 
basicstyle=\bf\ttfamily, 
backgroundcolor=\color{gray92}, 
frame= lrtb, 
framerule=0.5pt, 
linewidth=\textwidth, 
}

Once the styles are defined there are two ways to include the snippets in the document:

  • Writing the source code directly in the Latex document.
  • Importing the source code file.
\begin{lstlisting}[style=console, caption=A command] 
# gcc -o hello hello.c 
\end{lstlisting}

Note how we can specify the source code’s programming language as well as the listing’s caption:

\lstinputlisting[style=source_code, label = some label, caption=A shell script, language=bash]{example.bash}

The final result looks like this:

picture162 Source code snippets in Latex

You can get the full Latex source code here.

Share this post:

  • Print this article!
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
Related posts:
  1. Beautiful tables in Latex
  2. Latex brush for Syntax Highlighter Plus Wordpress plugin
  3. Wrap text around float figures in Latex
  4. Fix overfull problems when too many consecutive empty sections in Latex
  5. Visual Studio Doxygen Latex and encoding problems

Leave a Reply