3

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?

3
  • 1
    Spaces are obeyed in verbatim mode; so \(\langle{}x,y\rangle\in{}s^2\) should do.
    – egreg
    Jul 23, 2013 at 20:26
  • 2
    May be you can look into using one of the algorithmic packages in latex to typeset this? It will look better also than verbatim.
    – Nasser
    Jul 23, 2013 at 20:34
  • @egreg Oh, that's what's going on! I guess spaces are a different character class in verbatim mode. If you make that into an answer, I'll accept it.
    – Heatsink
    Jul 24, 2013 at 1:32

1 Answer 1

5

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

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.