Typevia
Code and Verbatim

Introduction to Verbatim Text

In LaTeX, certain characters like \, {, }, $, and % have special meanings. If you try to type these directly into your document, LaTeX will attempt to execute them as commands or logic, which often leads to errors or missing text.

Verbatim text allows you to tell LaTeX: "Stop interpreting these symbols and just print exactly what I type." This is essential when writing about programming, showing LaTeX code itself, or displaying file paths.

In this guide, we will move from basic inline commands to sophisticated packages used for professional code documentation.


1. Inline Verbatim with \verb

When you need to include a small snippet of code or a file path within a sentence, you use the \verb command.

Unlike most LaTeX commands that use curly braces { }, \verb uses a pair of delimiters to bookend the text. You can use almost any character as a delimiter (commonly |, +, or !), as long as that character does not appear within the code snippet itself.

Basic Syntax

The command \verb|\section| creates a new heading.
You can also use other delimiters: \verb+C:\Users\Documents+.

Key Rules for \verb

  • No Curly Braces: Do not use \verb{code}. It will fail.
  • Single Line Only: \verb cannot span across multiple lines.
  • The Starred Version: If you want to see visible spaces (represented by a small "u" shape), use \verb*.
This shows spaces: \verb*|int x = 5;|

Note: A common pitfall for beginners is trying to use \verb inside another command, such as \footnote{Check out \verb|code|}. This will cause a compilation error. For those cases, you need more advanced packages or specialized workarounds.


2. Basic Code Blocks with the verbatim Environment

If you need to display multiple lines of code as a standalone block, the verbatim environment is the simplest tool available. It uses a monospaced (fixed-width) font and preserves all line breaks and spaces.

Usage Example

\begin{verbatim}
def hello_world():
    print("Hello, LaTeX!")
    
# This comment and the indentation are preserved.
\end{verbatim}

The verbatim* Variant

Just like the inline command, the environment has a starred version that makes every space character visible. This is particularly useful when whitespace is critical, such as in Python or YAML.

\begin{verbatim*}
Line with spaces
    Indented line
\end{verbatim*}

3. Advanced Code Highlighting with the listings Package

The standard verbatim environment is functional but plain. It doesn't support colors, bold keywords, or line numbers. For real-world technical documents, the listings package is the industry standard.

To use it, add \usepackage{listings} to your preamble.

Basic Implementation

The listings package provides the lstlisting environment.

\usepackage{listings}

% ... inside the document ...

\begin{lstlisting}[language=Python, caption={My first Python script}]
def greet(name):
    return f"Hello, {name}"

print(greet("World"))
\end{lstlisting}

Customizing the Appearance

One of the best features of listings is the ability to define a global style. You can set colors, fonts, and frames in the preamble using \lstset.

\usepackage{xcolor}
\usepackage{listings}

\lstset{
    backgroundcolor=\color{gray!10},   % light gray background
    basicstyle=\ttfamily\small,        % use typewriter font
    breaklines=true,                   % wrap long lines
    keywordstyle=\color{blue},          % functions/keywords in blue
    commentstyle=\color{green!50!black}, % comments in dark green
    numbers=left,                      % line numbers on the left
    numberstyle=\tiny\color{gray},     % line number style
    frame=single                       % add a border around the code
}

Loading External Files

If you have a large source code file (e.g., main.cpp), you don't have to copy-paste it into LaTeX. You can pull it in directly:

\lstinputlisting[language=C++]{source_code/main.cpp}

4. Professional Highlighting with minted

While listings is powerful, it uses LaTeX's internal logic to "guess" keywords. For high-fidelity syntax highlighting that looks like a modern text editor (VS Code or Sublime Text), many users prefer the minted package.

minted uses an external Python library called Pygments.

Why use minted?

  1. Superior Accuracy: It recognizes almost every programming language in existence.
  2. Beautiful Themes: It supports many color schemes (like Monokai or Solarized).

Basic Usage

To use minted, you must add \usepackage{minted} and compile your document with the -shell-escape flag enabled in your LaTeX editor settings.

\begin{minted}{python}
def calculate_area(radius):
    import math
    return math.pi * radius**2
\end{minted}

Warning: Because minted requires an external Python installation and specific compiler flags, it can be slightly harder to set up for absolute beginners than listings. If you are using an online editor like Typevia, minted usually works "out of the box."


5. Summary and Best Practices

Choosing the right method depends on your specific needs:

RequirementRecommended Tool
Simple file path or command inside a sentence`\verb
Multiple lines of plain text without formattingverbatim environment
Documenting code with line numbers and frameslistings package
High-end, colorful syntax highlightingminted package

Best Practices

  1. Be Consistent: Don't mix listings and minted in the same document. Choose one and stick to it for a uniform look.
  2. Use \ttfamily: If you are creating your own commands for code-like text, use the Typewriter font (\texttt{...}) for visual consistency.
  3. Mind the Indentation: In a verbatim environment, LaTeX starts recording text from the very first character after \begin{verbatim}. Avoid adding extra tabs inside the environment unless you want them to appear in the PDF.
  4. Escape-Hatch: If you find yourself struggling with a complex code block that keeps breaking your build, consider taking a screenshot of the code and inserting it as an image with \includegraphics, though this prevents readers from copying and pasting the text.

By mastering these tools, you can transform your technical documents from plain text into professional-grade manuals and reports.