[Tex/LaTex] Boldface and subscripts in verbatim mode

boldsubscriptsverbatim

How do I create boldface and subscripts in verbatim mode? I've seen mention of a fancyvrb package that might be able to help. Can anyone provide working LaTeX code, either with or without fancyvrb?

Best Answer

Using the fancyvrb package, with the commandchars option you can introduce escape sequences in verbatim code; in particular, you can get boldfaced fonts (provided you are using a suitable font. Using the codes option you can specify catcode changes ; in particualr, this allows you to include formatted mathematics in verbatim text:

\documentclass{article}
\usepackage{fancyvrb}
\usepackage{bera}

\begin{document}

\begin{Verbatim}[commandchars=\\\{\},codes={\catcode`$=3\catcode`_=8}]
code line 1
$a_{i}$
code line 2
\textbf{boldfaced text}
\end{Verbatim}

\end{document}

enter image description here

Using the more powerful listings package, you can escape to LaTeX using the escapeinside option and you can activate the mathescape option:

\documentclass{article}
\usepackage{listings}
\usepackage{bera}

\lstset{basicstyle=\ttfamily,
escapeinside={||},
mathescape=true}

\begin{document}

\begin{lstlisting}
code line 1
$a_{i}$
code line 2
|\textbf{boldfaced text}|
\end{lstlisting}

\end{document}

enter image description here

The above solutions treted subscripts as mathematical expressions; you can get non-math subscripts using \textsubscript from the fixltx2e package; a little example using fancyvrb:

\documentclass{article}
\usepackage{fancyvrb}
\usepackage{fixltx2e}
\usepackage{bera}

\begin{document}

\begin{Verbatim}[commandchars=\\\{\},codes={\catcode`$=3\catcode`_=8}]
code line 1
$a_{i}$
code line 2
\textbf{boldfaced text}
a\textsubscript{i}
\end{Verbatim}

\end{document}

enter image description here