0

In a LaTeX document, how does one produce a verbatim-type expression like in the StackExchange website, for writing code? For example, example, where you get a grey box highlighting the text. I know about \verb, but not sure if this is attainable. Any ideas? Has this been answered before?

Apologies if I am using the wrong terms, I would be happy to receive any suggestions on how to learn about this.

sam wolfe
  • 257

1 Answers1

0

You have two main solutions: minted and listings. They give similar results, but minted is harder to set up because you need 1) a specific Python module installed and 2) to open a security risk in LaTeX by activating shell escape.

So I'll suggest listings, which works out of the box with no external installation and no special option. Here's a small sample:

\documentclass{article}
\usepackage{listings}

\begin{document}

\begin{lstlisting}[language=Python, numbers=left, frame=single]

A Python example

import numpy as np t = np.linspace(0, 10, 150) \end{lstlisting}

\begin{lstlisting}[language={[LaTeX]TeX}, numbers=left, frame=single] % A LaTeX example \begin{itemize} \item foo \item bar \end{itemize} \end{lstlisting}

\end{document}

result

Of course there are options to tweak the appearence by language, including colored syntax highlighting.

Inside the lstlisting environment, it is verbatim code so by default you can't have LaTeX commands that you want executed. There is a solution if necessary, look for the escapechar option in the documentation. I use to insert \label commands in the code so that I can reference specific lines later on.

Miyase
  • 2,544
  • 2
  • 12
  • 26