2

I tried looking up for this, but I have not found a way to do both at the same time.

I would like to write math symbols in a verbatim like environment, for which I use alltt. But I would also like to have my code in a box, for which I used to use \usepackage{fancyvrb} and Verbatim environment.

Is there a way to combine both?

4

Yes, you can do that, as explained on page 16 of the fancyvrb documentation:

\documentclass{article}
\usepackage{fancyvrb}

\begin{document}

\begin{Verbatim}[commandchars=\\\{\},
codes={\catcode`$=3\catcode`^=7\catcode`_=8},frame=single]
some code test
$\sum a_i$
\end{Verbatim}

\end{document}

enter image description here

I'd suggest you to switch to listings and use its mathescape=true feature:

\documentclass{article}
\usepackage{listings}

\lstset{
  basicstyle=\ttfamily,
  columns=fullflexible,
  mathescape=true,
  frame=single
}

\begin{document}

\begin{lstlisting}
some code test
$\sum a_i$
\end{lstlisting}

\end{document}

enter image description here

If you want fancier boxes, then you could use tcolorbox and its interaction with listings.

1
  • Will certainly look up for the listings you have updated, but for my purpose, Verbatim works just fine thanks!
    – Anthony
    Sep 8 '15 at 16:45
1

The following example derived from the documentation of fancyvrb, section "4.1.6 Catcode characters".

\documentclass[a5paper]{article}
\usepackage{fancyvrb}
\begin{document}
\begin{Verbatim}[
  frame=single,
  commandchars=\\\{\},
  codes={%
    \catcode`$=3\relax
    \catcode`^=7\relax
    \catcode`_=8\relax
  },
]
x\string_0=1/sqrt(z\string^2) ! $x_0=\frac{1}{\sqrt{z^2}}$
\end{Verbatim}
\begin{Verbatim}[
  frame=single,
  commandchars=\\\{\},
  codes={%
    \catcode`$=3\relax
  },
]
x_0=1/sqrt(z^2) ! $x\sb{0}=\frac{1}{\sqrt{z\sp{2}}}$
\end{Verbatim}
\end{document}

Result

When _ and ^ have the normal category codes, then they needed to be prefixed by \string, if they should be set in verbatim mode.

Alternatively, _ and ^ are kept unchanged and \sb and \sp are used in math mode instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.