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
\(\langle{}x,y\rangle\in{}s^2\)
should do.