Highlight the last element of a numbered list in Typst

29 Views Asked by At

I would like to display a numbered list, with all items in gray expect the last one.

In brief, below the desired output:

+ #text(gray)[First]
+ #text(gray)[Second]
+ #text(black)[Last]

enter image description here

Is there a way to modify the #enum function do this programmatically in typst?

1

There are 1 best solutions below

0
ntjess On BEST ANSWER

Enums are a bit tricky, since typst does not number them and complains when you try to associate them with a counter (see https://github.com/typst/typst/issues/325)

However, if you only have very simple cases like the one you printed (no nested enums, funky spacing, non-text content, etc.), you can use something like this:

#let cur-item = counter("cur-item")
#show enum: it => {
  cur-item.update(0)
  let n-children = it.children.len()
  let block = block
  if it.tight {
    block = block.with(spacing: 0.65em)
  }
  
  for (idx, child) in it.children.enumerate() {
    cur-item.step()
    block(pad(left: it.indent)[
      #stack(dir: ltr, spacing: it.body-indent)[
        #cur-item.display(it.numbering)
      ][
        #let txt-color = if idx == n-children - 1 { black } else { gray }
        #set text(txt-color) 
        #child.body
      ]
    ])
  }
}

+ First
+ Second

+ Last

Now try a tight list

+ Another first
+ Second
+ Last

enter image description here