Here’s a solution. From what the docs say about references, it’s probably the best that can be done at this point in Typst, but I think it works pretty well.
#let label_regex = regex("label_\w+?$")
#let codeline(num, lab) = place(hide[
#counter(figure.where(kind:"codeline")).update(num - 1)
#figure(kind:"codeline", supplement:[line])[]
#label(lab)
])
#show raw.where(block: true): code => {
grid(
columns: (auto, auto),
column-gutter: 1em,
row-gutter: par.leading,
align: (right, raw.align),
..for line in code.lines {
let match = line.text.find(label_regex)
let body = if match != none {
show label_regex: ""
[#line.body #codeline(line.number, match.slice(6))]
} else {
line.body
}
(
text(fill: gray)[#line.number],
body,
)
},
)
}
```python
import random
nums = [random.randint(1, 100) for _ in range(5)]
squared = [n**2 for n in nums]label_squaring_numbers
print("Numbers:", nums, "Squares:", squared)label_printing
```
In @squaring_numbers, you see that I squared some numbers.
In @printing, you see I printed the results.