logo

How to Insert Code Blocks in LaTeX Documents 📂Writing

How to Insert Code Blocks in LaTeX Documents

Description

$\TeX$ There are two methods you can use when you want to add a code block to a document.

  1. $\text{\textbackslash begin}\{\text{verbatim}\} … \text{\textbackslash end}\{\text{verbatim}\}$
  2. $\text{\textbackslash begin}\{\text{lstlisting}\} … \text{\textbackslash end}\{\text{lstlisting}\}$

Among these, verbatim is a basic feature that doesn’t require the use of a package, whereas lstlisting requires \usepackage{listings}.

Code

3524_texcodeblock.png

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{listings}

\title{How to Insert a Code Block in \LaTeX?}
\date{}

\begin{document}
\maketitle

verbatim style:
\begin{verbatim}
def add(x, y)
    sum = x + y

    return sum
\end{verbatim}

lstlisting style:
\begin{lstlisting}
def add(x, y)
    sum = x + y

    return sum
\end{lstlisting}


\end{document}

Environment

  • Editor: Overleaf
  • Compiler: pdfLaTeX
  • TeX Live version: 2022