[Tex/LaTex] \fbox inside listings

boxescodehighlightinglistings

I am trying to highlight a specific line inside a listing with listinline. The code I am currently using looks like this:

\begin{lstlisting}[escapechar=!]
class A {
  void m() {
    B b = ...
    !\fbox{b.n();}!
  }
}   
\end{lstlisting}

This works somewhat, however the text inside the fbox is obviously not processed by the listings package. Using !fbox{\lstinline{b.n();}}! produces an error.

Best Answer

It seems to me that listings doesn't allow any verbatim code between two escape characters. One solution would be to store the \lstinline{b.n();} in a box outside the lstlisting and use the box inside it:

\documentclass{article}

\usepackage{listings}
\usepackage{newverbs}

\newsavebox{\mybox}
\begin{document}
\begin{lrbox}{\mybox}
    \lstinline{b.n();}%
\end{lrbox}

\begin{lstlisting}[escapechar=!]
class A {
  void m() {
    B b = ...
    !\fbox{\usebox\mybox}!
  }
}   
\end{lstlisting}

\end{document}