1

Can I refer to a line number from the imported file without escaping chars inside the file?

Say, I import my file like this

\lstinputlisting[language=c]{main.c}

and I want to \hyperref{} line 50 without modifying it or copying to my .tex file.

  • 1
    Welcome to TeX.SX! I'm not sure that I understand. The whole point of using \ref{...} is to be able to dynamically refer to other parts of the document. From want you have said you simply want to refer to line 50 so why not write by line 50...? – Andrew Aug 15 '15 at 4:49
  • @Andrew yeah, you are correct. What I actually want though is to hyperref this part of the document. Sorry for not asking this straight away. – orestisf Aug 15 '15 at 9:28
3

The following example sets a label for the listings by option label. The anchor name of the label is extracted and analyzed to get the internal listings number. In this case the unnumbered listings has anchor lstlisting.-1 with the number -1 for the listings. The anchor names for the line numbers follow the pattern lstnumber.<listings number>.<line number>. Macro \lstlinelink references the line, given the label for the listings and the line number. Two LaTeX runs are necessary because of the label.

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[variablett]{lmodern}
\usepackage{listings}
\usepackage[colorlinks]{hyperref}
\usepackage{refcount}[2006/02/20]

\makeatletter
\newcommand*{\lstlinelink}[2]{%
  \refused{#1}%
  \edef\lstlinelink@tmp{\getrefbykeydefault{#1}{anchor}{}}%
  \ifx\lstlinelink@tmp\@empty
    #2%
  \else
    \edef\lstlinelink@target{%
      \expandafter\lstlinelink@parse\lstlinelink@tmp\@nil
      #2%
    }%
    \hyperlink{\lstlinelink@target}{#2}%
  \fi
}
\def\lstlinelink@parse#1.#2\@nil{lstnumber.#2.}%
\makeatother

\begin{document}
\noindent
Line~\lstlinelink{foo}{5} loads package \texttt{hyperref}
and the document starts at line~\lstlinelink{foo}{25}.
\lstinputlisting[
  language={[LaTeX]TeX},
  label=foo,
  numbers=left,
  columns=fullflexible,
  basicstyle=\ttfamily\small,
]{\jobname}
\end{document}

Result

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.