[Tex/LaTex] Why does using lstinline inside mathescape inside lstlisting not work

listings

I'm trying to typeset some code. That code has some embedded mathematics, but in the embedded mathematics, I need to reference variables from the code. I would like for the variables in referenced inside the mathematics to be typeset like the actual code (so I do not want to use the mathtt environment). Unfortunately I get an error when I try to do this. Here is an example:

\documentclass[11pt]{article}
\usepackage{listings}

\begin{document}
\begin{lstlisting}[mathescape]
@pre: $ \langle \lstinline!a! \rangle $
\end{lstlisting}
\end{document}

I get the following error message:

ERROR: Extra }, or forgotten \endgroup.

--- TeX said ---
<recently read> \egroup 

l.6 @pre: $ \langle \lstinline!a!
                                  \rangle $

I've also tried using \lstinline{a}. I've also tried embedding this inside an \mbox and a \parbox. I've also tried using the \begin{lstlisting}[escapechar=^] and adding an extra ^ around the math formula.

I cannot simply leave the escape environment as I am wrapping these inlined characters in big symbols like \left( and \right).

Best Answer

I think you want a savebox.

\documentclass[11pt]{article}

\usepackage{listings}

\begin{document}

\newsavebox\boxa
\savebox\boxa{\lstinline{a}}

\begin{lstlisting}[mathescape]
@pre: $ \langle \usebox{\boxa} \rangle $
\end{lstlisting}

\end{document}