[Tex/LaTex] Underscore vs. subscript in new command with fancyvrb

math-modeverbatim

I'm using fancyvrb to have math in my verbatim environment as suggested here.

I use a math escape command like so:
\newcommand{\m}[1]{$#1$}

But underscores are not being type set as subscripts, they are showing up as underscores.

\begin{Verbatim}[commandchars=\\\{\}]
for \m{i = 1, 2, \dots n}:
    sample \m{x_i} from \m{P(X_i \vert \mathrm{Parents}(X_i))}
return \m{(x_1, x_2, \dots, x_n)}
\end{Verbatim}

enter image description here

How can I have subscripts using the _ symbol? I think it is related to the definition of my new command.

Best Answer

The \m definition is missing a bit:

\makeatletter
\newcommand{\m][1]{\def\FV@Space{ }$#1$}
\makeatother

so that spaces are treated as usual in math (that is, ignored). But I'll add something more. You can exploit the fact that in verbatim mode the underscore is a printable character:

\documentclass{article}
\usepackage{fancyvrb}
\makeatletter
\newcommand{\m}[1]{%
  \begingroup
  \def\FV@Space{ }% spaces in math are ignored
  \mathcode`\_="8000 % _ is math active
  \do@@us % underscore is subscript
  $#1$%
  \endgroup
}
\newcommand{\do@@us}{%
  \begingroup\lccode`~=`\_ \lowercase{\endgroup\let~}\sb
}
\makeatother
\begin{document}
\begin{Verbatim}[commandchars=\\\{\}]
for \m{i = 1, 2, \dots n}:
    sample \m{x_i} from \m{P(X_i \mid \mathrm{Parents}(X_i))}
return \m{(x_1, x_2, \dots, x_n)}
this_is_verb
\end{Verbatim}
\end{document}

enter image description here