Repository navigation
Description
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:
- https://typst.app/universe/package/pariman calculations with units, using a
quantityfunction - https://typst.app/universe/package/unify
- https://typst.app/universe/package/zero
- https://typst.app/universe/package/metro
- https://typst.app/universe/package/nomos
- https://typst.app/universe/package/fancy-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 unitsbut 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 timeThe 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/sSpecialized 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
dfor day,hfor hour,mfor minute,sfor second
- Example: define
- 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
Lege19 commentedon Jun 28, 2026
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:
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).1.5m/shas 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 thinksshould only mean second when used as a postfix unit. I'm sure there are cases where this would be useful beyond being able to write1.5m/s, but can't they be covered by writing1s?I have some questions:
quantityto be an element? This would currently cause issues with+being used for joining content, but that looks like it might change in the future.bastienvoirin commentedon Jun 29, 2026
I fully agree, it was just a simple example to illustrate all other suggestions but anything else would definitely be better:
let m_ = ...(less intuitive for a postfix unit, and I don't like magic identifier syntaxes either)let ?m = ...(would require a change in the compiler to allow?prefixes, and I don't like magic identifier syntaxes either)#unit m = ...or#unit m: ...(orpostfix,define...), the cleanest and most Typst-y way IMOThe
1.5m/sexpressiveness 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/sto be valid, the essence of my proposal is about1.5m/1swith custommandspostfix units)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
quantitywheredimension isLor unit ism(to bikeshed), e.g.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 tostate, that keeps track of all quantities/units of the same dimensionality, but then any user-defined quantity likemy-speedwould be registered and tooltipped. So we'd have to specify which ones to include/exclude viaquantity(..., 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.
It can be useful to have
quantitybe an element, but indeed it could clash with some operations, so I'm not advocating for either. The folding mechanics are quite different betweenquantityand elements.Lege19 commentedon Jul 9, 2026
If this is done, there ought to be a
std.unitsmodule containingquantitydefinitions 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
unitas the keyword could be confusing as it implies a tighter coupling betweenquantitys (such as those defined instd.units) and number suffixes which ideally can be used withoutquantitys.postfixmight 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 bedefine postfixordefine unitor something --- that's just redundant.How about
suffix? IMO better thanpostfixbecause 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
importlist.import module: suffix mseems acceptable, and I feel likeimport module: a few regular imports, suffix *would be appreciated by some users.What if people want
quanitys wheredecimalis the underlying numeric type instead offloat?(I think this is at a level of importance where it should be done iff it can be done cleanly/simply)
quantitys are multiplied/added/whatever, if either has an underlyingdecimalthe result should probably also use adecimaldecimalquantitycould spiral into the whole computation running ondecimals and hence being much slower than if it ran onfloats, it shouldn't be possible to get adecimalquantityby accident.decimalquantityliterals though, so a slightly clunky:0.130981062d * 1mis fine, so we don't need a way to have bothdfor decimal andmfor meter suffixes.If two
quantitys are multiplied/divided and the result is dimensionless, should the result be a dimensionless quantity or should it be afloat/decimal?Principal of least surprise: leave it as a
quantityA proposal
Based on my points around
decimalquantity, 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.
dis 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
quantityto be expressed in user land).laurmaedje commentedon Jul 10, 2026
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.