I was wondering whether or not is possible to make a text (clickable or not) inside lstlisting which redirects to a figure in the document for example. Something like this:

...

\begin{figure}[t]
\includegraphics{myfigure}
\label{figx}
\end{figure}

...

\begin{lstlisting}
# plot figure~\hyperref[figx]{\ref{figx}}
some code
\end{lstlisting}

...


Thanks in advance for sharing any ideas.

You can include more or less any LaTeX macro you want inside your listing by defining a way to escape from verbatim code formatting to usual LaTeX processing. Here is an example using escapeinside to define two sequences of chars that start (/*!) and end (!*/) the escape area. I usually use the usual comment delimiters of the respective language plus some characters I usually don't use in comments, such that the code still looks good in editors without LaTeX parsing (but you can really use any delimiters you like).

Update: You can also use the options escapebegin and escapeend to add some LaTeX macros around the escaped sequence. Suppose you always use the escape in comments and have comments printed in gray, you can pass the escapebegin=\color{gray} option to have the escaped text printed in the same color.

Minimal example:

\documentclass{article}
\usepackage{graphicx}
\usepackage{hyperref}
\usepackage{xcolor}
\usepackage{listings}
\lstset{
language=C++,
escapeinside={/*!}{!*/},
escapebegin=\color{gray},
}

\begin{document}

\begin{figure}[h]
\centering
\includegraphics[width=0.3\textwidth]{example-image-a}
\caption{My figure}
\label{figx}
\end{figure}

\begin{lstlisting}
void test() {
figure->display(); // Output: /*!\ref{figx}!*/
}
\end{lstlisting}

\end{document}


• Thanks @Tiuri, it works pretty well. My smaller problem is that the escaped text is within a comment, which happens to be in gray color (but +1 to your answer). – Toño Feb 6 '18 at 12:40
• @Toño I updated my answer to show how you can include colors (or any other formatting macros) easily to the escape area. – Tiuri Feb 6 '18 at 12:48
• Yeps, I wanted to get that argument in the lstset. Thnx – Toño Feb 6 '18 at 12:51