Skip to content

Make enum items referencable #779

Open

Description

@reknih

Why can't you reference an item in an enumeration? I would assume you can access it as "Item X" or something similar

From web app user feedback

Activity

  1. added
    feature request
    on Apr 13, 2023
  2. Wsine commented on Nov 22, 2023

    @Wsine

    I do favor this feature.

    I want to write a research statement with a bibliography in a single .typ document.

  3. added
    model
    and removed on Nov 24, 2023
  4. caemor commented on Nov 29, 2023

    @caemor
  5. Y-jiji commented on May 2, 2024

    @Y-jiji

    Just add a dummy figure before the labeled item, and use a place command and remove its presence in layout.

    #let fake-label(name) = place[#figure(supplement: meta)[]#label(name)]
  6. Wsine commented on May 7, 2024

    @Wsine

    Just add a dummy figure before the labeled item, and use a place command and remove its presence in layout.

    #let fake-label(name) = place[#figure(supplement: meta)[]#label(name)]

    I tested the usage. This amended works.

    #let fake_label(name) = place[#figure(supplement: [])[]#label(name)]

    Be aware to add #fake_label("your_label") to every enum item. Otherwise, the indexes are wrong.

  7. robamler commented on Nov 3, 2024

    @robamler

    I couldn't get the trick with the invisible figure to work on typst 0.12.0 but, FWIW, here's a workaround I came up with. Unfortunately, it only works with explicitly numbered enums, and you have to explicitly provide the numbering scheme in each reference if it isn't "1" (it's also generally a bit wonky).

    #show ref: it => {
      let el = it.element
      if el != none and el.func() == enum.item {
        // Reference to an enum.item. Currently only works for _explicitly_ numbered enums; also, the
        // label must be immediately after the enum.item, but _not_ part of it (i.e., not indented).
    
        let sup = it.supplement;
        let (text, style) = if sup == auto {
          // Default reference text and style.
          ([Item~], "1")
        } else if sup.func() == text {
          // The author provided a replacement for "Item"
          ([#sup.text~], "1")
        } else {
          // The author provided a replacement for "Item" and a numbering scheme.
          (sup.children.slice(0, -1).join(), sup.children.at(-1).text)
        }
    
        link(el.location(), [#text#numbering(style, el.number)])
      } else {
        // Other references as usual.
        it
      }
    }
    
    1. first item
    <first>
    2. second item with a default reference to @first
    <second>
    3. third item with a named reference to @second[Case]
    <third>
    
    Reference to @third[Item~(a)] with custom numbering.
    
    Reference to @third[ (i)] with custom numbering and no leading text.

    image

  8. GunnarFarneback commented on Jan 16, 2025

    @GunnarFarneback

    Here is a different workaround for typst 0.12, which doesn't require explicitly numbered enums and abuses the fact that you can't otherwise make a reference to text. Support for supplements and different numbering schemes is left out.

    #let enum_numbering = (..it) => {
      counter("enum").update(it.pos())
      numbering("1.1.", ..it)
    }
    
    #set enum(numbering: enum_numbering, full: true)
    
    #show ref: it => {
      let el = it.element
      if el != none and el.func() == text {
        // Override enum references.
        link(el.location(), context numbering("1.1", ..counter("enum").at(el.location())))
      } else {
        // Other references as usual.
        it
      }
    }
    
    + First <item1>
    + Second <item2>
      + Third <item3>
    5. Fourth <item4>
    
    Items @item1, @item2, @item3, and @item4.
    

    enum_ref

  9. MiledMFN commented on Feb 4, 2025

    @MiledMFN

    I couldn’t get the actual label from the code of @GunnarFarneback. My code of labeling is this:

    #set heading(numbering: "I.1")
    #set heading(numbering: (..nums) => {
    if nums.pos().len() == 1 {
    "I" // For level 1
    } else {
    str(nums.pos().last()) // For level 2, show only the second number
    }
    })
    #let current-section() = {
    context counter(heading).display()
    }
    #set enum(numbering: n => {
    current-section() + numbering("a", n) + "."
    })

    Help please. Thank you for the previous answers.

  10. BarakKatzir commented on Mar 5, 2025

    @BarakKatzir

    I'm elaborated on @GunnarFarneback 's solution. Added support for custom enum item numbering, custom support, and made it work when the item includes more than text.

    Here is the code, with output (typst 0.13.0) if you want to use it copy up-to the demonstration part:

    /// Metadata marker for enum items labels,
    /// used to allow reference with the `enum-label` function
    #let enu-label-mark = metadata("enumeration_label")
    
    /// Add a label to an enumeration item.
    ///
    /// Used as:
    /// ```typ
    /// + #enum-label("first")first
    /// + second
    ///   + third #enum-label[third]
    ///
    /// I can ref @first and @third[It.]
    /// // I can ref Item~1 and It.~3
    /// ```
    ///
    /// The label can be used anywhere in the enumeration item.
    /// Calling enum-label works with str or text content.
    #let enum-label(label) = {
      if type(label) == content {
        // informative error message
        assert(label.has("text"), message: "enum-label requires text content")
        label = label.text
      }
      [#enu-label-mark#std.label(label)]
    }
    
    /// Counter name for tracking of enumeration items
    #let enum-counter-name = "enum-counter"
    /// State for tracking the numbering format of enumeration items
    #let enum-numbering-state = state("enum-numbering", none)
    
    /// Wrapper for enum numbering to allow for a references to enum items.
    /// The desired numbering format is passed as an argument (str or function)
    /// To reference an item use `enum-label` function.
    ///
    /// ```typ
    ///
    /// #set enum(numbering: wrapped-enum-numbering("1.1"), full: true)
    /// + #enum-label("one")first
    /// #set enum(numbering: wrapped-enum-numbering("I.1"), start: 2)
    /// + second
    ///   + third #enum-label[another]
    ///
    // One is @one[] and another is @another[] // One is 1 and another is II.2
    /// ```
    #let wrapped-enum-numbering(numbering) = {
      let enum-numbering = (..it,) => {
        enum-numbering-state.update(x => numbering)
        counter(enum-counter-name).update(it.pos())
        std.numbering(numbering, ..it)
      }
      enum-numbering
    }
    
    
    /// Copy from tools4typst
    /// return true if value is an empty array, dictionary, string or content
    #let is-empty(value) = {
      let empty-values = (
        array: (),
        dictionary: (:),
        str: "",
        content: [],
      )
      let t = repr(type(value))
      if t in empty-values {
        return value == empty-values.at(t)
      } else {
        return value == none
      }
    }
    
    
    #show ref: it => {
      let el = it.element
      if el != none and el.func() == metadata and el == enu-label-mark {
        let supp = it.supplement
        if supp == auto {
          supp = "Item"
        }
        // get the counter value in the correct format according to location
        let loc = el.location()
        let ref-counter = context numbering(state("enum-numbering").at(loc), ..counter(enum-counter-name).at(loc))
        if is-empty(supp) {
          link(el.location(), ref-counter)
        }
        else {
          link(el.location(), box([#supp~#ref-counter]))
        }
      } else {
        it
      }
    }
    
    /// Demonstration starts here
    
    #set enum(numbering: wrapped-enum-numbering("(E1)"), full: true)
    
    Group axioms:
    + #enum-label("ax:ass")Associativity
    + #enum-label("ax:id")Existence of identity element
    + #enum-label("ax:inv")Existence of inverse element
    
    
    #set enum(numbering: wrapped-enum-numbering("1.a"), full: true)
    #set math.equation(numbering: "(1.1)")
    Another important list:
    + Newton's laws of motion are three physical laws that relate the motion of an object to the forces acting on it.
      + A body remains at rest, or in motion at a constant speed in a straight line, unless it is acted upon by a force.
      + The net force on a body is equal to the body's acceleration multiplied by its mass
      + #enum-label[newton-third]If two bodies exert forces on each other, these forces have the same magnitude but opposite directions
    + #enum-label[hook1] Another important force is hooks law:
      $ arrow(F) = -k arrow(Delta x) $ <eq:hook> #enum-label[hook2]
    
    
    We covered the three group axioms @ax:ass[], @ax:id[] and @ax:inv[].
    
    It is important to remember Newton's third law @newton-third, and Hook's law @hook1. In @hook2 we gave Hook's law in @eq:hook.

    Image

    Notice that both enum-label-s "hook1" and "hook2" produce good refs (unlike usual labels where only the last works).
    Also, notice that I used enum-label("ax:id") and not enum-label[ax:id]. Ideally the second would work but I couldn't think of a simple way to convert the content to string.

  11. gkb commented on Sep 29, 2025

    @gkb

    I'd like this feature as well. It took me a good deal of searching to convince myself that Typst doesn't have the feature currently. Naively, as a LaTeX user, I took it for granted that Typst supported labels to enum items.

  12. DegrangeM commented on Oct 14, 2025

    @DegrangeM

    With #6619 enum can now be used with query. Couldn't this be used to make reference enum item ?

  13. patrick-kidger commented on Oct 15, 2025

    @patrick-kidger

    I find myself wanting to attach a supplement to my enum references, e.g. 'step 1', 'step 2' / 'goal 1', 'goal 2'. To that end I've written a snippet that supports this like so

    #show: enable-referable-enums
    #set enum(numbering: "a.", full: true)
    
    #referable-enum("step")[
    + foo
    + bar <baz>
    ]
    
    @baz  // Renders as 'step b'

    implementation here:

    Click to expand
    #let _state-referable-enum = state("--state-referable-enum", none)
    #let _counter-referable-enum = counter("--counter-referable-enum")
    // Both arguments assumed to be strings.
    #let _get-greatest-suffix(sample1, sample2) = {
        let suffix = ("",)
        for (c1, c2) in sample1.rev().split("").zip(sample2.rev().split("")) {
            if c1 == c2 {
                suffix.push(c1)
            } else {
                break
            }
        }
        suffix.rev().join("")
    }
    #let _remove-suffix(x, suffix) = {
        assert(x.ends-with(suffix))
        x.slice(0, x.len() - suffix.len())
    }
    
    /// *Example:*
    ///
    /// ```typst
    /// #show: enable-referable-enums
    /// #set enum(numbering: "a.", full: true)
    /// #referable-enum("Step")[
    /// + foo
    /// + bar <baz>
    /// ]
    /// @baz  // Renders as 'Step b'
    /// ```
    ///
    /// - supplement (str): The name to use when referencing this enum, e.g. the 'Step' in 'Step 1'.
    /// - doc (content): Content
    /// -> content
    #let referable-enum(supplement, doc) = context {
        let current-numbering = enum.numbering
        assert(enum.full, message: "Only `enum.full = true` is supported right now. Add `#set enum(full: true)`.")
        let wrap-numbering(..it) = {
            _counter-referable-enum.update(it.pos())
            numbering(current-numbering, ..it)
        }
        set enum(numbering: wrap-numbering)
    
        let sample1 = numbering(current-numbering, 1)
        let sample2 = numbering(current-numbering, 2)
        let suffix = _get-greatest-suffix(sample1, sample2)
    
        _state-referable-enum.update((supplement, suffix, current-numbering))
        doc
    }
    
    
    /// Referable enums.
    /// Use as e.g. `#show: enable-referable-enums`
    #let enable-referable-enums(doc) = {
        show ref: it => {
            let el = it.element
            let loc = el.location()
            if el != none and el.func() == text and _state-referable-enum.at(loc) != none {
                let (supplement, suffix, current-numbering) = _state-referable-enum.at(loc)
                let numbers = numbering(current-numbering, .._counter-referable-enum.at(loc))
                // Override enum references.
                link(loc, supplement + " " + _remove-suffix(numbers, suffix))
            } else {
                // Other references as usual.
                it
            }
        }
        doc
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature requestmodel

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions