Skip to content

Add quantity type and register custom postfix constructors in user space #8585

Open

Description

@bastienvoirin

Description

Note: this feature request clashes with #8093 and #8288. It builds upon and replaces #8093 (comment). See also #8093 (comment).

The current postfix length constructors, in particular the absolute ones (pt, mm, cm, in), as well as the angle constructors deg and rad, provide a particularly intuitive, useful, and elegant interface to real-world quantities. I would like to generalize them using user-space definitions of quantities/units/multipliers and the corresponding postfix constructors (see Use Case section below).

Typst Universe packages dealing with units:

Quantities/units/multipliers

Hereafter, a quantity would be a new type with a numeric value and an associative map of dimensions:

type quantity {
  value: number
  dimensions: dictionary(str, number)
}

This quantity type can represent both concrete quantities, like

#let one-mmol = quantity(6.02214076e20) // 1 mmol in elementary entities (e.g. atoms)
#let c = quantity(299792458, L: 1, T: -1) // Speed of light in a vacuum, assuming SI units

but also abstract dimensions or concrete units by simply setting the base value to, say, 1:

#let miles-per-hour = quantity(1, L: 1, T: -1) // *Assuming miles and hours as base units*
#let acceleration = quantity(1, L: 1, T: -2) // Length per unit time per unit time

The representation of such quantities would be, for example,

#{
  repr(acceleration) == "1L/T²"
}

and we could specify the base units as the dimensions themselves for clarity, e.g.

#{
  let meter-per-second = quantity(1, m: 1, s: -1)
  repr(meter-per-second) == "1m/s"
}

The real power of such quantity instances would be the folding of arithmetic operations, e.g.

#{
  // Add values iff dimensions match, otherwise panic
  2h + 3600s == quantity(10800, T: 1)

  // Subtract values iff dimensions match, otherwise panic
  2h - 3600s == quantity(3600, T: 1)

  // Multiply values, fold matching dimensions by adding their values
  3m * 4m == quantity(12, L: 2)

  // Divide values, fold matching dimensions by subtracting their values
  72km / 1h == quantity(20, L: 1, T: -1)
}

In particular, we could mix-and-match quantities and numbers with the following equivalence:

number <=> quantity(number)

E.g. for operations between a number and a quantity:

#{
  // Add values iff quantity has no dimensions, otherwise panic
  2 + 3600s // Panics

  // Subtract values iff quantity has no dimensions, otherwise panic
  2 - 3600s // Panics

  // Multiply values, clone dimensions of the quantity
  3 * 4m == quantity(12, L: 1)

  // Divide values, negate dimensions of the quantity
  72 / 1h == quantity(3600/72, T: -1)
}
Example implementation
#let _add_((val1, dim1), (val2, dim2)) = {
  if dim1 != dim2 {
    dim1 = dim1.pairs().fold("", (acc, (dim, pow)) => acc + str(dim) + super(str(pow)))
    dim2 = dim2.pairs().fold("", (acc, (dim, pow)) => acc + str(dim) + super(str(pow)))
    panic("Cannot add quantities with dimensions " + dim1 + " and " + dim2)
  }
  (val1 + val2, dim1)
}
#let _sub_((val1, dim1), (val2, dim2)) = {
  if dim1 != dim2 {
    dim1 = dim1.pairs().fold("", (acc, (dim, pow)) => acc + str(dim) + super(str(pow)))
    dim2 = dim2.pairs().fold("", (acc, (dim, pow)) => acc + str(dim) + super(str(pow)))
    panic("Cannot subtract quantities with dimensions " + dim1 + " and " + dim2)
  }
  (val1 - val2, dim1)
}
#let _mul_((val1, dim1), (val2, dim2)) = {
  // Copy dim1 and dim2, reduce common keys with a sum
  let dims = dim1
  for (dim, pow) in dim2.pairs() {
    dims.insert(dim, dims.at(dim, default: 0) + pow)
  }
  let dims = dim1.pairs().filter(((dim, pow)) => pow != 0).to-dict()

  if dims == (:) {
    val1 * val2
  } else {
    (val1 * val2, dims)
  }
}
#let _div_((val1, dim1), (val2, dim2)) = {
  // Copy dim1 and dim2, reduce common keys with a difference
  for (dim, pow) in dim2.pairs() {
    dim1.insert(dim, dim1.at(dim, default: 0) - pow)
  }
  let dims = dim1.pairs().filter(((dim, pow)) => pow != 0).to-dict()

  if dims == (:) {
    val1 / val2
  } else {
    (val1 / val2, dims)
  }
}

