6

How can I use \ref inside lstlisting.

I create two lstlistings, e.g. listing1 and listing2. Now, in the third lstlisting, I want to give a reference to them. But when I do, I do not get the reference of listing1 and listing2.

Here is the code I am using.

\documentclass{article}
\usepackage{listings}

\begin{document}
\begin{lstlisting}
Example 
"Listing 1": \ref={listing1},
"Listing 2": \ref{listing2}
\end{lstlisting}
\end{document}

listing1 and listing2 are the labels I defined in other listings and they work fine when I reference them within the section.

Here is the output I am getting:

enter image description here

1
  • 2
    (1) welcome, (2) as always on this site it is best to post full (but minimal) documents instead of sniplets like this. Full documents makes it easier for others to test. (3) Exactly why are you doing this? Listings has a very specific purpose, it might be that you should use a different solution here. (4) If you insist on using listings here, see the escapeinside option in the listings manual.
    – daleif
    Commented Mar 14, 2019 at 9:38

1 Answer 1

7

you can define an escapechar (in my example it's %). Everything between two of these chars whill be interpreted as LaTeX code:

\documentclass{article}
\usepackage{listings}

\begin{document}
\begin{lstlisting}[escapechar=\%]
Example 
"Listing 1": %\label{listing1}%
"Listing 2": %\label{listing2}%
\end{lstlisting}
\end{document}

output

3
  • 1
    I'm glad it helped @YasirSaleem! Please make sure to upvote and mark the answer as accepted if it works for you :) Commented Mar 14, 2019 at 9:55
  • 2
    I have marked the answer as accepted. But unfortunately, upvote does not work for me because of low reputation. Commented Mar 14, 2019 at 9:55
  • 1
    Oh don't worry about the upvote, but it is important to mark the answer that best works for you as accepted so others see that the question received a functioning reply. Commented Mar 14, 2019 at 9:57

You must log in to answer this question.

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