2

I defined an environnment \lstset{...} to put some code in a beamer presentation.

I would like to frame a specific line in my code, this way:

enter image description here

How can I do that? Have I to use tikz package in addition of \lstset{...}?

J...S
  • 189
Raoul722
  • 365
  • 1
  • 10
  • 1
    related: http://tex.stackexchange.com/questions/79762/automatic-background-coloring-in-listings-using-tikzmark – jub0bs Sep 08 '15 at 09:05

1 Answers1

4

You can use the tikzmark library; the idea is to use escapeinside to place some marks at designated locations and use those marks for the frames.

A little example (compile the code two or three times for the elements to reach their final positions):

\documentclass{beamer}
\usepackage{listings}
\usepackage{tikz}
\usetikzlibrary{tikzmark}

\lstset{
  language=Java,
  basicstyle=\ttfamily,
  keywordstyle=\color{green!70!black}
  columns=fullflexible,
  breaklines=true,
  escapeinside=||
}
\begin{document}

\begin{frame}[fragile]
\frametitle{A test frame}
\begin{lstlisting}
class Complex {
  |\tikzmark{starta}|public float real, imag;|\tikzmark{enda}|
  void Complex(float _real = 0, float _imag = 0) {
    |\tikzmark{startb}|real = _real; imag = _imag|\tikzmark{endb}|
}
public static void main(String[] args) {
  if (new Complex(1, 1).add(new Complex(-1, -1).equal(0))
    system.exit(0)
  }
}
\end{lstlisting}
\begin{tikzpicture}[remember picture,overlay]
\draw[red,rounded corners]
  ([shift={(-3pt,2ex)}]pic cs:starta) 
    rectangle 
  ([shift={(3pt,-0.65ex)}]pic cs:enda);
\draw[red,rounded corners]
  ([shift={(-3pt,2ex)}]pic cs:startb) 
    rectangle 
  ([shift={(3pt,-0.65ex)}]pic cs:endb);
\end{tikzpicture}
\end{frame}

\end{document}

enter image description here

Gonzalo Medina
  • 505,128