The user would be responsible for dealing with the same units/dimension names for the same dimensions, e.g.

#{
  let meter-per-second = quantity(1, m: 1: s: -1)
  let kilometer-per-hour = quantity(1, km: 1, h: -1)
  meter-per-second / kilometer-per-hour == quantity(1, m: 1, s: -1, km: -1, h: 1) // Bruh
  meter-per-second + kilometer-per-hour // Panics

  let meter-per-second = quantity(1, m: 1: s: -1)
  let kilometer-per-hour = quantity(1000/3600, m: 1, s: -1)
  meter-per-second / kilometer-per-hour == quantity(3.6) // Yay!
  meter-per-second + kilometer-per-hour == quantity(4600/3600, m: 1, s: -1) // Yay!
}

Postfix constructors

Now let's imagine a syntax sugar to define user-space postfix constructors for quantities: prefixing a quantity with a "placeholder" underscore allows it to serve as a number postfix (this particular syntax sugar is orthogonal to this proposal and subject to bikeshedding).

Generic proposal (string to type)

The most generic postfix constructor takes a string representation and returns anything you want (decimal number, duration, etc; see below):

#let _postfix = str => result
#let my-variable = 27postfix
#let my-variable = _postfix("27")

Example: decimal numbers (see #8093):

#let _d = decimal
#let almost-one = 0.99999999999999999999d
#let almost-one = decimal("0.99999999999999999999")

Example: duration

#let _d = days => duration(days: int(days))
#let one-day = 1d
#let one-day = duration(days: 1)

Example: quantity

// Without syntax sugar, already nice
#let s = quantity(1, T: 1)
#let m = quantity(1, L: 1)
#let walking = 1.5*m/s
// With syntax sugar, matching the power of the length postfix constructors `pt`, `cm`...
#let s = quantity(1, T: 1)
#let m = quantity(1, L: 1)
#let _s = s => quantity(float(s), T: 1) // Postfix constructor
#let _m = m => quantity(float(m), L: 1) // Postfix constructor
#let walking = 1.5m/s

Specialized proposal (implied product with a quantity)

Less useful (no decimal/duration possible) but way cleaner with respect to quantities, is to define postfix constructors as implied products with a corresponding quantity:

#let _s = quantity(1, T: 1) // Postfix constructor
#let _m = quantity(1, L: 1) // Postfix constructor
#let walking = 1.5m/_s // Notice the ugly underscore...
#let s = quantity(1, T: 1) // Quantity
#let _s = s // Postfix constructor (notice the ugly redundancy `_s = s`...)
#let _m = quantity(1, L: 1) // Postfix constructor
#let walking = 1.5m/s
  • Aside: composability example (bits, bytes, and multiples)

    #let _b = quantity(1)
    #let _B = quantity(8)
    #let one-byte = 8b
    #let one-byte = 8*b
    #let one-byte = 1*B
    #let one-byte = 1B
    
    #let _k = quantity(1000)
    #let _Ki = quantity(1024)
    #let _M = _k*_k
    #let _Mi = _Ki*_Ki
    #let _G = _k*_k*_k
    #let _Gi = _Ki*_Ki*_Ki
    #let values-two-bytes = 64Ki
    #let values-three-bytes = 16Mi
    #let values-four-bytes = 4Gi
    
    #let _GiB = _Gi*_B
    #let thumbdrive = 32GiB

If we allow any variable to define a postfix constructor, with no "placeholder" underscore required, this would even boil down to

#let s = quantity(1, T: 1) // Quantity _and_ postfix constructor
#let m = quantity(1, L: 1) // Quantity _and_ postfix constructor
#let walking = 1.5m/s // How elegant!

P.S.: I admit this proposal is really two proposals, 1) a quantity type and constructor 2) a mean to define new postfix constructors for quantities; the latter being dependent on the former. Please let me know if I should split this feature request this way.

