TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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:


@pre: $ \langle \lstinline!a! \rangle $

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).

share|improve this question
Why not simply $\langle$a$\rangle$? – egreg Jan 28 '13 at 20:22
$\langle$a$\rangle$ works in this example, however, $\left($a$\right)$ does not work as mentioned in the last sentence. – Arlen Cox Jan 28 '13 at 20:41
In section 4.14 of the listings documentation you find "Don't use any commands of the listings package when you have escaped to LaTeX". You can use $\biggl($ and $\biggr)$ (or variations thereof). – egreg Jan 28 '13 at 20:54
I missed that. Thanks for the citation. However it doesn't solve the general problem of placing arbitrary formulas that include listings formatted elements within a listing. The \savebox box technique does work, however. – Arlen Cox Jan 28 '13 at 21:23
up vote 2 down vote accepted

I think you want a savebox.





@pre: $ \langle \usebox{\boxa} \rangle $

share|improve this answer
This works! The syntactic overhead is really high however. Is there a way to make this more compact? – Arlen Cox Jan 28 '13 at 20:46
@ArlenCox There may be a way to make it more compact, but I'm not sure how to do it, given everything that is going on with listings. I suspect something tricky involving catcodes would be required. egreg's suggestion is probably best, if you want compact. – G. Poore Jan 28 '13 at 21:53

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.