About
Shop
LaTeX
Software
Books
Gallery
News
Contact
Blog
Settings
Account
Latest news 2024-09-23: new blog post "Tales for Our Times: Raising Funds and Awareness for St Martins Housing Trust".


4.5 Listings and Other Verbatim Text

[Code listings in LaTeX]There may be times when you want to include text exactly as you have typed it into your source code. For example, you may want to include a short segment of computer code. This can be done using the verbatim environment.

Example:

Note how I don't need to worry about special characters, such as #, within the verbatim environment:

\begin{verbatim}
#include <stdio.h> /* needed for printf */

int main()
{
   printf("Hello World\n");

   return 1;
}

\end{verbatim}

This just produces:

Image showing typeset output click here for a more detailed description.

A more sophisticated approach is to use the listings package. With this package, you first need to specify the programming language. For example, the above code is in C, so I need to specify this using:

\lstset{language=C}

Now I can use the lstlisting environment to typeset my C code:

\begin{lstlisting}
#include <stdio.h> /* needed for printf */

int main()
{
   printf("Hello World\n");

   return 1;
}

\end{lstlisting}

The resulting output looks like:

The keywords 'include' 'int' and 'return' are rendered in bold. The normal serif font is used.

I can also have inline code snippets using:

\lstinline[<options>]<char><code><char>

This is different syntax to the usual forms of command argument. You can chose any character <char> that isn't the open square bracket [ and that doesn't occur in <code> to delimit the code, but the start and end <char> must match. (The optional argument is discussed below.) So the following are all equivalent:

  1. <char> is the exclamation mark character:

    \lstinline!#include <stdio.h>!

  2. <char> is the vertical bar character:

    \lstinline|#include <stdio.h>|

  3. <char> is the double-quote character:

    \lstinline"#include <stdio.h>"

  4. <char> is the plus symbol:

    \lstinline+#include <stdio.h>+

And so on, but <char> can't be, say, # as that occurs in <code>. Example:

The stdio header file (required for the \lstinline+printf+ function) is loaded using the directive \lstinline!#include <stdio.h>! on the first line.

Result:

The keyword 'include' is rendered in bold.

Another alternative is to input the code from an external file. For example, suppose my C code is contained in the file helloworld.c, then I can input it using:

\lstinputlisting[<options>]{helloworld.c}

(Remember to use a forward slash / as the directory divider, even if you are using Windows.)

All the above (\lstinline, \lstinputlisting and the lstlisting environment) have an optional argument <options> that can be used to override the default settings. These are <key>=<value> options. There are a lot of options available, but I'm only going to cover a few. If you want more detail, have a look at the listings documentation [6].

title={<text>}
is used to set an unnumbered and unlabelled title. If <text> contains a comma or equal sign, make sure you enclose <text> in curly braces { and }.

caption={[<short>]<text>}
is used to set a numbered caption. The optional part <short> is an alternative short caption for the list of listings, which can be produced using

As above, if the caption contains a comma or equal sign, make sure you enclose it in curly braces { and }.

label={<text>}
is used to assign a label to this listing so the number can be referenced via \ref.

numbers={<setting>}
The value <setting> may be one of: none (no line numbers), left (line numbers on the left) or right (line numbers on the right).

mathescape
This is a boolean key that can either be true (dollar $ character acts as the usual math mode shift) or false (deactivates the usual behaviour of $).

basicstyle={<declaration>}
The value (one or more declarations) is used at the start of the listing to set the basic font style. For example, <declaration> could be \ttfamily (which actually makes more sense for a listing).

Note:

If you set basicstyle to \ttfamily and you want bold keywords, make sure you are using a typewriter font that supports bold, as not all of them do. (Recall from Volume 1 how to change the font family.) This book uses txtt (see Volume 1). Other possibilities include beramono, tgcursor, courier, DejaVuSansMono (or dejavu to load the serif and sans-serif DejaVu fonts as well), lmodern and luximono.

KOMA and listings

If you want to use the listings package with one of the KOMA-Script classes, you need to load scrhack before listings, otherwise you will get a warning that looks like:
Class scrbook Warning: Usage of deprecated \float@listhead!
(scrbook)              You should use the features of package `tocbasic'
(scrbook)              instead of \float@listhead.
(scrbook)              Definition of \float@listhead my be removed from
(scrbook)              `scrbook' soon, so it should not be used  on input 
line 57.

Example:

Listing 11:

\begin{lstlisting}[language=C,basicstyle=\ttfamily,mathescape=true]
#include <stdio.h> /* needed for printf */
#include <math.h> /* needed for sqrt */

int main()
{
   double x = sqrt(2.0); /* $x = \sqrt{2}$ */

   printf("x = %f\n", x);

   return 1;
}

\end{lstlisting}

Result:

The formula in the comment is typeset in math mode and spaces in the string are displayed with the visible space symbol

If you are using double-spacing, you may need to temporarily switch it off in the listings. You can do this by adding \singlespacing to the basicstyle setting.

\lstset{basicstyle={\ttfamily\singlespacing}}

(Check with your supervisor to find out if listings should be double- or single-spaced.)

Note:

It is not usually appropriate to have reams of listings in your thesis. It can annoy an examiner if you have included every single piece of code you have written during your PhD, as it comes across as padding to make it look as though your thesis is a lot larger than it really is. (Examiners are not easily fooled, and it's best not to irritate them as it is likely to make them less sympathetic towards you.) If you want to include listings in your thesis, check with your supervisor first to find out whether or not it is appropriate.

Be careful when you use verbatim-like environments or commands, such as verbatim, lstlisting, \lstinline and \lstinputlisting. In general, they can't be used in the argument of another command.[Why doesn't verbatim work within ...?]


This book is also available as A4 PDF or 12.8cm x 9.6cm PDF or paperback (ISBN 978-1-909440-02-9).

© 2013 Dickimaw Books. "Dickimaw", "Dickimaw Books" and the Dickimaw parrot logo are trademarks. The Dickimaw parrot was painted by Magdalene Pritchett.

Terms of Use Privacy Policy Cookies Site Map FAQs