41

How can I place a 'label' marker inside a lstlisting environment (external file imported and formatted via the listinputlisting command) so that I can cross-reference a particular line number?

In other words, I would like to be able to use the following sort of text content in my document.

"By referring to line LINE_NUMBER, in listing ABC, the use of DEF object has resulted in GHI objectives being met" etc...

Where the LINE_NUMBER would be marked in the file to the effect of \label{line:marker} and then used in the document with \ref{line:marker}.

It may require the use of an encapsulating flag/s, such as <\label{line:marker}> to differentiate from surrounding actual code, which is fine with me.

Cheers.

1

1 Answer 1

53

You can use escapechar=<char> to use commands.

\documentclass{scrartcl}
\usepackage{listings}

\begin{document}
\begin{lstlisting}[
    language=Java,escapechar=|] %language and your escape char
public class Main {
    public static void main(String [] args) {
        System.out.println("Hello world !");|\label{line:sp}|   %% <--- label here
    }
}
\end{lstlisting}

By referring to line~\ref{line:sp}, in listing ABC, the use of DEF object has resulted in GHI objectives being met" etc...
\end{document}

enter image description here

1
  • 1
    Note that the escape char $ does not work if this is for labels. Aug 2, 2016 at 9:45

You must log in to answer this question.

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