Skip to content

Instantly share code, notes, and snippets.

@PgBiel
Last active October 28, 2024 14:40
Show Gist options
  • Save PgBiel/23a116de4a235ad4cf6c7a05d6648ca9 to your computer and use it in GitHub Desktop.
Save PgBiel/23a116de4a235ad4cf6c7a05d6648ca9 to your computer and use it in GitHub Desktop.
Referencing enum items in Typst 0.8.0
// MIT No Attribution
//
// Copyright (c) 2023 Pg Biel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify,
// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#show enum.item: it => {
let body = it.body
let number = it.number
let generate-item(base-label) = {
[#it #base-label]
}
if body.has("label") {
generate-item(body.label)
} else if body.has("children") {
let penultimate-child = body.children.at(calc.max(0, body.children.len() - 2))
let last-child = body.children.last()
if last-child.has("label") {
generate-item(last-child.label)
} else if penultimate-child.has("label") {
generate-item(penultimate-child.label)
} else {
it
}
} else {
it
}
}
#show ref: it => {
if it.element == none {
locate(loc => {
let matches = query(it.target, loc)
let found = false
for match in matches {
if match.func() == enum.item {
found = true
let supplement = if it.has("supplement") { it.supplement } else [Item]
if supplement in (none, []) [#match.number] else [#supplement #match.number]
}
}
if not found { it }
})
} else {
it
}
}
1. amongus <label>
2. amongus
3. trimongus <labelled>
@label // Item 1
@labelled // Item 3
@labelled[Banana] // Banana 3
Ball @labelled[] // Ball 3
a@labelled[]b // a3b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment