Reference source code line in minted package
Use mathescape
, then put your \label
in math mode in a comment:
\begin{minted}[linenos=true, mathescape]{c++}
i = i + 1 ;
j = j + 1 ; // The important line $\label{myline}$
k = k + 1 ;
\end{minted}
The important line is line \ref{myline}.
@Ant's answer is great, but requires that your \label
go inside a comment that will appear in the rendered code. You can get around this by using escapeinside
instead of mathescape
:
\begin{minted}[linenos=true, escapeinside=!!]{c++}
i = i + 1 ;
j = j + 1 ; !\label{myline}!
k = k + 1 ;
\end{minted}
The important line is line \ref{myline}.
If you are happy to change from minted
to listings
then it is possible as this example shows:
\documentclass{article}
\usepackage{listings}
\lstset{basicstyle=\ttfamily,
escapeinside={(*}{*)},
numbers=left
}
\begin{document}
\begin{lstlisting}
def foo
while do bar(*\label{line}*)
end
\end{lstlisting}
As we can see in line \ref{line}
\end{document}
Unfortunately, this means a lot more work to get nice colourful syntax highlighting. escapeinside
defines a way to escape the verbatim environment and have what's inside the (*
and *)
actually read by TeX...