516

How do I insert code into a LaTeX document? Is there something like:

\begin{code}## Heading ##
...
\end{code}

The only thing that I really need is indentation and a fixed width font. Syntax highlighting could be nice although it is definitely not required.

3

9 Answers 9

762

Use listings package.

Simple configuration for LaTeX header (before \begin{document}):

\usepackage{listings}
\usepackage{color}

\definecolor{dkgreen}{rgb}{0,0.6,0}
\definecolor{gray}{rgb}{0.5,0.5,0.5}
\definecolor{mauve}{rgb}{0.58,0,0.82}

\lstset{frame=tb,
  language=Java,
  aboveskip=3mm,
  belowskip=3mm,
  showstringspaces=false,
  columns=flexible,
  basicstyle={\small\ttfamily},
  numbers=none,
  numberstyle=\tiny\color{gray},
  keywordstyle=\color{blue},
  commentstyle=\color{dkgreen},
  stringstyle=\color{mauve},
  breaklines=true,
  breakatwhitespace=true,
  tabsize=3
}

You can change default language in the middle of document with \lstset{language=Java}.

Example of usage in the document:

\begin{lstlisting}
// Hello.java
import javax.swing.JApplet;
import java.awt.Graphics;

public class Hello extends JApplet {
    public void paintComponent(Graphics g) {
        g.drawString("Hello, world!", 65, 95);
    }    
}
\end{lstlisting}

Here's the result:

Example image

8
  • 4
    I have a follow up question relating to you code. Have a look if you get a chance: stackoverflow.com/questions/3408996/… Aug 4, 2010 at 19:15
  • 2
    Is there a way to reduce space between lines of code ?
    – sukhvir
    Oct 1, 2014 at 11:29
  • Is it possible to add small text underneath the code snippet, similar to the text written under a figure in Latex?
    – Brian Var
    Jan 18, 2015 at 18:14
  • @Brian I am not aware of that. Perhaps having the code inside a figure could achieve the effect.
    – Cloudanger
    Jan 20, 2015 at 21:30
  • I heard this package is now obsolete!
    – hola
    Jun 15, 2017 at 17:08
230

You could also use the verbatim environment

\begin{verbatim}
your
code
example
\end{verbatim}
3
  • 70
    There is an issue with using tabs inside the verbatim environment. If tabs are converted to "space" the problem disappears.
    – midtiby
    Jul 5, 2010 at 5:57
  • 1
    This is good for showing example text file contents (e.g., textual data to be read/processed by a program).
    – nalyd88
    Feb 15, 2016 at 1:42
  • 1
    For two column article, it does not handle the margins well. Nov 12, 2019 at 13:40
129

Here is how to add inline code:

You can add inline code with {\tt code } or \texttt{ code }. If you want to format the inline code, then it would be best to make your own command

