1

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?

  • minted uses fancyvrb, so the documentation of fancyvrb will help you.+ – Marco Daniel Mar 4 '13 at 19:24
  • 3
    You can use texcl=true to allow LaTeX in comments, and then put a \label in a comment and \ref that. Unfortunately, Pygments doesn't allow LaTeX anywhere except for comments (though that feature has been requested). So Pygments is a bit more limited than listings in that respect. (You could always take the direct output of pygmentize and add \label's by hand, but that's probably not what you were looking for.) – G. Poore Mar 4 '13 at 20:05
  • Ok, I added a bogus comment by hand and used the texcl feature. – green diod Mar 4 '13 at 20:40
3

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:

\begin{minted}[escapeinside=||]{py}
def f(x):
    y = x|\colorbox{green}{**}|2
return y
\end{minted}

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

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{minted}

\begin{document}
\begin{minted}[escapeinside=||,linenos,gobble=0]{c}
void hello() |\label{line:hello_start}|
{
    printf("Hello minted!\n");
} |\label{line:hello_end}|
int main()
{
    hello(); |\label{line:invoke}|
    return 0;
}
\end{minted}
The code at Line~\ref{line:invoke} invokes a function defined
between Line~\ref{line:hello_start} and Line~\ref{line:hello_end}.
\end{document}

The example on Overleaf.

Hope this helps. :)

  • Thank you @mkdong for updating this. I now have a lot of stuff with listings but for new projects, I'll think about it. – green diod Jan 14 '17 at 17:48
  • I think this only works when the document is not compiled in draft mode (so do not worry about undefined labels in draft mode). – asante Apr 30 at 20:47

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.