How to Write Code in LaTeX

For a short piece of code in a sentence write \verb|x = 1| or \texttt{…}. For a block, use the verbatim environment for plain text, or the listings package (\begin{lstlisting}[language=Python] … \end{lstlisting}) for syntax highlighting, line numbers and frames. minted gives the nicest colors but needs shell escape.

Ways to show code

  • \verb|print("hi")|
    print("hi")

    Inline code, printed exactly as typed.

  • \texttt{print}
    print

    Monospace text; special characters must be escaped.

  • \begin{verbatim} ... \end{verbatim}
    Text mode, no math preview

    Plain code block, no highlighting.

  • \begin{lstlisting}[language=Python] ... \end{lstlisting}
    Text mode, no math preview

    listings: highlighting, numbers, frames.

  • \lstinputlisting[language=C]{main.c}
    Text mode, no math preview

    Include code from a file.

  • \begin{minted}{python} ... \end{minted}
    Text mode, no math preview

    minted: Pygments colors; needs -shell-escape.

Try it live

Change the formula and the preview redraws as you type. Copy the LaTeX, download a PNG or SVG, copy it for Word, or use Edit here on any example below to load it.

Templates

Code listings examples

Each result below is drawn from the LaTeX under it. Copy the code, edit it on this page, or open it in the full editor.

  • Code next to the math it computes

    sum(range(n)) = ∑ i = 0 n − 1 i
    LaTeX
    \texttt{sum(range(n))} = \sum_{i=0}^{n-1} i
  • A variable name in a formula

    max _ iter = 100
    LaTeX
    \mathtt{max\_iter} = 100

In a LaTeX document

These commands work in the text of a .tex document (Overleaf, TeX Live, MiKTeX), not inside math. The box on the right shows what the compiled PDF looks like.

  • Python with listings

    LaTeX
    \usepackage{listings}
    \usepackage{xcolor}
    \lstset{basicstyle=\ttfamily\small, numbers=left, frame=single,
      keywordstyle=\color{blue}, commentstyle=\color{gray}, showstringspaces=false}
    ...
    \begin{lstlisting}[language=Python]
    def mean(xs):
        # average of a list
        return sum(xs) / len(xs)
    \end{lstlisting}
  • Plain verbatim block

    LaTeX
    \begin{verbatim}
    $ pdflatex paper.tex
    $ bibtex paper
    \end{verbatim}
    Compiled result

    $ pdflatex paper.tex

    $ bibtex paper

  • minted (Overleaf has shell escape on)

    LaTeX
    \usepackage{minted}
    ...
    \begin{minted}[linenos]{javascript}
    const total = items.reduce((a, b) => a + b, 0);
    \end{minted}

listings or minted

listings is pure LaTeX: it works everywhere and colors keywords for dozens of languages, set with language=. minted calls the Python tool Pygments, so the highlighting is richer and closer to an editor, but the document must be compiled with -shell-escape. Overleaf enables it; on your own machine add the flag.

Both accept options for line numbers, a frame, a caption (caption=… in listings) and a \label, and both can read code from a file so the document never goes out of date.

Pseudo-code

For algorithms written as steps rather than real code, use the algorithm environment with algpseudocode or algorithm2e, which set keywords such as "if" and "return" and number the lines.

Common mistakes

  • \verb cannot be used inside another command's argument.

    Instead of
    \section{The \verb|x| variable}
    Write
    \section{The \texttt{x} variable}
  • Inside \texttt the special characters still need escaping; \verb does not.

    Instead of
    \texttt{a_b%c}
    Write
    \texttt{a\_b\%c}
  • minted fails with "You must invoke LaTeX with the -shell-escape flag".

    Instead of
    \begin{minted}...  (no -shell-escape)
    Write
    pdflatex -shell-escape file.tex

In Overleaf, MathJax and Word

  • Overleaf and pdfLaTeX

    listings and verbatim work out of the box; minted works because Overleaf compiles with shell escape.

  • MathJax and KaTeX

    Web renderers do not do code blocks; on the web use Markdown code fences or an HTML pre element. In math, \texttt and \mathtt give monospace text.

  • Microsoft Word

    In Word paste code into a one-cell table or use a monospace font such as Consolas; Word has no syntax highlighting.

Already have the whole document?

Move complete papers between PDF, Word and LaTeX without retyping; every equation stays editable.

Single printed formulas are free: 3 a day without an account, 6 with a free account. New accounts get 30 credits to try handwriting, pages and documents; failed conversions return their credits. See plans and credit prices.

Code listings in LaTeX: questions

How do I write code in LaTeX?
Use \verb|…| inline, verbatim for plain blocks, or the listings package for highlighted blocks.
How do I add syntax highlighting?
Use listings with language= and \lstset colors, or minted with shell escape.
How do I include a source file?
\lstinputlisting[language=Python]{script.py} or \inputminted{python}{script.py}.

Have the formula as a picture?

Paste a screenshot or photo of the equation and get its LaTeX, ready to copy or open in the editor.

Convert an image to LaTeX