[Tex/LaTex] Inline links in code listings

hyperreflistingsverbatim

I would like to include links inside source code listings by providing URLs within the listing source text.

That is, I would like to be able to generate something that looks like the following:

enter image description here

with source code something like the following:

\begin{lstlisting}
int main(){
int x;
\href{http://foo.com/MyFunctionDocs.html}{MyFunction}(x);
}
\end{lstlisting}

The pink text is a hyperlink to an arbitrary URL. This would ideally be compatible with the listings package, but any well-supported verbatim-style environment would be acceptable. How can I accomplish this?

Best Answer

The simplest method I can think of is to just use listings's escapechar key. This requires choosing a character that doesn't appear in the code. For example, I've used the pipe character | below, but this would need to be changed to something else if the code fragment contained, say, a logical or bitwise or operation.

\documentclass{article}

\usepackage{listings}
\usepackage[colorlinks]{hyperref}

\begin{document}

\begin{lstlisting}[language=C,escapechar=|]
int main(){
int x;
|\href{http://foo.com/MyFunctionDocs.html}{MyFunction}|(x);
}
\end{lstlisting}

\end{document}

This produces:

image of result

Related Question