Tx · LaTeX & TikZ

Best Practices for Publishing Computer Code with LaTeX

Published By the 9to5Science editorial team

At a glance

  1. 1. Choose the right tool

    Use verbatim for short snippets, listings for configurable code, and minted when syntax highlighting is worth the extra setup.

  2. 2. Make code readable

    Set a readable monospaced font, line spacing, margins, line numbers, and a language appropriate to the snippet.

  3. 3. Keep examples maintainable

    Store substantial source in external files so the document and published code do not drift apart.

  4. 4. Build safely

    Use shell escape only when required, and never execute untrusted source during compilation.

Computer code should be presented as code, not typeset as ordinary LaTeX prose. That means preserving spaces and indentation, using a monospaced font, preventing special characters such as _, {, and \ from being interpreted, and choosing line breaks that remain readable in the page layout.

The best method depends on the size and purpose of the example. This article compares the standard approaches and gives a complete document you can compile.

Choose the simplest suitable method

Use verbatim for tiny examples

The built-in verbatim environment requires no package:

\begin{verbatim}
for i in range(10):
    print(i)
\end{verbatim}

It preserves the input literally, so it is reliable for a short command or a few lines. It does not provide syntax highlighting, line numbers, captions, labels, or convenient control over the appearance.

Use listings for most documents

The listings package is usually the best default for papers, theses, lecture notes, and books. It formats code inside the document, supports many languages, allows line numbering and captions, and does not need an external syntax-highlighting program.

Use minted for advanced highlighting

The minted package delegates highlighting to external Pygments-based tooling (in current versions, through latexminted). It supports many languages and often produces more attractive highlighting, but compilation needs Python, Pygments, and permission to run an external command. This makes it less convenient on restricted systems and in automated publishing workflows.

A complete listings example

This document uses listings with a restrained style suitable for publication:

\documentclass{article}

\usepackage[T1]{fontenc}
\usepackage{xcolor}
\usepackage{listings}
\usepackage{inconsolata}

\definecolor{codegray}{gray}{0.95}
\definecolor{commentgray}{gray}{0.40}
\definecolor{keywordblue}{rgb}{0.00,0.25,0.60}

\lstdefinestyle{publishedcode}{
  language=Python,
  basicstyle=\small\ttfamily,
  keywordstyle=\color{keywordblue}\bfseries,
  commentstyle=\color{commentgray}\itshape,
  stringstyle=\color{purple},
  backgroundcolor=\color{codegray},
  numbers=left,
  numberstyle=\scriptsize\color{commentgray},
  numbersep=8pt,
  frame=single,
  rulecolor=\color{black!20},
  breaklines=true,
  breakatwhitespace=false,
  showstringspaces=false,
  columns=fullflexible,
  keepspaces=true
}

\lstset{style=publishedcode}

\begin{document}

The following function computes the mean of a nonempty sequence.

\begin{lstlisting}[caption={Computing a mean}, label={lst:mean}]
def mean(values):
    if not values:
        raise ValueError("values must not be empty")
    return sum(values) / len(values)
\end{lstlisting}

Listing~\ref{lst:mean} rejects an empty input before performing the division.

\end{document}

The packages in this example are listings for code, xcolor for colors, fontenc for good font encoding with pdfLaTeX, and inconsolata for a readable monospaced font. The font package is optional; remove it if it is unavailable.

basicstyle controls the ordinary code font. breaklines=true prevents long lines from running into the margin. keepspaces=true preserves indentation, while showstringspaces=false avoids marking spaces inside quoted strings with visible symbols. The caption and label options make the listing a numbered, cross-referenceable document object.

Keep long code in external files

For a substantial program, do not paste the same source into both the project and the paper. Store the code in a version-controlled file and load it into the document:

\lstinputlisting[
  language=Python,
  caption={The data-cleaning script},
  label={lst:cleaning},
  firstline=12,
  lastline=28
]{src/clean_data.py}

This has three advantages: the typeset listing reflects the source file, line ranges can focus attention on the relevant section, and the complete program can be distributed separately. Use a relative path and keep the source file in the project repository so another reader can reproduce the build.

If you publish a code fragment that is intentionally simplified, say so in the caption or surrounding text. Readers should be able to distinguish executable source from pseudocode or an excerpt.

When to use minted

A minimal minted example is:

\documentclass{article}
\usepackage{minted}

\begin{document}

\begin{minted}[linenos, breaklines, frame=lines]{python}
def mean(values):
    if not values:
        raise ValueError("values must not be empty")
    return sum(values) / len(values)
\end{minted}

\end{document}

Compile this with a command such as:

pdflatex -shell-escape document.tex

The exact command may differ for an editor or build system. This command enables unrestricted shell escape and is a widely compatible way to build minted documents, but it is not the safest choice for untrusted projects. Current versions of minted can instead use restricted shell escape with latexminted on supported TeX systems; older versions or other setups may require unrestricted -shell-escape. minted invokes Pygments through that tooling, so Python and the Pygments package must be installed. Restricted shell escape is safer than unrestricted shell escape because it limits which external commands can be run, but do not assume every installation is configured that way. With unrestricted shell escape, a malicious document can use external-command permissions to access files or run programs.

If a journal, thesis template, or online service does not permit shell escape or does not provide the required latexminted setup, use listings or ask whether the service provides a configured minted workflow.

Design choices that improve readability

  • Use a sufficiently large font. Code that is technically present but unreadable at normal zoom is not useful. \small\ttfamily is often a reasonable starting point; check the result in print as well as on screen.
  • Avoid excessive color. A pale background and one or two text colors usually reproduce better than a dark editor theme. Ensure that meaning does not depend only on color.
  • Break long lines deliberately. Automatic breaks are useful, but a long line may still be hard to understand. Refactor the example or show a carefully chosen excerpt when possible.
  • Add line numbers selectively. They help discussion and debugging, but they add visual weight. For a short code fragment, omit them.
  • Identify the language. Language selection controls keywords and comments. Do not label pseudocode as Python, C, or another executable language unless it follows that language’s syntax.
  • Explain the code outside the listing. A caption should identify the purpose; the surrounding text should explain assumptions, input, output, and any omitted context.

Common mistakes

Putting code in \texttt{}

\texttt{} changes the font but does not make ordinary LaTeX input safe. Characters such as %, _, #, and \ can still have LaTeX meanings. Use \verb|short_code| for a very short inline fragment, or use verbatim, listings, or minted for blocks.

Letting code float unexpectedly

A listings caption does not necessarily make the listing a float. If you use a floating listing environment, LaTeX may move it like a figure. That is often helpful in a paper, but confusing in instructions that require code to appear immediately after a sentence. Choose placement intentionally and avoid forcing every float with many [H] options.

Copying editor formatting blindly

Tabs, trailing whitespace, invisible Unicode characters, and very long lines can create inconsistent output. Normalize the source, preserve meaningful indentation, and test the exact files that will be published.

Publishing incomplete or non-reproducible code

State the language version, important dependencies, input-data assumptions, and the license when those details matter. For research code, provide a repository or archive, a README, and enough information to run the relevant example. The PDF listing is documentation; it is not a substitute for the source distribution.

Executing code accidentally

Neither listings nor minted normally executes the displayed program. Avoid packages or custom build scripts that run source code unless that behavior is deliberate, isolated, and understood. Treat compilation of an unfamiliar project as running a program when shell escape is enabled.

A practical default

Start with listings and an external source file. Use verbatim when the snippet is only a few lines and needs no formatting. Move to minted when its highlighting is materially better for your readers and your build environment can safely support Pygments. In every case, make the code readable, label it accurately, and publish the executable source separately when reproducibility matters.

References

  1. The LaTeX2e Reference Manual
  2. The listings package documentation
  3. The minted package documentation

Spotted an error? Send a correction. Read how we write and check articles in our editorial policy.