[Tex/LaTex] Verbatim environment with correct tab handling and special characters

codeindentationsourcecodesymbolsverbatim

I'm looking for an environment similar to Verbatim which will allow me to say something like the following code (which uses indentation instead of spaces):

\documentclass{article}

\usepackage{fancyvrb}
\usepackage[margin=1in]{geometry}

\begin{document}
    \begin{enumerate}
        \item We first set \texttt{x} to infinity if it is positive:
            \begin{Verbatim}
                if x > 0:
                    x = \infty
            \end{Verbatim}
    \end{enumerate}
\end{document}

and get back exactly the following, in terms of the indentation, the escaping of all symbols (like \infty), etc.

Screenshot

The problem with Verbatim is that it requires me to un-indent the body with respect to the rest of the code, which makes my source code ugly. (I also can't use verbatim because it forces me to use spaces.) Furthermore, I can't figure out how to embed special symbols in it, either.

Is there some environment that fixes these problems with a not-too-difficult syntax for inserting special symbols and math into the code? (Ideally, I would want \ and $ to be the escape characters, but anything that isn't too difficult to type will do.)

Best Answer

UPDATE

Martin Scharrer's lstautogobble package takes care of the tabs issue using the listings package; for the other issues, you can and the mathescape=true, and escapeinside options; a little example:

\documentclass{article}
\usepackage{listings}
\usepackage{lstautogobble}

\lstset{basicstyle=\ttfamily,
  mathescape=true,
  escapeinside=||,
  autogobble}

\begin{document}

    \begin{enumerate}
        \item We first set \texttt{x} to infinity if it is positive:
            \begin{lstlisting}
                if $x > 0$:
                     $x = \infty$
                if x > 0:
                     x = $\infty$
            \end{lstlisting}
    \end{enumerate}

\end{document}

enter image description here

The file lstautogobble.sty can be found in this answer to How to automatically skip leading white spaces in listings