Inline code in LaTeX (texttt, verb, lstinline)

\texttt{code} sets a word in typewriter font. \verb|code| also prints special characters such as _, \ and % as typed, and \lstinline|code| from the listings package adds syntax highlighting.

Preamble

The snippets on this page need these lines before \begin{document}:

\usepackage[T1]{fontenc}
\usepackage{listings}

Typewriter font with texttt

\texttt only changes the font. LaTeX still reads its argument as normal text, so special characters need their escaped form: \_, \%, \#, \{, \} and \textbackslash.

The function \texttt{read\_file} returns \texttt{None}.

Set \texttt{\{"debug": true\}} in \texttt{C:\textbackslash temp\textbackslash app.json}.
Result
The compiled example

Open in the editor

Print characters as typed with verb

\verb takes its content between two equal characters instead of braces. Any character that does not occur in the code works as the delimiter: \verb|a_b| or \verb+a|b+. Nothing inside needs escaping.

Call \verb|read_file("data.csv")| and write \verb+a | b+ for a pipe.
The command \verb|\textbf{text}| prints bold text.
Result
The compiled example

Open in the editor

Highlight inline code with lstinline

\lstinline uses the same delimiters as \verb and the settings from \lstset. The optional argument selects the language for this one piece of code.

\lstset{basicstyle=\ttfamily}
The loop \lstinline[language=Python]|for i in range(3):| runs three times.
Result
The compiled example

Open in the editor

Define your own command for code

A command of your own marks code by its meaning. To change the look of all code words later, for example to add a color, you change one line.

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

Call \code{main()} first, then \code{cleanup()}.
Result
The compiled example

Open in the editor

Pitfalls

Compiled with pdfLaTeX from TeX Live 2023.

Related pages