[Tex/LaTex] Minted cross reference line


I used to use listings a lot but minted+pygmentize has outstanding output. However, there are a few features from listings that are hard to find in minted, like having the line numbers on the right.

Is there a way to cross reference lines in a minted environment as in listings?

Best Answer

I know this is an "ancient" question but I would like to answer it to help those who get here like me. :)

minted nows provides a macro called escapeinside (also texcl and texcomments for LaTeX in comments, please check the document for more):

escapeinside (string) (default: ⟨none ⟩)

Escape to LaTeX between the two characters specified in (string). All code between the two characters will be interpreted as LaTeX and typeset accordingly. This allows for additional formatting. The escape characters need not be identical. Special LaTeX characters must be escaped when they are used as the escape characters (for example, escapeinside=\#\%). Requires Pygments 2.0+.

Escaping does not work inside strings and comments (for comments, there is texcomments)....

An example given in the document is:

def f(x):
    y = x|\colorbox{green}{**}|2
return y

I've tried that. We can also use \label{refname} to create a line reference using esacpeinside like this:


void hello() |\label{line:hello_start}|
    printf("Hello minted!\n");
} |\label{line:hello_end}|
int main()
    hello(); |\label{line:invoke}|
    return 0;
The code at Line~\ref{line:invoke} invokes a function defined
between Line~\ref{line:hello_start} and Line~\ref{line:hello_end}.

The example on Overleaf.

Hope this helps. :)

Related Question