\newcommand{\code}[1]{\texttt{#1}}

Also, note that code blocks can be loaded from other files with

\lstinputlisting[breaklines]{source.c}

breaklines isn't required, but I find it useful. Be aware that you'll have to specify \usepackage{ listings } for this one.

Update: The listings package also includes the \lstinline command, which has the same syntax highlighting features as the \lstlisting and \lstinputlisting commands (see Cloudanger's answer for configuration details). As mentioned in a few other answers, there's also the minted package, which provides the \mintinline command. Like \lstinline, \mintinline provides the same syntax highlighting as a regular minted code block:

\documentclass{article}

\usepackage{minted}

\begin{document}
  This is a sentence with \mintinline{python}{def inlineCode(a="ipsum)}
\end{document}
4
  • 1
    is any better way for inline code which activates keyword colors etc? Aug 23, 2019 at 6:03
  • how do you insert spacing/tabs for making it look more readable? Dec 18, 2019 at 21:03
  • is it possible to remove space between characters when mintinline is used?
    – alper
    Jul 17, 2022 at 0:54
  • I'm not sure what you mean. It sounds like a font issue. The minted page on CTAN has thorough documentation for these sorts of things: ctan.org/pkg/minted
    – alan
    Jul 18, 2022 at 14:59
36

Specialized packages such as minted, which relies on Pygments to do the formatting, offer various advantages over the listings package. To quote from the minted manual,

Pygments provides far superior syntax highlighting compared to conventional packages. For example, listings basically only highlights strings, comments and keywords. Pygments, on the other hand, can be completely customized to highlight any token kind the source language might support. This might include special formatting sequences inside strings, numbers, different kinds of identifiers and exotic constructs such as HTML tags.

2
  • 2
    I have tried minted, the documentation is quite straight forward. The default style is quit good. Aug 12, 2015 at 8:49
  • 9
    This may be an unsatisfactory solution for many users, because of the external call required to Pygmentsic. In particular, the requirement to call latex with the -shell-escape directive is, at best, a minor modification to exisiting build systems, and at worst, incompatible with some users' security preferences.
    – KDN
    Jan 10, 2017 at 18:33
29

Minted, whether from GitHub or CTAN, the Comprehensive TeX Archive Network, works in Overleaf, TeX Live and MiKTeX.

It requires the installation of the Python package Pygments; this is explained in the documentation in either source above. Although Pygments brands itself as a Python syntax highlighter, Minted guarantees the coverage of hundreds of other languages.

Example:

\documentclass{article}
\usepackage{minted}
\begin{document}

\begin{minted}[mathescape, linenos]{python}

# Note: $\pi=\lim_{n\to\infty}\frac{P_n}{d}$
title = "Hello World"

sum = 0
for i in range(10):
 sum += i

\end{minted}

\end{document}

Output:

enter image description here

0
14

Use Minted.

It's a package that facilitates expressive syntax highlighting in LaTeX using the powerful Pygments library. The package also provides options to customize the highlighted source code output using fancyvrb.

It's much more evolved and customizable than any other package!

1
  • 2
    However, as already mentioned on a similar answer, -shell-escape might suck for some people.
    – Egor Hans
    Jul 23, 2018 at 14:30
14

A very simple way if your code is in Python, where I didn't have to install a Python package, is the following:

\documentclass[11pt]{article}  
\usepackage{pythonhighlight}

\begin{document}

The following is some Python code

\begin{python}
# A comment
x = [5, 7, 10]
y = 0

for num in x:
    y += num
    
print(y)
\end{python}

\end{document}

which looks like: enter image description here

Unfortunately, this only works for Python.

1
  • The pythonhilight package works pretty well out of the box. I used it for a while while trying to get install issues I was having with pygments resolved. However, if you want to control: the font size, the syntax highlighting, the background color, the border, whether to include line numbers and where, or have better placement for short code snippets in two column pages, minted is a far better option. Also, PyCharm's support for minted is better: it doesn't complain about _ in a minted environment.
    – hlongmore
    Jan 26 at 8:59
7

Since it wasn't yet mentioned here, it may be worth to add one more option, package spverbatim (no syntax highlighting):

\documentclass{article}
\usepackage{spverbatim}

\begin{document}

\begin{spverbatim}
  Your code here
\end{spverbatim}

\end{document}

Also, if syntax highlighting is not required, package alltt:

\documentclass{article}
\usepackage{alltt}

\begin{document}

\begin{alltt}
  Your code here
\end{alltt}

\end{document}
3
  • 1
    This is more or less what I want, but I can't seem to indent with tabs. How do you indent / is there a similar package that allows for easier indentation? Sep 19, 2018 at 22:47
  • 1
    @Darokrithia I edited my answer: can you check/confront indentation? :) Sep 26, 2018 at 17:28
  • 1
    It doesn't seem to work. I can send you the code I am using, but the formatting is destroyed in comments. BTW I used a different answer and it worked fine, but I feel like this should still be fixed for future readers. Sep 26, 2018 at 20:32
6

Use Pygments !

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.