Inserting code in this LaTeX document with indentation

Latex

Latex Problem Overview


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.

Latex Solutions


Solution 1 - Latex

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

Solution 2 - Latex

You could also use the verbatim environment

\begin{verbatim}
your
code
example
\end{verbatim}

Solution 3 - Latex

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}

Solution 4 - Latex

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.

Solution 5 - Latex

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

Solution 6 - Latex

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!

Solution 7 - Latex

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.

Solution 8 - Latex

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}

Solution 9 - Latex

Use Pygments !

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsixtyfootersdudeView Question on Stackoverflow
Solution 1 - LatexCloudangerView Answer on Stackoverflow
Solution 2 - LatexmidtibyView Answer on Stackoverflow
Solution 3 - LatexalanView Answer on Stackoverflow
Solution 4 - LatexPhilippView Answer on Stackoverflow
Solution 5 - LatexShital ShahView Answer on Stackoverflow
Solution 6 - LatexOussama L.View Answer on Stackoverflow
Solution 7 - LatexMoreyView Answer on Stackoverflow
Solution 8 - LatexMattAllegroView Answer on Stackoverflow
Solution 9 - LatexTarantulaView Answer on Stackoverflow