How to reference line numbers in raw segment using labels?

Hello I have a lot of c header files which I explain in a report written in typst.

Sometimes I do changes to those raw segments and then I need to adjust all my explanation, because lines are not correct anymore.

Is it somehow possible, or planned to use inside of raw segments, so that I can reference the labels and get the line this way?

I know that the pinit package uses show rules to work around thisissue with raw. Perhaps that could work for you too?

Update: This is the closest I’ve gotten so far. Label doesn’t work to reference if it labels text, so I think a custom kind will be required:

#let label_regex = regex("label_\w+?$")

#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 #hide[#line.number #label(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]
print("Numbers:", nums, "Squares:", squared)label_stuff
```

@stuff

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.

The codly package supports this: codly – Typst Universe

Referencing code blocks

Codly offers a wide range of features for referencing code blocks, lines, highlights, and annotations. This is done using:

  • the line shorthand @<label>:<line>
  • the highlight or annotation label @<highlight>
2 Likes