[Tex/LaTex] Putting math inside a verbatim environment without altering the formatting

math-modespacingverbatim

In a verbatim code listing, I want to use inline math in comments with the same formatting that I get for inline math in body text. I can use a math environment, but the spacing is weird. In this example, there is a lot of space inside the angle brackets and after the comma.

\documentclass{article}
\usepackage{fancyvrb}
\begin{document}

\begin{Verbatim}[commandchars=\\\{\},codes={\catcode`^=7}]
# visit each \(\langle x, y \rangle \in s^2\)
for x in s:
  for y in s:
    foo(x, y)
\end{Verbatim}

\end{document}

Is there a way to get normal spacing?

Related: How do I use mathematical symbols in verbatim mode?

Best Answer

Spaces are obeyed in verbatim mode and Verbatim uses (backslash-space) when it finds a space in the input. There are some workarounds. In all the examples I omitted \catcode`^=7, preferring \sp instead of ^; but your option can be employed as well.

Using empty groups

\documentclass{article}
\usepackage{fancyvrb}
\begin{document}

\begin{Verbatim}[commandchars=\\\{\}]
# visit each \(\langle{}x,y\rangle\in{}s\sp{2}\)
for x in s:
  for y in s:
    foo(x, y)
\end{Verbatim}

\end{document}

This adds ordinary math atoms, but it should rarely be a concern with respect to spacing.

Using a noop macro

\documentclass{article}
\usepackage{fancyvrb}
\begin{document}

\newcommand{\?}{}

\begin{Verbatim}[commandchars=\\\{\}]
# visit each \(\langle\?x,y\rangle\in\?s\sp{2}\)
for x in s:
  for y in s:
    foo(x, y)
\end{Verbatim}

\end{document}

This avoids all possible spacing issues. Notice that a control symbol is used, so there's no need to delimit it with spaces.

Make the space again an ignored space in math mode

\documentclass{article}
\usepackage{fancyvrb}
\begin{document}

\makeatletter
\newcommand{\verbmathspace}{\let\FV@Space\space}
\makeatother

\begin{Verbatim}[commandchars=\\\{\},
  codes=\everymath\expandafter{\the\everymath\verbmathspace}]
# visit each \(\langle x, y\rangle\in s\sp{2}\)
for x in s:
  for y in s:
    foo(x, y)
\end{Verbatim}

\end{document}

In math mode the space is reverted to a normal space, so it will be ignored by TeX rule.

Output for all the examples

enter image description here