# Circled references within code lstlisting

So I just want to create some circled numbers within my code lstlisting, which I could easily reference within a nearby description text.

This is my description text and I want to refer to [1] in \ref{lst:code}:

\begin{lstlisting}[caption={some code here},label={lst:code}]
public int do_something(param 1) {
int a;
int b; [1]
return a+b;
}
\end{lstlisting}


It should finally look something like this within in the listing and the description:

There is two parts to the answer:

• First, you need a way to escape inside the listings environment to LaTex, to execute a LaTeX reference command. Choose delimiters that escape the LaTeX commands that are not used in your code. Since your example seems to in C, I would suggest \*! and !*\ as escape characters. Setup with:

\lstset{escapeinside={/*!}{!*/}}

• Second, you can define an own counter and define references to it using circled symbols like in your example picture. Here, I use from the pifonts package the symbols \ding{182} to \ding{191}. I define then a command that (1) increases the counter, (2) sets a reference, and (3) prints the encircled number:

    \newcommand{\annotation}[1]{\refstepcounter{lstannotation}\label{#1}\thelstannotation}


You can then use \annotation{mylabel} to create a reference with the label mylabel.

Combining both gives a full example:

\documentclass{article}
\usepackage{pifont}
\usepackage{listings}
\lstset{escapeinside={/*!}{!*/}}

\newcounter{lstannotation}
\setcounter{lstannotation}{0}
\renewcommand{\thelstannotation}{\ding{\number\numexpr181+\arabic{lstannotation}}}
\newcommand{\annotation}[1]{\refstepcounter{lstannotation}\label{#1}\thelstannotation}

\begin{document}

This is my description text and I want to refer to \ref{lst:annotation1} and \ref{lst:annotation2} in \ref{lst:code}:

\begin{lstlisting}[caption={some code here},label={lst:code}]
public int do_something(param 1) {
int a;
int b; /*!\annotation{lst:annotation1}!*/
return a+b;
} /*!\annotation{lst:annotation2}!*/
\end{lstlisting}

\end{document}


• So I have one little issue with this solution. As I only did only a short POC during the week, I now have the following issue: \ref{lst:annotation2} won't be incremented. So it's displaying only two (1) within in the paragraph for both references \ref{lst:annotation1} and \ref{lst:annotation2} . Do you have any idea or suggestions? Aug 5 '17 at 16:50
• Right, I didn't test to reference the second annotation. I updated the answer: the solution is essentially to replace \value with \arabic. Aug 5 '17 at 17:57