Skip to content

Instantly share code, notes, and snippets.

@guhetier
Created December 28, 2017 22:45
Show Gist options
  • Save guhetier/f64d7d8772ba31d51ca9d3c65f02705e to your computer and use it in GitHub Desktop.
Save guhetier/f64d7d8772ba31d51ca9d3c65f02705e to your computer and use it in GitHub Desktop.
Make brackets to highligh code lines
%% From https://tex.stackexchange.com/questions/141892/how-can-i-put-a-curly-brace-inside-a-listing-to-group-code-lines
\documentclass{beamer}
\usepackage{tikz}
\usepackage{listings}
\usetikzlibrary{positioning,decorations.pathreplacing,fit}
\newcommand{\tikzmark}[2][]{%
\tikz[remember picture,overlay,baseline=-.5ex] \node[#1] (#2) {};%
}
% \drawBrace[xshift]{beginningNode}{endingNode}
% This command draws a brace between two tikzmarks, to their right,
% no matter which one is the rightmost, and includes
% a node midway the brace, to write the comment.
% This command also creates a new node
% whose name is the concat of the names of beginning and ending nodes.
\newcommand*{\drawBrace}[4][0pt]{%
\node[draw=none, fit={(#2) (#3)}, inner sep=0pt] (rectg) {};%
\draw [decoration={brace,amplitude=0.3em},decorate,very thick,red]%
([xshift=#1]rectg.north east) --%
coordinate[right=1em, midway] (#2#3)
([xshift=#1]rectg.south east);%
\node[right=1.5em of #2#3] (#2#3-comment) {#4};
\draw (#2#3-comment.west) edge (#2#3);
}%
\begin{document}
\begin{lstlisting}[name=listing,escapechar=!]
Example code line 1 !\tikzmark{bgnShifted}!
Example code line 2
Example code line 3
Example code line 4 !\tikzmark{bgnBrace}\tikzmark{trmShifted}!
Example code line 5
Example code line 6
Example code line 7 !\tikzmark{trmBrace}!
Example code line 8
Example code line 9 !\tikzmark{bgnOther}!
Example code line 10 !\tikzmark{trmOther}!
\end{lstlisting}
\begin{tikzpicture}[overlay, remember picture]
\drawBrace[.6em]{bgnShifted}{trmShifted}{Example xshifted.};
\drawBrace{bgnBrace}{trmBrace}{Example annotation.};
\drawBrace{bgnOther}{trmOther}{Another example.};
\end{tikzpicture}
\end{document}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment