Svenska login

StartTeX and LaTeX

Code listings

listings

There are several options for present code listings in a report. One is the package listings. To use that, write

\usepackage{listings}
in the document preamble, maybe followed by something like
\lstset{
  basicstyle=\small\ttfamily,
  commentstyle=\color{red},
}
to state how different parts should be formatted, in this case in small typewriter font and with comments in red.

Here are some more example settings:

\lstset{backgroundcolor=\color{yellow!20}, frame=single,
        numbers=left, numberstyle=\tiny}
This makes the listing yellowish with a frame around it, and with line numbers. See the documentation for listings for further options.

Then in the text you can use

\lstinputlisting[language=python]{foo.py}
to get a listing of your program foo.py.

There is support for several languages, for example language=sh for a shell script.

Non-ASCII characters in code?

The package listings can't handle utf8 files, so if you have for example Swedish letters åäö in the code it won't work. One workaround is to use

\usepackage{listingsutf8}
instead in the preamble and then
\lstinputlisting[language=python,inputencoding=utf8/latin1]{foo.py}
in the text.

That means that the code is in utf8 and can be converted to latin1 for the listing.

pythonhighlight

The package pythonhighlight builds on listings and is made just for Python code.

You load it with

\usepackage{pythonhighlight}

Then you get an environment python, a command \pyth{...} for inline code, and you can load an external Python file with

\inputpython{python_file.py}{23}{50}
which will display the contents of the file python_file from line 23 to line 50.