[Tex/LaTex] Using math mode escapes with listings enabled fancyvrb

fancyvrblistingsmath-modeverbatim

I am trying to escape math mode within Verbatim, using this answer. This works fine, until I use the listings package with fancyvrb=true

\documentclass{article}
\usepackage{fancyvrb}
\usepackage{listings}
\lstset{
% fancyvrb=true,%
}

\begin{document}

\begin{Verbatim}[commandchars=\\\{\},codes={\catcode`$=3\catcode`^=7}]
x=1/sqrt(z**2) ! $\frac{1}{\sqrt{z^2}}$
\end{Verbatim}

\end{document}

If I enable the fancyvrb=true, I get the following error: Missing $ inserted. And then nothing works.


EDIT: Taking the idea of adding mathescape=true from this answer, it seems to work in some cases, in others not:

\documentclass{article}
\usepackage{fancyvrb}
\usepackage{listings}
\lstset{
fancyvrb=true,%
mathescape=true,%
}

\begin{document}

Outside of verbatim: $\mathsf{lb}_\mathsf{pre}$:

\begin{Verbatim}[commandchars=\\\{\},codes={\catcode`$=3\catcode`^=7}]
x=1/sqrt(z**2) ! $\frac{1}{\sqrt{z^2}}$
Vertex = ($\mathsf{lb}_\mathsf{pre}$: Label, $\mathsf{lb}_\mathsf{post}$: Label)
\end{Verbatim}

\end{document}

The subscript still doesn't work inside the verbatim:

enter image description here


If there is no solution to this, how could I disable listings temporarily for one particular Verbatim block?

Best Answer

Change locally the setting with formatcom:

\documentclass{article}
\usepackage{fancyvrb}
\usepackage{listings}
\lstset{
 fancyvrb=true,%
}

\begin{document}

\begin{Verbatim}[commandchars=\\\{\},
  codes={\catcode`$=3\catcode`^=7},
  formatcom={\lstset{fancyvrb=false}}]
x=1/sqrt(z**2) ! $\frac{1}{\sqrt{z^2}}$
\end{Verbatim}

\begin{Verbatim}[commandchars=\\\{\},
  codes={\catcode`$=3\catcode`^=7\catcode`_=8},
  formatcom={\lstset{fancyvrb=false}}]
x=1/sqrt(z**2) ! $\frac{1}{\sqrt{z^2}}$
Vertex = ($\mathsf{lb}_\mathsf{pre}$: Label, $\mathsf{lb}_\mathsf{post}$: Label)
\end{Verbatim}

\end{document}

The \lstset is local, so it won't propagate to the following listings environments. For the subscripts you have to reset also the category code of _.

enter image description here