Adding Source Code Listings to LaTeX Documents

There are several methods of adding program source code to a document - either by using the verbatim environment which is built into LaTeX, or by downloading the listings package.

Method 1: The Built-In Verbatim Environment

The simplest method is to use a verbatim environment. This requires no additional packages. To get a horizontal line above and below (for example, when used with a figure environment) use \makebox[\textwidth]{\hrulefill} To refer to the code in the text body, use the inline verb format: \verb!int m, n;!

If you wish to use a framed box, download the style file boxedminipage.sty (alternate site), It provides a new environment of that name, like a verbatim but with a frame around it.

Method 2: The Add-On Listings Package

The listings package provides many more features and flexibility: language-aware syntax highlighting, listings spread over several pages, and formatting options such as color and framed boxes.

To use it, you must download (alternate site), all the package files, and refresh the filename database under MiKTeX-options. Full documentation comes with the package, but an example source file listingseg.tex gives an idea of what is possible. This requires a MATLAB® source code file lowertri.m to be formatted (you may also need the A4 page size definitions from the packages page on this site). You may view the final result to get an idea of what the package is capable of.

Back