# How to refer to line numbers of source code in listings without adding labels by hand?

I use listings to produce my Matlab code. There I can use the \label and \ref commands for readers to direct them to my code and line number.

\begin{lstlisting}[caption={Code for deflection at the point of intersection},label={lst:A.1},numbers=left,escapeinside={@}{@}]
@\label{lst:Li11}@In_x = X_num - 1;
\end{lstlisting}

As you can see in listing \ref{lst:A.1} line number \ref{lst:Li11}


My code is 700 lines and I have to discuss each line of my code by cross-referring. As you can see it's tiring. Is there any other way so that I can label the line number quickly?

listings doesn't add labels automatically to each line number, but we can use the EveryPar hook to do that. The following code defines a label for each line, based on the listing's label value plus the line number separated by a hyphen, so in your example lst:A.1-1, lst:A.1-2 etc.

\documentclass{article}
\usepackage{listings}
\usepackage{hyperref}

\makeatletter

\edef\@temp{\noexpand\label{\lst@label-\arabic{lstnumber}}}%
\@temp
}

\makeatother

\begin{document}
\begin{lstlisting}[
caption={Code for deflection at the point of intersection},
label={lst:A.1},
numbers=left,
basicstyle=\ttfamily,
escapeinside={@}{@}]
foo
bar
@\label{lst:Li11}@In_x = X_num - 1;
baz
\end{lstlisting}

As you can see in listing \ref{lst:A.1} line number \ref{lst:Li11} ...

As you can see in listing \ref{lst:A.1} line numbers \ref{lst:A.1-1}--\ref{lst:A.1-3} ...
\end{document}


• Thank you very much. – JayDK Nov 6 at 14:30