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}.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.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.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()}.Pitfalls
\verbdoes not work inside the argument of another command such as\section,\footnote,\captionor\textbf; LaTeX reports "\verb illegal in argument". Use\textttwith escaped characters there. The content of\verbalso has to stand on one line of the source; a line break inside it stops with \verb ended by end of line.- With the default font encoding OT1, LaTeX takes
\{,\}and\textbackslashfrom a symbol font, also inside\texttt, so they do not match the typewriter font. With\usepackage[T1]{fontenc}they come from the typewriter font. - LaTeX does not hyphenate text in typewriter font. A long piece of code at the end of a line sticks out into the margin and produces Overfull \hbox (263.664pt too wide) in paragraph at lines 3--6.
Compiled with pdfLaTeX from TeX Live 2023.
Related pages
- Package
listings - How-to Insert source code in LaTeX
- How-to Verbatim text in LaTeX
- How-to Special characters in LaTeX: percent, underscore, ampersand, backslash
- Error \verb ended by end of line
- Package
fontenc