I'm a Canadian based in Berlin, Germany. My day job is a Technical Writer in the API space. I write about topics such as technology, usability, creative writing and Canadian history. All views mine. I tweet at @glennjlea. Read more about me here or at LinkedIn.
Site version: 3.0

Inserting code snippets

Here is some syntax you can use to insert code snippets and code highlighting in a text flow.

You can use the listings, boxhandler and verbatimbox packages for source code.

However, I found the Listing packagelstset best suited my needs for technical documentation. from the Listing package documentation:

The listings package is a source code printer for LATEX. You can typeset stand alone files as well as listings with an environment similar to verbatim as well as you can print code snippets using a command similar to \verb. Many parameters control the output and if your preferred programming language isn’t already supported, you can make your own definition.

## Code highlighting

You can put code inside a corresponding environment.

For example, for SQL commands, you could use the following.

Other examples are:

• codesh - shell commands
• codecsv - CSV commands
• codecpp - C++
• codejava - Java code
• codejson JSON
• codexml - XML

## verbatim

LaTeX provides a default command verbatim for inserting code. It ignores all text and commands within the environment and outputs the text in monospaced font.

## listings package

The listings package supports most common languages. To include this package, add the following line to the stylesheet.

First, I defined the colours for the source code as follows:

\definecolor{dkgreen}{rgb}{0,0.6,0}
\definecolor{gray}{rgb}{0.5,0.5,0.5}
\definecolor{mauve}{rgb}{0.58,0,0.82}
\definecolor{lightgrey}{RGB}{211,211,211}


Then I configured \lstset as follows:

Then when I want to insert some code, I use this macro as follows:

You add your code sample using the following syntax, changing the language setting accordingly.