functions
every function a note can call without an import, and every task attribute. your editor's completion and signature help show the same descriptions as you type. back to the book
built-ins
what a note is written with. the ones marked *prelude* are .xmd functions every note can call by name, below the names it defines itself
coalesce(values: Value...)
returns Value
Return the first non-null value.
coalesce(null, 1)
completed(checklist)
*prelude*
Count completed leaf tasks beneath a named heading, as a Count: completed(trip).
countdown(duration, elapsed?, started?)
*prelude*
An idle countdown. Use Start timer to capture a timestamp; elapsed and started are persisted by timer controls.
date(value: Text, Date, or DateTime)
returns Date or DateTime
Parse ISO or relative date text, or take a timestamp's calendar date in the request timezone.
date("next Friday")
debug(value: Value)
returns Text
Inspect any value as compact JSON text in an inlay. Records, lists, and host objects expose their fields; money, dates, durations, and ratios keep their type and units.
debug({rain: 35%, pack: true})
effort(checklist)
*prelude*
Sum estimates of unfinished leaf tasks beneath a named heading, as a Duration: effort(trip).
forecast(place, date, unit?)
*prelude*
The cached forecast for a place and day, with .high, .low, .summary and .rain. Beyond 16 days, returns a seasonal outlook for up to about 7 months, labeled as an estimate. Seasonal .rain is the fraction of available ensemble runs with more than 0.1 mm of daily precipitation (including snow); it is null with fewer than two valid runs. Itinerary days with a place get one automatically.
forecast_range(place, start, end, unit?)
*prelude*
Cached daily forecasts in chronological order, including both dates. Project .high, .low, or .rain and pass the list to sparkline. One refresh requests the entire interval. Dates beyond 16 days use seasonal estimates; missing days remain lookup warnings until available. Limited to 4096 days.
if(condition: Boolean, then: Value, else: Value)
returns Value
Evaluate only the selected branch; more condition, result pairs may come before the else.
if(n < 0, "negative", n == 0, "zero", "positive")
import(id: Text)
returns Record
Load a module by ID, or a note by path such as import("./values.x.md"); members keep their own source.
import("format")
let(names: Record, body: Value)
returns Value
Name values for the body; each name can use the ones before it.
let({x: 2, y: x * 3}, x + y)
match(value: Value, case: Value, result: Value, otherwise: Value)
returns Value
Pick the result of the first case equal to the value, else the last argument; more case, result pairs may follow the first.
match(state, "open", "○", "done", "✓", "?")
maximize(objective: linear expression)
returns Plan
Declare a linear plan over the | constraint | expression | table below; undefined names become decisions.
maximize(3 * bagels + 1.25 * doughnuts)
minimize(objective: linear expression)
returns Plan
Like maximize, but finds the smallest objective that satisfies every constraint in the table below.
minimize(cost)
now()
returns DateTime
The current timestamp. Sampled once per evaluation; live hints refresh every second.
now()
quote(symbol)
*prelude*
The cached last price for a ticker, e.g. quote(NVDA); non-US tickers need a provider in .xmd/providers.json.
rate(from, to)
*prelude*
The cached exchange rate between two currencies, e.g. rate(EUR, USD). Refresh with xmd refresh or the ⟳ lookups lens; hovers show the age.
remaining(checklist)
*prelude*
Count unfinished leaf tasks beneath a named heading, as a Count: remaining(trip).
solve(constraint: expression with <=, >=, or ==)
returns Number, Money, or Duration
Goal seek: the definition's own name is the unknown, set to the boundary value that makes the constraint hold.
solve(total >= $500)
sparkline(values, min?, max?)
*prelude*
Draw one Unicode bar per numeric value, in list order, as Text. Null leaves a gap (·). The scale uses the data's minimum and maximum unless both bounds are supplied; values outside fixed bounds are clipped. Values and bounds must use matching units. sparkline([12, 18, 9, 24]) is ▂▅▁█.
stopwatch(elapsed?, started?)
*prelude*
An idle stopwatch. Use Start, Pause, Resume, or Reset timer. Elapsed time includes time while the editor is closed.
sum(items: List or Table, expression?: row calculation)
returns Number, Money, Ratio, or Duration
Add compatible quantities from a list, skipping nulls, or a row expression over each table row, keeping units.
sum(groceries, quantity * price)
to(amount, currency)
*prelude*
Convert money with the cached rate, e.g. to(hotel, USD); without one the note warns until xmd refresh.
today()
returns Date
The current local calendar date. Updates at midnight.
today()
total(checklist)
*prelude*
Count all leaf tasks beneath a named heading, as a Count: total(trip).
toolkit
the list and text plumbing a note reaches for once it needs it
concat(lists: List...)
returns List
Concatenate lists.
concat([1, 2], [3])
contains(value: List or Text, part: Value)
returns Boolean
Test membership or a text substring.
contains("hello", "ell")
desc(key: Function)
returns Record
Sort by a key descending, as a sort_by key.
desc(.due)
ends_with(text: Text, suffix: Text)
returns Boolean
Test a text suffix.
ends_with("hello", "lo")
entries(record: Record)
returns List
List key/value pairs in key order.
entries({x: 1})
filter(items: List, predicate: Function)
returns List
Keep items whose predicate returns true.
filter([1, 2], fn(x) => x > 1)
floor(number: Number)
returns Number
Round down to an integer.
floor(1.5)
fold(items: List, initial: Value, function: Function)
returns Value
Combine items left to right with an accumulator.
fold([1, 2], 0, fn(a, x) => a + x)
get(collection: Record or List, key: Text or Number)
returns Value
Read a field or index; return null when absent.
get({name: "hello"}, "name")
group_by(items: List, key: Function)
returns List
Group by a scalar key into {key, rows} records, in first-seen order.
group_by([1, 2, 1], fn(x) => x)
join(items: List, separator: Text)
returns Text
Join a list of text.
join(["a", "b"], "/")
length(value: List, Record, or Text)
returns Count
Count items, fields, or Unicode characters.
length("hello")
lower(text: Text)
returns Text
Convert text to lowercase.
lower("Hello")
map(items: List, function: Function)
returns List
Apply a pure function to every item.
map([1, 2], fn(x) => x * 2)
number(value: Number, Money, Ratio, Duration or Count)
returns Number
Extract the numeric magnitude; durations use seconds.
number(90m)
object(entries: List)
returns Record
Build a record from key/value pairs; duplicate keys are rejected.
object([{key: "x", value: 1}])
pad_end(text: Text, width: Number, fill: Text)
returns Text
Pad text on the right.
pad_end("x", 3, " ")
pad_start(text: Text, width: Number, fill: Text)
returns Text
Pad text to a character width with one character.
pad_start("3", 2, "0")
repeat(text: Text, count: Number)
returns Text
Repeat text a bounded number of times.
repeat("█", 3)
replace(text: Text, from: Text, to: Text)
returns Text
Replace text occurrences.
replace("hello", "h", "j")
round(number: Number)
returns Number
Round to the nearest integer.
round(1.5)
slice(value: Text or List, start: Number, end: Number)
returns Text or List
Take a half-open range; text indices count Unicode characters.
slice("hello", 0, 2)
sort_by(items: List, key: Function, desc(key), or a list of them)
returns List
Stable sort by one key, or by several in order; desc(key) sorts that key descending. Nulls come last either way.
sort_by(tasks, [desc(.due), .title])
source(value: Any)
returns Text
Format a typed scalar as a round-trippable expression.
source(now())
split(text: Text, separator: Text)
returns List
Split text into pieces.
split("a/b", "/")
starts_with(text: Text, prefix: Text)
returns Boolean
Test a text prefix.
starts_with("hello", "he")
text(value: Value)
returns Text
Format a value as text; null remains null.
text($25)
trim(text: Text)
returns Text
Remove surrounding whitespace.
trim(" hello ")
type(value: Any)
returns Text
Get the runtime type name.
type(42)
upper(text: Text)
returns Text
Convert text to uppercase.
upper("Hello")
attributes
written on a line, like - [ ] Pack @due(tomorrow). the bundled module that owns each one declares it: tasks a task's, appointments an appointment's @at
@after(dependency: Boolean or Checklist, more dependencies...)
Block this task until all dependencies are satisfied. Cycles are reported with source locations.
@after(task_name)
@at(time: Date or DateTime)
Appointment time; a line with @at and no checkbox is an appointment. Include an explicit UTC offset for ambiguous local times.
@at(2026-09-18T14:00-04:00)
@completed(date: Date)
The day the task was checked off, as YYYY-MM-DD. Checking a task stamps today's date on it and its subtasks; unchecking removes the stamp. The checkbox, not the stamp, decides whether the task is done.
@completed(2026-09-18)
@due(date: Date or DateTime)
Deadline. Accepts a named date, an expression, or relative input such as tomorrow. Use Freeze relative date to capture it.
@due(tomorrow)
@estimate(effort: Duration)
A nonnegative estimate. Examples: 30s, 20m, 2h.
@estimate(20m)
@every(interval: recurrence)
Repeat a leaf task: day, week, month, year, or a positive whole-day duration such as 2w.
@every(week)
@repeat_from(anchor: Date)
The date a recurring task's @every counts from, as YYYY-MM-DD. Completing the task writes it once, from @due or today, so each later @due stays on the same cycle (a monthly bill anchored on the 31st comes back on the last day of every month) however early or late it is checked off.
@repeat_from(2026-01-31)
@scheduled(date: Date or DateTime)
Planned work date; separate from the deadline.
@scheduled(tomorrow)
@tag(tag: name)
Tag a task for filtering. Multiple tags may be comma-separated.
@tag(errands)
@timer(timer: Timer)
Associate a named timer with this task. Completion does not stop the timer.
@timer(focus)
module built-ins
only .xmd module code can call these
at_time(date: Date, time: Duration, offset: DateTime)
returns DateTime
Combine a date and time of day using the reference timestamp offset.
at_time(today(), 9h, now())
cached(kind: Text, key: List of one-field records, label?: Text)
returns Record or Null
The workspace's cached answer for a lookup as {value, fetched_at, source}, or null before anything has fetched it. Every key read, cached or not, is one xmd refresh and the ⟳ lookups lens fetch, through the provider for its kind; hovers name it by its label and show its age. The key's parts are in the order the cache spells them: [{from: "EUR"}, {to: "USD"}] is rate:EUR:USD.
cached("rate", [{from: "EUR"}, {to: "USD"}], "rate EUR→USD")
clocked(value: Value, ticking: Function)
returns Value
The value, which keeps depending on the clock it read only while ticking(value) is true: once ticking says no, the value no longer moves with the clock it read, so nothing refreshes it.
clocked(state, fn(s) => s.running)
date_parts(date: Date or DateTime)
returns Record
Read year, month, day and weekday (Monday is zero).
date_parts(today())
display_width(text: Text)
returns Count
How many columns text takes in a terminal or a monospace editor: most characters take one, wide ones such as CJK and most emoji take two, and combining marks and zero-width characters none. It aligns text where padding to length would not.
display_width("名前")
duration_parts(duration: Duration)
returns Record
Split integer seconds into total hours, remaining minutes and seconds without rounding.
duration_parts(90m)
end_position(text: Text)
returns Record
Where text ends as an editor counts: {line, character}, its line count and the UTF-16 length of its last line, or the next line's start when it ends in a line break. Where an edit appends to a note.
end_position(ctx.document.text)
error(message: Text)
returns Never
Return an evaluation error.
error("Missing data")
eval(expression: Text)
returns Value
Evaluate expression text in the current document's scope.
eval("price * 2")
format_date(date: Date or DateTime, format: Text)
returns Text
Format a date or timestamp with strftime directives.
format_date(today(), "%Y-%m-%d")
make_date(year: Number, month: Number, day: Number)
returns Date or Null
Construct a calendar date; invalid dates return null.
make_date(2026, 9, 18)
make_money(amount: Number, currency: Text)
returns Money or Null
An amount of money in a currency code, or null when the code is not three uppercase letters.
make_money(12.5, "EUR")
make_ratio(fraction: Number)
returns Ratio
A number as a ratio: 0.4 is 40%.
make_ratio(0.4)
match_pattern(text: Text, pattern: Text)
returns Record or Null
The first match of a regular expression, or null: {text, start, end, groups}, offsets counting Unicode characters as slice does. groups has every named group (?<name>...) as {text, start, end}, or null when it took no part. Matching takes time linear in the text; a pattern is limited to 4096 bytes and compiled once.
match_pattern("Ada: 42", "(?<name>\\w+): (?<n>\\d+)")
merge3(base: Text, ours: Text, theirs: Text)
returns Record
Merge two edits of a common base line by line: {clean, text}, with conflict markers when both changed the same lines.
merge3(base, ours, theirs)
next_occurrence(rule: Text, anchor: Date, after: Date)
returns Record
{date, error}: the first date after after that a recurrence counted from anchor falls on, or null with why there is none. A recurrence is day, week, month or year (or daily, weekly, monthly, yearly), or a positive whole-day duration such as 2w. Months and years keep the anchor's day, or the month's last day when it has none (an anchor on the 31st comes back on the 30th, then the 31st).
next_occurrence("month", 2026-01-31, today())
parse_date(text: Text, format: Text)
returns Date or Null
Parse a calendar date with a strftime format; invalid input returns null.
parse_date("2026-09-18", "%F")
parse_datetime(text: Text, format: Text, offset: DateTime)
returns DateTime or Null
Parse a local timestamp using a reference timestamp's offset.
parse_datetime("2026-09-18 09:30", "%F %H:%M", now())
parse_duration(text: Text)
returns Duration or Null
Parse a written duration.
parse_duration("2h")
parse_time(text: Text, format: Text)
returns Duration or Null
Parse a time of day as seconds since midnight.
parse_time("09:30", "%H:%M")
pending(message: Text)
returns Never
Return an evaluation error that says the data is not available yet, such as a lookup nothing has fetched: hosts report it as a warning rather than a mistake in the note.
pending("No cached score; run xmd refresh")
quantize(values: List, levels: Number, low: Number or Null, high: Number or Null)
returns List
Each value's level from 0 to levels - 1, in equal steps between low and high (the values' own extremes when both are null) and clipped to them; null stays null, and equal bounds put every value on the middle level. Reads magnitudes as number does, so units are the caller's to check.
quantize([12, 18, 9, 24], 8, null, null)
solve_linear(model: Record)
returns Record
Solve a bounded linear model and return raw numeric values and status.
solve_linear(model)
tagged(kind: Text, fields: Record, display: Text, hover?: Markdown)
returns the kind
A record a note sees as a kind of its own, named by the module: a capitalized name of letters, digits and underscores that no built-in kind has. It reads its fields, names the kind in type, hovers and errors, shows the display text wherever it is shown, adds the hover to a symbol's hover, and is the plain record in queries and JSON. A record whose origin field is null learns the definition whose whole expression is the call that built it: {document, name, line, text, range, function, arguments}.
tagged("Reading", {celsius: 21}, "21°C")
to_json(value: Text, Number, Boolean, Null, List or Record)
returns Text
The value as compact JSON, record keys sorted. Anything else, a date included, is an error: write it as text first.
to_json({title: "Rent", due: "2026-10-01"})
url_encode(text: Text)
returns Text
Percent-encode text for a URL query or path segment, spaces as +.
url_encode("New York")