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")|Inline code, printed exactly as typed.
\texttt{print}Monospace text; special characters must be escaped.
- Text mode, no math preview
\begin{verbatim} ... \end{verbatim}Plain code block, no highlighting.
- Text mode, no math preview
\begin{lstlisting}[language=Python] ... \end{lstlisting}listings: highlighting, numbers, frames.
- Text mode, no math preview
\lstinputlisting[language=C]{main.c}Include code from a file.
- Text mode, no math preview
\begin{minted}{python} ... \end{minted}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.
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
LaTeX\texttt{sum(range(n))} = \sum_{i=0}^{n-1} iA variable name in a formula
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
\verbcannot be used inside another command's argument.Instead of\section{The \verb|x| variable}Write\section{The \texttt{x} variable}Inside
\textttthe special characters still need escaping;\verbdoes 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)Writepdflatex -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,
\textttand\mathttgive 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.
- PDF to LaTeXTurn a paper or textbook PDF into a .tex project with every equation.10 credits per page
- Word to LaTeXA .docx with Word equations becomes LaTeX ready for Overleaf.10 credits per page
- LaTeX to WordA whole .tex file becomes a .docx whose equations open in Word.5 credits per file
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\lstsetcolors, or minted with shell escape. - How do I include a source file?
\lstinputlisting[language=Python]{script.py}or\inputminted{python}{script.py}.
Related LaTeX reference
- How to Type a Backslash in LaTeXThe \ character in text (\textbackslash), in math (\backslash), in code (\verb) and as set minus (\setminus).
- How to Cite in LaTeXA .bib file, \cite{key}, BibTeX or biblatex, citation styles, citing websites and fixing [?].
- How to Insert an Image in LaTeXgraphicx, \includegraphics with width, figure placement, captions, labels and side-by-side images.
- How to Start a New Page in LaTeX\newpage, \clearpage, \cleardoublepage and \pagebreak compared, floats, blank pages and breaks inside long equations.
- LaTeX equation editorSymbol panel, live preview, and PNG, SVG, MathML or Word export.
- All LaTeX reference pagesSymbols, math structures and text formatting in one list.
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