Svenska login

StartTeX and LaTeX

Code listings


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

in the document preamble, maybe followed by something like
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

to get a listing of your program

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

instead in the preamble and then
in the text.

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


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

You load it with


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

which will display the contents of the file python_file from line 23 to line 50.