TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How do I make references to specific lines in program source code (e.g. Python)? For example, I want to say:

In lines 22-30, the algorithm is implemented...

If I changed the Python source code, "lines 22-30" will automatically change to reflect the new line numbers.

I'm using minted

share|improve this question
minted uses the fancyvrb environment, but doesn't seem to support the commandchars option: this is a problem here :-( Perhaps Konrad can help out, as he actually writes minted. – Joseph Wright Nov 15 '10 at 9:50
Related (for listings): tex.stackexchange.com/questions/2228/… – Charles Stewart Nov 15 '10 at 10:43

I don't use minted, but here's how I would do it for fancyvrb, which minted uses internally. Here, I define new command \VerbLabel{linex}{a $ a} which assigns the label linex to the source code line a $ a.

It's written using expl3, so see the source3 documentation for explanation for any of the commands that don't make sense. In brief: prop in expl3 is a ‘property list’ datatype that holds pair-value data. \prop_gput is the allocator, \prop_if_in tests for the existence of a key, and \prop_get_gdel is an accessor function that also deletes the entry afterwards.


\cs_generate_variant:Nn \prop_gput:Nnn {Nxn}
\cs_generate_variant:Nn \prop_get_gdel:NnN {NxN}
\cs_generate_variant:Nn \prop_if_in:NnT {NxT}

\prop_new:N \g_verb_label_prop
\newcommand \VerbLabel [2] {
  \prop_gput:Nxn \g_verb_label_prop { \tl_to_str:n {#2} } {#1}
\renewcommand \FancyVerbFormatLine [1] {
  \prop_if_in:NxT \g_verb_label_prop { \tl_to_str:n {#1} }
    \prop_get_gdel:NxN \g_verb_label_prop { \tl_to_str:n {#1} } \l_tmpa_tl
    \label {verbline:\l_tmpa_tl}

\VerbLabel{linex}{a $ a}
\VerbLabel{liney}{c & c}

See lines \ref{verbline:linex}--\ref{verbline:liney}

1 _ 1
a $ a
b # b
c & c
9 ^ 9

There is a bug in this code which means it doesn't work for lines that contain the # char, but that's not an unsolvable problem.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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