Octree LogoOctree

LaTeX Code Listings: Display Programming Code Beautifully

Date Published

LaTeX Code Listings: Display Programming Code Beautifully

Code Listings in LaTeX

Display programming code beautifully in your LaTeX documents with syntax highlighting.

The listings Package

The most common solution for code in LaTeX:

\usepackage{listings}

Basic Usage

\begin{lstlisting} def hello(): print("Hello, World!") \end{lstlisting}

Specify Language

\begin{lstlisting}[language=Python] import numpy as np x = np.array([1, 2, 3]) \end{lstlisting}

Inline Code

\lstinline|print("hello")|

Supported Languages

The listings package supports 100+ languages:

- Python, Java, C, C++ - JavaScript, TypeScript - HTML, CSS - SQL, Bash - And many more

Customizing Appearance

Global Settings

\lstset{ basicstyle=\ttfamily\small, keywordstyle=\color{blue}, commentstyle=\color{green}, stringstyle=\color{red}, numbers=left, numberstyle=\tiny, frame=single, breaklines=true }

Key Options

- basicstyle — font for code - keywordstyle — keywords formatting - commentstyle — comments formatting - stringstyle — strings formatting - numbers — line numbers (left, right, none) - frame — border (none, single, shadowbox) - breaklines — wrap long lines - tabsize — spaces per tab - showstringspaces — show spaces in strings

The minted Package

More powerful syntax highlighting using Pygments:

\usepackage{minted}

Basic Usage

\begin{minted}{python} def factorial(n): return 1 if n <= 1 else n * factorial(n-1) \end{minted}

Inline Code

\mintinline{python}{print("hello")}

Minted Options

\begin{minted}[linenos, frame=lines, fontsize=\small]{python}

Note: minted requires Python and Pygments installed, and compilation with -shell-escape.

Verbatim Environment

For simple, unformatted code:

\begin{verbatim} This is verbatim text. All characters are literal. \end{verbatim}

Inline Verbatim

\verb|special chars: $#%|

Including External Files

With listings

\lstinputlisting[language=Python]{script.py}

With minted

\inputminted{python}{script.py}

Algorithm Pseudocode

For pseudocode (not real code), use algorithm2e or algorithmicx packages instead.

Styling Tips

Choose Readable Fonts

\usepackage{inconsolata} — nice monospace font

Color Schemes

Popular combinations: - Dark keywords, gray comments - Blue keywords, green strings - Match your IDE theme

Consistent Sizing

Use \small or \footnotesize for long code to fit page width.

Common Issues

Problem: Special characters break Solution: Use mathescape=true and escape with $...$

Problem: Long lines overflow Solution: Set breaklines=true

Problem: Wrong language detection Solution: Always specify language=... explicitly

Display Code with Octree

Octree handles code beautifully:

- Easy listings/minted setup - Preview syntax highlighting - AI helps with formatting - Export polished PDFs

Try it at https://useoctree.com