26. Inserting code snippets

## Selecting a package

The verbatim and listings packages can be used for inserting in a text flow source code snippets and code highlighting. 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.

These packages are inserted using the following commands:

## Inserting code in a specific environment

You can put code inside a corresponding environment. For example, for SQL commands, you could use the following.

Other environments include:

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

## Using the verbatim package to insert code

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.

## Using the listings package

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

First, define the colours for the source code:

\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 configure the listing using \lstset:

Then add your code sample, changing the language setting accordingly:

Click to continue.