Use Case

  • Much more expressive/elegant (and typed!) use of Typst's scripting for lightweight STEM calculations and tables/plots, basically a DSL
    • Example: define d for day, h for hour, m for minute, s for second
  • Make 2D/3D drawings with custom units easier (e.g. panels/face plates, mechanical parts footprints, schematics...)
    • Personal use case: Eurorack modules: define 1U as 1.75in, 1HP as 0.2in
    • Personal use case: printed circuit boards: define 1mil as 0.001in
    • Personal use case: Ph.D. thesis in particle physics

Activity

  1. added
    feature request
    on Jun 28, 2026
  2. Lege19 commented on Jun 28, 2026

    @Lege19
    Contributor

    While it might have been better to have two issues for postfix constructors and quantity type I think it's fine to keep discussion in 1 now that it exists. The important thing is that the topic of the issue matches the issue title so it can be found easily.


    I have some concerns with this as proposed:

    • The let _m = ... syntax is definitely not the way to go. Since Typst lacks a way to make some bindings in a module private plenty of packages prefix private names with an _ like you would in Python (some use a double underscore, this would still clash).
    • Your suggestion of being able to write 1.5m/s has issues. Won't doing it that way lead to loads of single or double letter bindings in your global scope? Sounds like namespace pollution, I think s should only mean second when used as a postfix unit. I'm sure there are cases where this would be useful beyond being able to write 1.5m/s, but can't they be covered by writing 1s?

    I have some questions:

    • Would you want your user-defined length units to be usable as Typst lengths?
    • Would you want quantity to be an element? This would currently cause issues with + being used for joining content, but that looks like it might change in the future.
  3. added
    syntax
    foundations
    scripting
    on Jun 29, 2026
  4. bastienvoirin commented on Jun 29, 2026

    @bastienvoirin
    SponsorContributorAuthor

    The let _m = ... syntax is definitely not the way to go. Since Typst lacks a way to make some bindings in a module private plenty of packages prefix private names with an _ like you would in Python (some use a double underscore, this would still clash).

    I fully agree, it was just a simple example to illustrate all other suggestions but anything else would definitely be better:

    • Another position like let m_ = ... (less intuitive for a postfix unit, and I don't like magic identifier syntaxes either)
    • Another symbol like let ?m = ... (would require a change in the compiler to allow ? prefixes, and I don't like magic identifier syntaxes either)
    • A new language keyword/statement like #unit m = ... or #unit m: ... (or postfix, define...), the cleanest and most Typst-y way IMO

    Your suggestion of being able to write 1.5m/s has issues. Won't doing it that way lead to loads of single or double letter bindings in your global scope? Sounds like namespace pollution, I think s should only mean second when used as a postfix unit. I'm sure there are cases where this would be useful beyond being able to write 1.5m/s, but can't they be covered by writing 1s?

    The 1.5m/s expressiveness by unifying the notions of quantities and postfix units is mostly an intuitiveness/discoverability bonus, but I share your concerns for namespace pollution.


    In summary, I feel like your concerns are essentially about 1) the undecided syntax 2) the most extreme "takes" of my proposal (we don't need 1.5m/s to be valid, the essence of my proposal is about 1.5m/1s with custom m and s postfix units)


    Would you want your user-defined length units to be usable as Typst lengths?

    It's not mandatory for this proposal to be useful, but ideally I would. We could redefine the built-in Typst lengths as a subtype of quantity where dimension is L or unit is m (to bikeshed), e.g.

    // Built-in
    #let _mm = quantity(0.001, m: 1)
    #let _cm = quantity(0.01, m: 1)
    #let _in = quantity(0.0254, m: 1)
    ...
    // Built-in
    
    // User-space
    #let _U = 1.75in
    #let _HP = 0.2in
    // User-space

    But in a way that keeps the useful 1in = 2.54cm = 25.4mm = ... on-hover tooltips. This could be done via a kind of equivalence "register", akin to state, that keeps track of all quantities/units of the same dimensionality, but then any user-defined quantity like my-speed would be registered and tooltipped. So we'd have to specify which ones to include/exclude via quantity(..., is-base: true) or another mechanism.

    If this proves to be too tricky to implement, I'd be perfectly fine with keeping user-defined lengths and Typst length separate.

    Would you want quantity to be an element? This would currently cause issues with + being used for joining content, but that looks like it might change in the future.

    It can be useful to have quantity be an element, but indeed it could clash with some operations, so I'm not advocating for either. The folding mechanics are quite different between quantity and elements.

  5. Lege19 commented on Jul 9, 2026

    @Lege19
    Contributor
    • If this is done, there ought to be a std.units module containing quantity definitions for SI units (as base units) and common US Customary and Imperial units defined in terms of the SI units.

      I'm a little concerned that using unit as the keyword could be confusing as it implies a tighter coupling between quantitys (such as those defined in std.units) and number suffixes which ideally can be used without quantitys.

    • postfix might also be confusing as people may be expecting general postfix operators (1 + 1)m, which (so far) isn't being suggested and would cause a lot of problems even if technically possible.

    • Definitely not define, I assume it would be define postfix or define unit or something --- that's just redundant.

    • How about suffix? IMO better than postfix because it doesn't sound like an operator --- it sounds like it will be part of the number literal. This is my favorite so far.

    • Suffix syntaxes should be scoped and importable, this implies there will need to be a way to refer to one in the import list. import module: suffix m seems acceptable, and I feel like import module: a few regular imports, suffix * would be appreciated by some users.

    • What if people want quanitys where decimal is the underlying numeric type instead of float?

      (I think this is at a level of importance where it should be done iff it can be done cleanly/simply)

      • Supposing this is done, when two quantitys are multiplied/added/whatever, if either has an underlying decimal the result should probably also use a decimal
      • Since the presence of a single decimal quantity could spiral into the whole computation running on decimals and hence being much slower than if it ran on floats, it shouldn't be possible to get a decimal quantity by accident.
      • Users won't need to write many decimal quantity literals though, so a slightly clunky: 0.130981062d * 1m is fine, so we don't need a way to have both d for decimal and m for meter suffixes.
    • If two quantitys are multiplied/divided and the result is dimensionless, should the result be a dimensionless quantity or should it be a float/decimal?
      Principal of least surprise: leave it as a quantity

    A proposal

    Based on my points around decimal quantity, I think I have a conclusion for what the scope of the suffixes side of this feature should be.

    Let's suppose the keyword is suffix, you should be able to define them as:
    suffix m = quantity(m: 1)
    suffix m(x) = x * quantity(m: 1)

    When used, if the suffix is defined to be a quantity, the quantity is multiplied by the dimensionless part as a float.
    If the suffix is instead defined to be a function, the function is called with the dimensionless part as a single argument as a float.

    d is still implemented in the compiler since it's the only time where a string is needed.

    TBH The main reason for passing the argument as a float instead of a string is that it feels cleaner to me. I could argue that doing it that way will discourage weird behaviour. Doing it this way also has the benefit of us getting decimal literals sooner (as otherwise they probably get held up by the other much more controversial features).

    Potential for operator overloading

    Suggestions of operator overloading or complex numbers have been rejected before, but I'd like to point out that number suffixes + custom types + operator overloading would cover a very wide range of use cases (including allowing quantity to be expressed in user land).

  6. laurmaedje commented on Jul 10, 2026

    @laurmaedje
    Member

    I am not convinced that custom suffixes pull their weight in terms of syntax and learnability. Features like this add up in terms of making a language easy to grasp and it's in my opinion too far removed for the problem domain of typesetting to support this kind of stuff at the syntactical level.

    Without the syntax, I would then think that a quantity type like proposed here is is also better left in user space, though I understand that, without operator overloading, it can't feel quite as native if it's in a package.

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 requestfoundationsscriptingsyntax

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions