> For the complete documentation index, see [llms.txt](https://overleaf-pro.ayaka.space/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://overleaf-pro.ayaka.space/latex/formatting/11-code-listing.md).

# Code listing

## Introduction

LaTeX is widely used in science and programming has become an important aspect in several areas of science, hence the need for a tool that properly displays code. This article explains how to use the standard **verbatim** environment as well as the package **listings**, which provide more advanced code-formatting features. [This separate article](/latex/formatting/12-code-highlighting-with-minted.md) discusses the `minted` package, which performs syntax-highlighting using Python's `pygmentize` library.

## The verbatim environment

The default tool to display code in LaTeX is `verbatim`, which generates an output in monospaced font.

```latex
\begin{verbatim}
Text enclosed inside \texttt{verbatim} environment
is printed directly
and all \LaTeX{} commands are ignored.
\end{verbatim}
```

[Open this example on Overleaf](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=verbatim+text+example\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cbegin%7Bdocument%7D%0A%5Cbegin%7Bverbatim%7D%0AText+enclosed+inside+%5Ctexttt%7Bverbatim%7D+environment+%0Ais+printed+directly+%0Aand+all+%5CLaTeX%7B%7D+commands+are+ignored.%0A%5Cend%7Bverbatim%7D%0A%5Cend%7Bdocument%7D)

The code above produces the following output:

![Verbatim1.png](/files/TCzuCqqYyZQcE5aFK6vj)

Just as in the example at the introduction, all text is printed keeping line breaks and white spaces. There's a starred version of this command whose output is slightly different.

```latex
\begin{verbatim*}
Text enclosed inside \texttt{verbatim} environment
is printed directly
and all \LaTeX{} commands are ignored.
\end{verbatim*}
```

[Open this example on Overleaf](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=verbatim+text+example\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cbegin%7Bdocument%7D%0A%5Cbegin%7Bverbatim%2A%7D%0AText+enclosed+inside+%5Ctexttt%7Bverbatim%7D+environment+%0Ais+printed+directly+%0Aand+all+%5CLaTeX%7B%7D+commands+are+ignored.%0A%5Cend%7Bverbatim%2A%7D%0A%5Cend%7Bdocument%7D)

The code above produces the following output:

![Verbatim2.png](/files/h2T2w9KQrlsnIZTdCpSR)

In this case spaces are emphasized with a special "visible-space" character: **`␣`**.

Verbatim-like text can also be used in a paragraph by means of the `\verb` command.

```latex
In the directory \verb|C:\Windows\system32| you can find a lot of Windows
system applications.

The \verb+\ldots+ command produces \ldots
```

[Open this example on Overleaf](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=using+the+%5Cverb+command\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cbegin%7Bdocument%7D%0AIn+the+directory+%5Cverb%7CC%3A%5CWindows%5Csystem32%7C+you+can+find+a+lot+of+Windows+%0Asystem+applications.+%0A+%0AThe+%5Cverb%2B%5Cldots%2B+command+produces+%5Cldots%0A%5Cend%7Bdocument%7D)

The code above produces the following output:

![Verbatim3OLV2.png](/files/CXPfCab0sMo6XdNKPFTk)

The command `\verb|C:\Windows\system32|` prints the text inside the delimiters `|` in verbatim format. Any character, except letters and `*`, can be used as delimiter. For instance `\verb+\ldots+` uses `+` as delimiter.

## Using listings to highlight code

To use the `lstlisting` environment you have to add the following line to the preamble of your document:

```latex
\usepackage{listings}
```

Here's an example of using the `lstlisting` environment from the `listings` package:

```latex
\begin{lstlisting}
import numpy as np

def incmatrix(genl1,genl2):
    m = len(genl1)
    n = len(genl2)
    M = None #to become the incidence matrix
    VT = np.zeros((n*m,1), int)  #dummy variable

    #compute the bitwise xor matrix
    M1 = bitxormatrix(genl1)
    M2 = np.triu(bitxormatrix(genl2),1)

    for i in range(m-1):
        for j in range(i+1, m):
            [r,c] = np.where(M2 == M1[i,j])
            for k in range(len(r)):
                VT[(i)*n + r[k]] = 1;
                VT[(i)*n + c[k]] = 1;
                VT[(j)*n + r[k]] = 1;
                VT[(j)*n + c[k]] = 1;

                if M is None:
                    M = np.copy(VT)
                else:
                    M = np.concatenate((M, VT), 1)

                VT = np.zeros((n*m,1), int)

    return M
\end{lstlisting}
```

[Open this `listings` example on Overleaf](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=listings+package+example\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%7Blistings%7D%0A%5Cbegin%7Bdocument%7D%0A%5Cbegin%7Blstlisting%7D%0Aimport+numpy+as+np%0A++++%0Adef+incmatrix%28genl1%2Cgenl2%29%3A%0A++++m+%3D+len%28genl1%29%0A++++n+%3D+len%28genl2%29%0A++++M+%3D+None+%23to+become+the+incidence+matrix%0A++++VT+%3D+np.zeros%28%28n%2Am%2C1%29%2C+int%29++%23dummy+variable%0A++++%0A++++%23compute+the+bitwise+xor+matrix%0A++++M1+%3D+bitxormatrix%28genl1%29%0A++++M2+%3D+np.triu%28bitxormatrix%28genl2%29%2C1%29+%0A%0A++++for+i+in+range%28m-1%29%3A%0A++++++++for+j+in+range%28i%2B1%2C+m%29%3A%0A++++++++++++%5Br%2Cc%5D+%3D+np.where%28M2+%3D%3D+M1%5Bi%2Cj%5D%29%0A++++++++++++for+k+in+range%28len%28r%29%29%3A%0A++++++++++++++++VT%5B%28i%29%2An+%2B+r%5Bk%5D%5D+%3D+1%3B%0A++++++++++++++++VT%5B%28i%29%2An+%2B+c%5Bk%5D%5D+%3D+1%3B%0A++++++++++++++++VT%5B%28j%29%2An+%2B+r%5Bk%5D%5D+%3D+1%3B%0A++++++++++++++++VT%5B%28j%29%2An+%2B+c%5Bk%5D%5D+%3D+1%3B%0A++++++++++++++++%0A++++++++++++++++if+M+is+None%3A%0A++++++++++++++++++++M+%3D+np.copy%28VT%29%0A++++++++++++++++else%3A%0A++++++++++++++++++++M+%3D+np.concatenate%28%28M%2C+VT%29%2C+1%29%0A++++++++++++++++%0A++++++++++++++++VT+%3D+np.zeros%28%28n%2Am%2C1%29%2C+int%29%0A++++%0A++++return+M%0A%5Cend%7Blstlisting%7D%0A%5Cend%7Bdocument%7D)

The code above produces the following output:

![CodeListingEx1.png](/files/CwPFHEPMNmdOgMDQWSlP)

In this example, the output ignores all LaTeX commands and the text is printed keeping all the line breaks and white spaces typed. Let's see a second example:

```latex
\begin{lstlisting}[language=Python]
import numpy as np

def incmatrix(genl1,genl2):
    m = len(genl1)
    n = len(genl2)
    M = None #to become the incidence matrix
    VT = np.zeros((n*m,1), int)  #dummy variable

    #compute the bitwise xor matrix
    M1 = bitxormatrix(genl1)
    M2 = np.triu(bitxormatrix(genl2),1)

    for i in range(m-1):
        for j in range(i+1, m):
            [r,c] = np.where(M2 == M1[i,j])
            for k in range(len(r)):
                VT[(i)*n + r[k]] = 1;
                VT[(i)*n + c[k]] = 1;
                VT[(j)*n + r[k]] = 1;
                VT[(j)*n + c[k]] = 1;

                if M is None:
                    M = np.copy(VT)
                else:
                    M = np.concatenate((M, VT), 1)

                VT = np.zeros((n*m,1), int)

    return M
\end{lstlisting}
```

[Open this `listings` example on Overleaf](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=Python+listings+package+example\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%7Blistings%7D%0A%5Cbegin%7Bdocument%7D%0A%5Cbegin%7Blstlisting%7D%5Blanguage%3DPython%5D%0Aimport+numpy+as+np%0A++++%0Adef+incmatrix%28genl1%2Cgenl2%29%3A%0A++++m+%3D+len%28genl1%29%0A++++n+%3D+len%28genl2%29%0A++++M+%3D+None+%23to+become+the+incidence+matrix%0A++++VT+%3D+np.zeros%28%28n%2Am%2C1%29%2C+int%29++%23dummy+variable%0A++++%0A++++%23compute+the+bitwise+xor+matrix%0A++++M1+%3D+bitxormatrix%28genl1%29%0A++++M2+%3D+np.triu%28bitxormatrix%28genl2%29%2C1%29+%0A%0A++++for+i+in+range%28m-1%29%3A%0A++++++++for+j+in+range%28i%2B1%2C+m%29%3A%0A++++++++++++%5Br%2Cc%5D+%3D+np.where%28M2+%3D%3D+M1%5Bi%2Cj%5D%29%0A++++++++++++for+k+in+range%28len%28r%29%29%3A%0A++++++++++++++++VT%5B%28i%29%2An+%2B+r%5Bk%5D%5D+%3D+1%3B%0A++++++++++++++++VT%5B%28i%29%2An+%2B+c%5Bk%5D%5D+%3D+1%3B%0A++++++++++++++++VT%5B%28j%29%2An+%2B+r%5Bk%5D%5D+%3D+1%3B%0A++++++++++++++++VT%5B%28j%29%2An+%2B+c%5Bk%5D%5D+%3D+1%3B%0A++++++++++++++++%0A++++++++++++++++if+M+is+None%3A%0A++++++++++++++++++++M+%3D+np.copy%28VT%29%0A++++++++++++++++else%3A%0A++++++++++++++++++++M+%3D+np.concatenate%28%28M%2C+VT%29%2C+1%29%0A++++++++++++++++%0A++++++++++++++++VT+%3D+np.zeros%28%28n%2Am%2C1%29%2C+int%29%0A++++%0A++++return+M%0A%5Cend%7Blstlisting%7D%0A%5Cend%7Bdocument%7D)

The code above produces the following output:

![CodeListingEx2.png](/files/qoELqlNN0mzvWjt4zWKd)

The additional parameter inside brackets `[language=Python]` enables code highlighting for this particular programming language (Python), special words are in boldface font and comments are italicized. See the [reference guide](#reference-guide) for a complete list of supported programming languages.

## Importing code from a file

Code is usually stored in a source file, therefore a command that automatically pulls code from a file becomes very handy.

```latex
The next code will be directly imported from a file

\lstinputlisting[language=Octave]{BitXorMatrix.m}
```

![CodeListingEx3.png](/files/r8FYQzPeIRvQwSoqeEQ4)

The command `\lstinputlisting[language=Octave]{BitXorMatrix.m}` imports the code from the file *BitXorMatrix.m*, the additional parameter in between brackets enables language highlighting for the Octave programming language. If you need to import only part of the file you can specify two comma-separated parameters inside the brackets. For instance, to import the code from the line 2 to the line 12, the previous command becomes

```latex
\lstinputlisting[language=Octave, firstline=2, lastline=12]{BitXorMatrix.m}
```

If `firstline` or `lastline` is omitted, it's assumed that the values are the beginning of the file, or the bottom of the file, respectively.

## Code styles and colours

Code formatting with the **listing** package is highly customisable. Let's see an example

```latex
\documentclass{article}
\usepackage{listings}
\usepackage{xcolor}

\definecolor{codegreen}{rgb}{0,0.6,0}
\definecolor{codegray}{rgb}{0.5,0.5,0.5}
\definecolor{codepurple}{rgb}{0.58,0,0.82}
\definecolor{backcolour}{rgb}{0.95,0.95,0.92}

\lstdefinestyle{mystyle}{
    backgroundcolor=\color{backcolour},
    commentstyle=\color{codegreen},
    keywordstyle=\color{magenta},
    numberstyle=\tiny\color{codegray},
    stringstyle=\color{codepurple},
    basicstyle=\ttfamily\footnotesize,
    breakatwhitespace=false,
    breaklines=true,
    captionpos=b,
    keepspaces=true,
    numbers=left,
    numbersep=5pt,
    showspaces=false,
    showstringspaces=false,
    showtabs=false,
    tabsize=2
}

\lstset{style=mystyle}

\begin{document}
The next code will be directly imported from a file

\lstinputlisting[language=Octave]{BitXorMatrix.m}
\end{document}
```

The code above produces the following output:

![CodeListingEx4.png](/files/nGZfez9BzQAHnapMZrjx)

As you see, the code colouring and styling greatly improves readability.

In this example the package **xcolor** is imported and then the command `\definecolor{}{}{}` is used to define new colours in rgb format that will later be used. For more information see: [using colours in LaTeX](/latex/formatting/13-using-colors-in-latex.md)

There are essentially two commands that generate the style for this example:

**\lstdefinestyle{mystyle}{...}**

Defines a new code listing style called "mystyle". Inside the second pair of braces the options that define this style are passed; see the reference guide for a full description of these and some other parameters.

**\lstset{style=mystyle}**

Enables the style "mystyle". This command can be used within your document to switch to a different style if needed.

## Captions and the list of Listings

Just like in floats ([tables](/latex/figures-and-tables/01-tables.md) and [figures](/latex/more-topics/27-inserting-images.md)), captions can be added to a listing for a more clear presentation.

```latex
\begin{lstlisting}[language=Python, caption=Python example]
import numpy as np

def incmatrix(genl1,genl2):
    m = len(genl1)
    n = len(genl2)
    M = None #to become the incidence matrix
    VT = np.zeros((n*m,1), int)  #dummy variable

    #compute the bitwise xor matrix
    M1 = bitxormatrix(genl1)
    M2 = np.triu(bitxormatrix(genl2),1)

    for i in range(m-1):
        for j in range(i+1, m):
            [r,c] = np.where(M2 == M1[i,j])
            for k in range(len(r)):
                VT[(i)*n + r[k]] = 1;
                VT[(i)*n + c[k]] = 1;
                VT[(j)*n + r[k]] = 1;
                VT[(j)*n + c[k]] = 1;

                if M is None:
                    M = np.copy(VT)
                else:
                    M = np.concatenate((M, VT), 1)

                VT = np.zeros((n*m,1), int)

    return M
\end{lstlisting}
```

[Open this `listings` example on Overleaf](/latex/formatting/11-code-listing.md)

The code above produces the following output:

![CodeListingEx5.png](/files/M3BEBjDHJkoQvizmIg7X)

Adding the comma-separated parameter `caption=Python example` inside the brackets, enables the caption. This caption can be later used in the list of Listings.

```latex
\lstlistoflistings
```

![CodeListingEx6OLV2.png](/files/tbDLLdU1osm1jPr0PtxD)

## Sample Overleaf project

Open this link to [try out the `listings` package example on Overleaf.](https://www.overleaf.com/project/new/template/20053?id=68266290\&templateName=listings+package+demo\&latexEngine=pdflatex\&texImage=texlive-full%3A2020.1\&mainFile=)

## Reference guide

### Supported languages

**supported languages (and its dialects if possible, dialects are specified in brackets and default dialects are italized):**

|                                                        |                                                  |
| ------------------------------------------------------ | ------------------------------------------------ |
| ABAP (R/2 4.3, R/2 5.0, R/3 3.1, R/3 4.6C, *R/3 6.10*) | ACSL                                             |
| Ada (*2005*, 83, 95)                                   | Algol (60, *68*)                                 |
| Ant                                                    | Assembler (Motorola68k, x86masm)                 |
| Awk (*gnu*, POSIX)                                     | bash                                             |
| Basic (Visual)                                         | C (*ANSI*, Handel, Objective, Sharp)             |
| C++ (ANSI, GNU, *ISO*, Visual)                         | Caml (*light*, Objective)                        |
| CIL                                                    | Clean                                            |
| Cobol (1974, *1985*, ibm)                              | Comal 80                                         |
| command.com (*WinXP*)                                  | Comsol                                           |
| csh                                                    | Delphi                                           |
| Eiffel                                                 | Elan                                             |
| erlang                                                 | Euphoria                                         |
| Fortran (77, 90, *95*)                                 | GCL                                              |
| Gnuplot                                                | Haskell                                          |
| HTML                                                   | IDL (empty, CORBA)                               |
| inform                                                 | Java (empty, AspectJ)                            |
| JVMIS                                                  | ksh                                              |
| Lingo                                                  | Lisp (empty, Auto)                               |
| Logo                                                   | make (empty, gnu)                                |
| Mathematica (1.0, 3.0, *5.2*)                          | Matlab                                           |
| Mercury                                                | MetaPost                                         |
| Miranda                                                | Mizar                                            |
| ML                                                     | Modula-2                                         |
| MuPAD                                                  | NASTRAN                                          |
| Oberon-2                                               | OCL (decorative, *OMG*)                          |
| Octave                                                 | Oz                                               |
| Pascal (Borland6, *Standard*, XSC)                     | Perl                                             |
| PHP                                                    | PL/I                                             |
| Plasm                                                  | PostScript                                       |
| POV                                                    | Prolog                                           |
| Promela                                                | PSTricks                                         |
| Python                                                 | R                                                |
| Reduce                                                 | Rexx                                             |
| RSL                                                    | Ruby                                             |
| S (empty, PLUS)                                        | SAS                                              |
| Scilab                                                 | sh                                               |
| SHELXL                                                 | Simula (*67*, CII, DEC, IBM)                     |
| SPARQL                                                 | SQL                                              |
| tcl (empty, tk)                                        | TeX (AlLaTeX, common, LaTeX, *plain*, primitive) |
| VBScript                                               | Verilog                                          |
| VHDL (empty, AMS)                                      | VRML (*97*)                                      |
| XML                                                    | XSLT                                             |

### Options to customize code listing styles

* **backgroundcolor** - colour for the background. External ***color*** or ***xcolor*** package needed.
* **commentstyle** - style of comments in source language.
* **basicstyle** - font size/family/etc. for source (e.g. `basicstyle=\ttfamily\small`)
* **keywordstyle** - style of keywords in source language (e.g. `keywordstyle=\color{red}`)
* **numberstyle** - style used for line-numbers
* **numbersep** - distance of line-numbers from the code
* **stringstyle** - style of strings in source language
* **showspaces** - emphasize spaces in code (true/false)
* **showstringspaces** - emphasize spaces in strings (true/false)
* **showtabs** - emphasize tabulators in code (true/false)
* **numbers** - position of line numbers (left/right/none, i.e. no line numbers)
* **prebreak** - displaying mark on the end of breaking line (e.g. `prebreak=\raisebox{0ex}[0ex][0ex]{\ensuremath{\hookleftarrow}}`)
* **captionpos** - position of caption (t/b)
* **frame** - showing frame outside code (none/leftline/topline/bottomline/lines/single/shadowbox)
* **breakatwhitespace** - sets if automatic breaks should only happen at whitespaces
* **breaklines** - automatic line-breaking
* **keepspaces** - keep spaces in the code, useful for indetation
* **tabsize** - default tabsize
* **escapeinside** - specify characters to escape from source code to LaTeX (e.g. `escapeinside={\%*}{*)}`)
* **rulecolor** - Specify the colour of the frame-box

## Further reading

For more information see:

* [Code Highlighting with minted](/latex/formatting/12-code-highlighting-with-minted.md)
* [Using colours in LaTeX](/latex/formatting/13-using-colors-in-latex.md)
* [Table of contents](/latex/document-structure/02-table-of-contents.md)
* [Management in a large project](/latex/document-structure/07-management-in-a-large-project.md)
* [Multi-file LaTeX projects](/latex/document-structure/08-multi-file-latex-projects.md)
* [Font sizes, families, and styles](/latex/fonts/01-font-sizes-families-and-styles.md)
* [Font typefaces](/latex/fonts/02-font-typefaces.md)
* [**listings** package documentation](https://texdoc.org/serve/listings/0)
* [**listings** CTAN website](http://www.ctan.org/pkg/listings)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://overleaf-pro.ayaka.space/latex/formatting/11-code-listing.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
