9

I am using the listings package to incorporate listings into my paper.

However I'd like to reference individual parts of the code with a small circular number (such as say the number 1 in white surrounded by a small black filled circle) and then reference this within the main body outside of the listing by reusing the small graphic along with some explanatory text.

I am not sure how to place my code here but essentially it is just code within:

\begin{lstlisting}[caption=...]
this is some code here...
\end{lstlisting}

So in summary a way of referencing an individual part of a listing within the code and using that reference in my main body. In the above example say a small indicator by the 'some' and then be able to reference that in my body afterwards.

Apologies if I sound confused. I know what I am trying to do but couldn't see any way of doing it in the listing documentation.

1 Answer 1

12

By default the listings package seems to number labels with the line number itself (even if line numbering is hidden!), which it is an elegant option. So, I recommend using the line number as reference instead of adding more noise.

In the code I show three ways of doing it 1) using the line as reference, 2) using a footnote and 3) perhaps what you want which is to a personalized label.

\documentclass{article}
\usepackage{hyperref}
\usepackage{listings}
\usepackage{xcolor}
\begin{document}

Bla bla

\newcounter{codecounter}

\begin{lstlisting}[escapeinside={(*}{*)}, numbers=right]
/* Hello World program */

#include<stdio.h>
main()
{
    printf("Hello World"); (*\label{code:printf}*)
    double a = b (*\textcolor{red}{\footnote{This is a variable $b$}}*) + c;
    double d = b (*\textcolor{red}{(\refstepcounter{codecounter}\thecodecounter\label{code:b})}*) + c;
}

\end{lstlisting}

We produce the output in line \ref{code:printf}. Or concentrate on \textcolor{red}{(\ref{code:b})}.

\end{document}


We produce the output in line \ref{code:printf}.

\end{document}

The numbers can appear on the right with numbers=right

main footnote

3
  • Hi, many thanks, unfortunately perhaps I should have been clearer :) I need to label individual characters as the material referenced might be a variable for example... a = b+ c, and I would need to reference b!
    – Hi Lo
    Commented Dec 31, 2015 at 0:15
  • 2
    Fortunately the variable b can be referenced by its own name, "b". Maybe what you like is to highlight b. Anyway I posted an alternative using footnote.
    – alfC
    Commented Dec 31, 2015 at 0:21
  • 1
    Ok, I put all the alternatives, it is easy to beautify, but using other footnote or fancy labeler packages.
    – alfC
    Commented Dec 31, 2015 at 0:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .