API Reference
Every Deft API, indexed straight from the per-symbol reference docs.
Core is what the deft command line can do;
TUI is the host layer (retro / retra / hydra).
922 symbols · 62 namespaces
Core
Core 721 symbols
Available in the deft scripting runtime — language, data, files, network, servers, and tooling.
Globals
186 symbolsabs
Return the absolute value of a number.
add-watch
Register a watcher fn on a ref cell under key. The fn is invoked with (key cell old new) on every swap!/reset! (never on def).
after-cancel
Cancel a scheduled after callback.
after
Schedule a callback to run after n milliseconds.
aget
Get the element at index $idx from a mutable array or vector. Zero-based and O(1); literal [aget ...] calls compile to a dedicated opcode. Out-of-range indices, negative indices, and non-indexable targets all return nil.
all?
Check if all elements match a predicate.
and-then
Monadic bind (flatMap) for Results.
any?
Check if any element matches a predicate.
append
Add an element to the end of a list.
apply
Call a function with explicit arguments. $fn may be a direct callable or a string/keyword name resolved through the namespace chain.
array-of
Create a mutable flat array of $n copies of $fill in a single allocation. Size 0 yields @{}; a fractional $n truncates toward zero.
array
Create a mutable flat array with O(1) indexed access via aget/aset. A single number argument makes a nil-filled array of that length, NOT a one-element array — [array 5] and [array 5 6] mean different things.
aset
Set the element at index $idx in a mutable array (in place, O(1)) and return the array. Also accepts vectors, whose backing store is updated in place; an out-of-range index is a silent no-op.
assoc-in
Associate a value at a path in a nested map.
assoc
Add or update one or more keys in a map.
async
Define an asynchronous function that returns a Future.
avg
Compute the average of arguments.
await
Resolve a Future or coroutine to its result value. Passes through non-future values unchanged.
begin
Evaluate a sequence of expressions in order, returning the value of the last one. Discards intermediate results.
break
Exit a for or while loop early.
byte-at
Raw byte value (0-255) at a byte index — the binary-safe counterpart of char-at. Use for byte-oriented data (protocol parsing, encoded blobs); text code wants char-at.
capabilities
Return a map describing the running binary's compiled-in feature set so code can branch on platform capability rather than rely on silent no-ops. This is a top-level stdlib function, available in every build — including the standalone scripting shell (deft), not just the workspace/TUI runtime.
ceil
Round a number up to the nearest integer.
cells
Decode a UTF-8 string into display cells: a vector of @{char-index char-string width} entries, one per codepoint.
char-at
The character at CODEPOINT index n — the same coordinate system as nth/slice (never a raw byte fragment; byte-at for binary).
clamp
Constrain a value to a range [min, max].
close
Close a channel opened with open.
collect
Materialize a lazy sequence into a concrete list.
comp
Compose transducers right-to-left. (comp) with no args is the identity transducer.
completing
Wrap a 2-arg function as a %Reducer. Optional 2nd arg supplies a custom completing fn.
contains
Check if a string contains a substring.
continue
Skip the rest of the current loop iteration.
coro-state
Get the state of a coroutine.
current-ns
Return the name of the current namespace.
curry
Partial application. Returns a closure awaiting the remaining args.
def
Define a function.
defcoro
Define a coroutine.
defer
Execute a block when the current scope exits (cleanup).
defimpl
Implement a protocol's methods for a specific type.
defmacro
Define a compile-time macro that transforms code before evaluation. Macros operate on AST forms (unevaluated SExprs), not values. They expand at compile time — zero runtime cost.
defmethod
Add a method directly to a type without defining a protocol.
defmod
Declare a module namespace.
defprotocol
Define a protocol — a set of methods that types can implement.
defsuite
Define a test suite.
deftask
Create an async task — a Future or stream depending on the body's decorators.
deftest
Define a single test case (usually inside a defsuite).
deftype
Define a user-defined type with named fields. Instances are tagged maps.
defunion
Define a union (sum) type over existing deftypes. A value of the union is always one of its variants; there is no union constructor of its own.
defworker
Spawn a persistent worker — Deft's answer to Node's worker_threads.
deref
Get the current value of a ref cell (an anonymous ref or a [var x] binding cell).
difference
Elements in the first set but not in the second.
dissoc
Remove a key from a map.
drop
Skip the first N elements, return the rest.
each
Execute a side-effect function for each element. Does not return a transformed list.
echo
Print a value to standard output.
empty?
Check if a string or collection is empty.
ends-with?
Check if a string ends with a suffix.
entries
Return key-value pairs of a map as a list of [key, value] pairs.
err!
Assert that a value is %Err and extract its :message; if it is %Ok, return from the enclosing function with that Ok. Any other value passes through unchanged. Symmetric counterpart of ok!.
err
Create an error Result value.
err?
Check if a Result is an Err value.
eval
Evaluate a string as Deft source code and return the result.
fill-range
Return a new list (vector) with the elements in [start, end) replaced by $val, built in one allocation — replaces a set-nth loop over a contiguous range. Negative indices count from the end.
filter
Keep elements that match a predicate.
find
Return the first element matching a predicate.
first
Return the first element of a list or sequence.
flatten
Flatten nested lists into a single list.
floor
Round a number down to the nearest integer.
for
Iterate over elements of a list or sequence.
format
Printf-style string formatting. Interpolates arguments into a format string using %-prefixed conversion specifiers (C printf / Go fmt convention).
from-entries
Convert a list of [key value] pairs into a map.
from
Selectively import specific definitions from a module.
future?
Check if a value is a Future (async task).
get-in
Get a value from a nested map by a path of keys.
get
Get a value from a map or list by key or index, with an optional default.
gets
Read one line from a channel (defaults to :stdin).
group
Group list elements by a key function.
identity
Return the argument unchanged.
if
Conditional branching. Statement form uses else; expression form uses [if] without else.
import
Import a module, making its definitions available.
in-ns
Switch the current namespace (like cd for modules).
in?
Check if a value exists in a list or set.
indent
Indent each line of a string.
index-of
Find a substring in a string, or a value in a list. The string result is a CODEPOINT index — the same coordinate system as len/slice/nth (slice the hit with $s($i .. ($i + n))). Returns -1 (strings) or nil (lists) when not found.
insert-nth
Return a new list with a value inserted at an index.
int
Convert a number or string to an integer (truncates toward zero).
intersection
Compute elements common to both sets.
into
Conjoin elements of a collection through a transducer into a target collection.
is?
Check if a value is of a given type. For user-defined types the check walks the whole parent chain (<<), so a subtype is also is? its ancestors.
join
Join a list of strings with a separator.
keys
Return the keys of a map.
keyword
Create a keyword from a string.
last
Return the last element of a list.
len
Length of a collection or string. For strings this is the CODEPOINT count — multi-byte characters (中, é, ─) count 1 each. Use bytes/len when you mean the byte size (buffer sizing, protocol offsets on binary data).
lines
Split a string by newlines.
log
Append values to /deft.log, bypassing TUI redirects and the echo capture buffer. Always writes to disk regardless of host (CLI, TUI, scripting).
logging
The logging system provides debug, info, warn, and error macros that wrap the built-in log/* functions. The level check happens at compile time — when DEFT_LOG_LEVEL filters out a level, the filtered call sites produce zero runtime code (not even a branch).
lower
Convert a string to lowercase.
map
Transform each element of a list using a function.
mapcat
Apply a function to each element of a collection and concatenate the results (flat map).
match
Pattern matching expression. Tests a value against patterns, evaluates the first match.
max
Return the maximum of the arguments.
merge
Combine two maps. Later keys override earlier ones.
meta
Read metadata from a function or value.
min
Return the minimum of the arguments.
mod
Return the remainder of integer division.
next
Alias for resume — advance a suspended coroutine/generator and return the next yielded value. Use it to drive spawned coroutines or defcoro/@generator functions one step at a time.
nil?
Check if a value is nil.
nth
Element at index n. For strings: the n-th CODEPOINT as a string (never a raw byte fragment). Negative indices count from the end; out of range returns nil.
num
Convert a value to a number.
ok!
Assert that an expression is %Ok and unwrap its :value; if it is %Err, return from the enclosing function with that Err. Any other value passes through unchanged.
ok
Create a success Result value.
ok?
Check if a Result is an Ok value.
open
Open a file for line I/O, returning an opaque channel handle.
pad-left
Pad a string on the left to a minimum width. width counts CHARACTERS (len semantics); for display-cell alignment with wide glyphs use pad-width-left.
pad-right
Pad a string on the right to a minimum width. width counts CHARACTERS (len semantics); for display-cell alignment with wide glyphs use pad-width-right.
pad-width-left
Pad a string on the left to w DISPLAY cells (fill defaults to a space). Unlike pad-left, East Asian Wide glyphs count as 2 cells, so mixed-script columns stay aligned.
pad-width-right
Pad a string on the right to w DISPLAY cells (fill defaults to a space). Unlike pad-left, East Asian Wide glyphs count as 2 cells, so mixed-script columns stay aligned.
pow
Raise a number to a power.
prelude
Return the loaded prelude configuration (the auto-loaded %Prelude tagged map), or nil if none is loaded.
pretty-str
Return a pretty-formatted string for a value.
pretty
Pretty-print a value to stderr with indentation and line breaks.
puts
Write a value to a channel (defaults to :stdout), followed by a newline.
random
Generate a random number between 0.0 and 1.0.
range
Generate a list of integers.
reduce
Fold a list into a single value with an accumulator.
reduced
Wrap a value in a %Reduced early-termination signal.
reduced?
True if a value is a %Reduced early-termination wrapper.
ref
Create a new anonymous ref cell with an initial value.
ref?
Check if a value is a ref cell (either an anonymous ref or a [var x] binding cell). Use var? to test specifically for binding cells.
reload
Re-evaluate a source file in the current namespace.
remove-nth
Return a new list with the element at an index removed.
remove-watch
Remove the watcher registered under key from the ref cell.
repeat
Repeat a string a given number of times.
replace-first
Replace the first occurrence of a substring.
replace
Replace all occurrences of a substring.
replicate
Build a vector of $n copies of $val in a single allocation — use it instead of an append loop for pre-filling. Negative $n is treated as 0; a fractional $n truncates toward zero.
reset!
Set a ref cell to a new value, returning the new value. Fires any registered watchers with (key cell old new). def rebinding a binding cell's root does NOT fire watchers.
rest
Return all elements except the first.
resume
Resume a suspended coroutine, passing an optional value in.
return
Return a value from a function early.
reverse
Reverse a list or string. Strings reverse by CODEPOINT — multi-byte characters stay intact.
round
Round a number to the nearest integer.
rpc
Call a public @rpc method exposed by another runtime. Returns a Future that resolves to the method's return value when the target finishes. Works from any runtime — in-panel apps, headless child runtimes (e.g. the shell's REPL), cluster workers, or standalone scripts.
satisfies?
Check whether a value implements a named protocol, returning true or false. Looks up the value's type name (a tagged map's tag, or the built-in type name) and searches the type registry for a defimpl of that protocol, walking the type's inheritance chain.
set-nth
Return a new list with the element at an index replaced.
set
Assign a value to a variable.
sleep
Yield the current coroutine for n milliseconds.
slice
Sub-range of a list or string. For strings the indices are CODEPOINTS — slicing never lands mid-character (mojibake is impossible). Negative indices count from the end; nil start/end mean 0/length. $s(a..b) is sugar for [slice $s a b].
sort
Sort elements in ascending order.
spawn
Spawn a coroutine from a closure.
split
Split a string by a delimiter. With an empty delimiter the string splits into CODEPOINTS (whole characters, never byte fragments).
sqrt
Return the square root of a number.
starts-with?
Check if a string starts with a prefix.
str
Concatenate values into a string.
subset?
Check if the first set is a subset of the second.
sum
Sum all arguments.
superset?
Check if one set is a superset of another.
swap!
Apply a function to a ref cell's current value and update it. Returns the new value. Fires any registered watchers with (key cell old new).
tag
Tag a plain map with a type name, making it a typed instance.
take
Return the first N elements of a list.
throw
Throw an error, triggering the nearest try catch handler.
transduce
Reduce a collection through a transducer.
trim
Remove leading and trailing whitespace from a string.
truncate-width
Longest prefix of a string fitting w display cells — a wide glyph that would straddle the limit is dropped whole, never half-drawn. The width-aware replacement for byte-based truncation (len counts bytes, so column math drifts on non-ASCII text).
try
Exception handling. Execute a block and catch errors.
type
Return the type name of a value as a string.
union
Compute the union of two sets.
unique
Remove duplicate elements from a list.
unreduced
Unwrap a %Reduced wrapper; idempotent on non-reduced values.
untag
Remove the type tag from a tagged map, returning a plain map.
unwrap
Extract the value from a Result. Optionally provide a default for Err results.
update
Process pending events without blocking.
upper
Convert a string to uppercase.
values
Return the values of a map.
var?
Check if a value is an interned binding cell ([var x]) — the cell behind a module def. Use ref? to test for any ref cell.
vary-meta
Apply $f to the value's current metadata (or nil when it has none) and attach the result — equivalent to [with-meta $value [$f [meta $value]]]. Convenient for threading functional metadata updates.
vwait
Wait for events, blocking until at least one fires.
while
Loop while a condition is true.
width
Display width of a string in terminal cells: East Asian Wide/Fullwidth codepoints (CJK ideographs, kana, Hangul, fullwidth forms, wide emoji) count 2, everything else counts 1. Invalid UTF-8 bytes count 1 each.
with-meta
Attach metadata to a function or value.
without-meta
Return a copy of the value with its metadata stripped, sharing the same payload. Values that carry no metadata (or whose kind cannot carry any) are returned unchanged. Useful for display or serialization when side-channel metadata should not be shown.
words
Split a string by whitespace.
wrap-width
Greedy word wrap at w display cells: breaks at spaces when possible, hard-breaks words longer than the width, and never splits a wide glyph's cell pair. Newlines in the input start fresh lines. The display-aware replacement for hand-rolled column wrapping in chat, log, and markdown UIs.
yield
Yield a value from a coroutine or generator.
zip
Combine two lists into a list of pairs.
ai
4 symbolsask
Single-turn LLM query through the dynamic provider registry. The provider is chosen by the cfg's :provider keyword; provider packages tagged "ai-provider" (deft/ai-deepseek, deft/ai-anthropic, ...) are discovered and loaded on first use.
chat
Multi-turn conversation with tool use. Appends the user message, runs the tool-use loop against the MCP tool registry, and returns the extended message list. The provider comes from the cfg (registry form) or is passed explicitly (low-level form).
complete
Raw single-shot completion. There is no separate registry entry point by this name — build a cfg and use ai/ask, or drive the provider protocol directly when you need the parsed response map:
models
List the models a provider plugin advertises.
assert
15 symbolscontains?
Assert a collection or string contains an element or substring. Used inside deftest blocks.
empty?
Assert a collection or string is empty. Used inside deftest blocks.
eq
Assert two values are equal. Used inside deftest blocks.
falsy
Assert a value is falsy. Used inside deftest blocks.
gt
Assert a > b for numbers. Used inside deftest blocks.
gte
Assert a >= b for numbers. Used inside deftest blocks.
length
Assert the length of a collection or string. Used inside deftest blocks.
lt
Assert a < b for numbers. Used inside deftest blocks.
lte
Assert a <= b for numbers. Used inside deftest blocks.
ne
Assert two values are not equal. Used inside deftest blocks.
nil?
Assert a value is nil. Used inside deftest blocks.
not-empty?
Assert a collection or string is non-empty. Used inside deftest blocks.
not-nil?
Assert a value is not nil. Used inside deftest blocks.
truthy
Assert a value is truthy. Used inside deftest blocks.
type
Assert the type name of a value. Used inside deftest blocks.
bin
54 symbolsbytes-at
Slice a byte string by byte offsets: bytes[offset .. offset+len]. With the length omitted, takes everything from offset to the end. This is the raw counterpart of codepoint-based slice / $s(a..b) and never re-aligns on UTF-8 boundaries.
bytes
Build a byte string from integer byte values (0-255), strings (appended raw), and vectors of integers. The variadic constructor for binary data.
f32-at
Read 32-bit float (little-endian) from a byte string at offset, widened to a Deft number.
f32-be-at
Read 32-bit float (big-endian) from a byte string at offset, widened to a Deft number.
f32-le-at
Read 32-bit float (little-endian) from a byte string at offset, widened to a Deft number.
f64-at
Read 64-bit float (little-endian) from a byte string at offset, widened to a Deft number.
f64-be-at
Read 64-bit float (big-endian) from a byte string at offset, widened to a Deft number.
f64-le-at
Read 64-bit float (little-endian) from a byte string at offset, widened to a Deft number.
i16-at
Read a signed 16-bit integer (little-endian) from a byte string at offset.
i16-be-at
Read a signed 16-bit integer (big-endian) from a byte string at offset.
i16-le-at
Read a signed 16-bit integer (little-endian) from a byte string at offset.
i32-at
Read a signed 32-bit integer (little-endian) from a byte string at offset.
i32-be-at
Read a signed 32-bit integer (big-endian) from a byte string at offset.
i32-le-at
Read a signed 32-bit integer (little-endian) from a byte string at offset.
i64-at
Read a signed 64-bit integer (little-endian) from a byte string at offset.
i64-be-at
Read a signed 64-bit integer (big-endian) from a byte string at offset.
i64-le-at
Read a signed 64-bit integer (little-endian) from a byte string at offset.
set-bytes
Return a copy of $bytes with the bytes of $data overlaid at offset. The copy has the same length as the original — this is an overlay, not an insert. Byte strings are immutable, so the original is unchanged.
set-f32-be
Return a copy of $bytes with a 32-bit float written at offset (big-endian).
set-f32-le
Return a copy of $bytes with a 32-bit float written at offset (little-endian).
set-f32
Return a copy of $bytes with a 32-bit float written at offset (little-endian).
set-f64-be
Return a copy of $bytes with a 64-bit float written at offset (big-endian).
set-f64-le
Return a copy of $bytes with a 64-bit float written at offset (little-endian).
set-f64
Return a copy of $bytes with a 64-bit float written at offset (little-endian).
set-i16-be
Return a copy of $bytes with a signed 16-bit integer written at offset (big-endian).
set-i16-le
Return a copy of $bytes with a signed 16-bit integer written at offset (little-endian).
set-i16
Return a copy of $bytes with a signed 16-bit integer written at offset (little-endian).
set-i32-be
Return a copy of $bytes with a signed 32-bit integer written at offset (big-endian).
set-i32-le
Return a copy of $bytes with a signed 32-bit integer written at offset (little-endian).
set-i32
Return a copy of $bytes with a signed 32-bit integer written at offset (little-endian).
set-i64-be
Return a copy of $bytes with a signed 64-bit integer written at offset (big-endian).
set-i64-le
Return a copy of $bytes with a signed 64-bit integer written at offset (little-endian).
set-i64
Return a copy of $bytes with a signed 64-bit integer written at offset (little-endian).
set-u16-be
Return a copy of $bytes with an unsigned 16-bit integer written at offset (big-endian).
set-u16-le
Return a copy of $bytes with an unsigned 16-bit integer written at offset (little-endian).
set-u16
Return a copy of $bytes with an unsigned 16-bit integer written at offset (little-endian).
set-u32-be
Return a copy of $bytes with an unsigned 32-bit integer written at offset (big-endian).
set-u32-le
Return a copy of $bytes with an unsigned 32-bit integer written at offset (little-endian).
set-u32
Return a copy of $bytes with an unsigned 32-bit integer written at offset (little-endian).
set-u64-be
Return a copy of $bytes with an unsigned 64-bit integer written at offset (big-endian).
set-u64-le
Return a copy of $bytes with an unsigned 64-bit integer written at offset (little-endian).
set-u64
Return a copy of $bytes with an unsigned 64-bit integer written at offset (little-endian).
set-u8
Return a copy of $bytes with an unsigned byte written at offset.
u16-at
Read an unsigned 16-bit integer (little-endian) from a byte string at offset.
u16-be-at
Read an unsigned 16-bit integer (big-endian) from a byte string at offset.
u16-le-at
Read an unsigned 16-bit integer (little-endian) from a byte string at offset.
u32-at
Read an unsigned 32-bit integer (little-endian) from a byte string at offset.
u32-be-at
Read an unsigned 32-bit integer (big-endian) from a byte string at offset.
u32-le-at
Read an unsigned 32-bit integer (little-endian) from a byte string at offset.
u64-at
Read an unsigned 64-bit integer (little-endian) from a byte string at offset.
u64-be-at
Read an unsigned 64-bit integer (big-endian) from a byte string at offset.
u64-le-at
Read an unsigned 64-bit integer (little-endian) from a byte string at offset.
u8-at
Read an unsigned byte from a byte string at offset.
zeros
Build a byte string of n NUL bytes (0x00). Useful as the buffer for bin/set-* writes and as a scratch region for protocol framing.
bytes
2 symbolslen
Byte length of a string. len counts CODEPOINTS; use bytes/len for buffer sizing and byte offsets on binary data (fs/read bodies, crypto, encoded blobs) — byte math must never drift on data that happens to contain valid UTF-8 runs.
slice
Sub-range by BYTE indices [start, end) — the raw counterpart of codepoint-based slice. For binary data (fs/read bodies, crypto, blobs) whose chunk boundaries must not be re-aligned by accidental UTF-8 runs. Negative indices count from the end; nil start/end mean 0/length.
capture
4 symbolsclear
Discard any captured content and uninstall the capture buffer without reading it.
flush
Drain the capture buffer and uninstall it. Subsequent echo/println calls go to stdout/stderr again.
start
Install (or clear) the VM's echo capture buffer. Subsequent echo/println calls append to it instead of writing to stdout/stderr. Idempotent.
with
Capture all echo/println output produced by invoking a 0-arity callable. Safe to nest — restores any prior capture buffer on exit.
chars
10 symbolsalpha?
Check if a character is alphabetic (a-z, A-Z).
count
Number of codepoints in a string — identical to len on strings (kept as an explicit, self-documenting form). bytes/len is the byte size.
digit?
Check if a character is a digit (0-9).
ident-cont?
Check if a character can continue an identifier (alphanumeric, _, -, ?, !, /).
ident-start?
Check if a character can start an identifier (alpha or _).
lower?
Check if a character is lowercase (a-z).
slice
Substring by CODEPOINT indices [a, b) — identical to slice on strings (kept as a self-documenting form). b clamps to the string end, a to 0; a >= b yields "".
space?
Check if a character is whitespace (space, tab, newline, carriage return).
upper?
Check if a character is uppercase (A-Z).
word?
Check if a character is a word character (alphanumeric, _, -, ?, !, /).
clock
7 symbolsadd
Calendar-aware date arithmetic on an epoch-seconds value. Positional form [clock/add time n :unit n :unit …]; spec-map form [clock/add time %{ :days n :months n :timezone "…" }].
clicks
Return a high-resolution monotonic timestamp in nanoseconds. Unlike the other clock/ primitives this value is not anchored to the epoch — it is only meaningful as a difference between two samples. Use it for elapsed-time and profiling measurements.
format
Format an epoch-seconds value as a string. Positional form [clock/format time ?format? ?timezone?]; spec-map form [clock/format time %{ :format "…" :timezone "…" :locale "…" }].
micros
Return the current time as integer microseconds since the Unix epoch (1970-01-01 00:00:00 UTC).
millis
Return the current time as integer milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC).
scan
Parse a string into epoch seconds. Strict strptime-style dual of clock/format — the same specifier table drives both. Free-form parsing is intentionally not supported (TCL deprecated it for irreducible ambiguity): :format is required.
seconds
Return the current time as integer seconds since the Unix epoch (1970-01-01 00:00:00 UTC). This is the universal value type for the whole clock/ namespace: every other subcommand takes or returns epoch seconds.
compress
7 symbolsgunzip
Decompress gzip-encoded bytes. Returns the original bytes.
gzip
Gzip-compress bytes using a stored-block deflate stream. Returns compressed bytes.
list-tgz
List the entry paths inside a tar.gz archive without extracting.
tar-create
Create a USTAR tar archive from a directory tree. Returns the archive as bytes.
tar-extract
Extract a tar archive (bytes) into a destination directory.
tgz-create
Create a tar.gz archive from a directory tree. Equivalent to gzip-compressing a tar archive. Returns the compressed bytes.
tgz-extract
Extract a tar.gz archive (bytes) into a destination directory. Decompresses with gzip, then unpacks the tar stream.
config
10 symbolscount
Return the total number of keys currently in the registry.
get
Look up a key in the global config registry. Returns the stored value, or nil if absent.
keys
Return a list of all key names matching the given prefix.
load
Load registry entries from a Deft map file, replacing the current registry contents. The file must be a flat %{ "dotted/key" value } map whose values are valid Deft literals.
save-map
Write a given map to a Deft config file in the same format used by config/save. Used by the config app to persist only the user overrides diff rather than the entire registry.
save-overrides
Diff the live registry against the loaded defaults snapshot and write only the keys whose current value differs from default. The canonical save path for the config app — produces a minimal .deft/config.dft acting as a clean "user changes" layer over package defaults.
save
Write the entire registry to a Deft map file in %{ "dotted/key" value } form. Atomicity is best-effort (write-then-rename).
scan
Return a map of all registry entries whose key starts with the given prefix. Used to read one app's slice of the registry at once.
set
Store a value under a key in the global config registry, replacing any prior value. Publishes a change event on the "config" pub/sub topic.
unset
Remove a key from the global config registry.
crypto
14 symbolsb64-decode
Decode a standard base64 string (with padding) back to raw bytes.
b64-encode
Encode a string into standard base64 (with padding).
blake3
Compute the BLAKE3 hash of the input. Returns the digest as a lowercase hex string (64 chars).
decrypt
- :chacha20-poly1305 — Algorithm keyword (only one supported) - $key-hex — 32-byte key as 64 hex chars (must match encryption key) - $nonce-hex — 12-byte nonce as 24 hex chars (must match encryption nonce) - $ciphertext-hex — Hex ciphertext (from %Encrypted~ciphertext) - $tag-hex — 16-byte tag as 32 hex chars (from %Encrypted~tag) - ?$aad — Optional AAD (must match encryption)
encrypt
- :chacha20-poly1305 — Algorithm keyword (only one supported) - $key-hex — 32-byte key as 64 hex chars - $nonce-hex — 12-byte nonce as 24 hex chars - $plaintext — String to encrypt - ?$aad — Optional AAD (covered by tag, not encrypted)
hash
Hash data with a named algorithm (dispatches to the dedicated hash function).
hex-decode
Decode a hexadecimal string back to raw bytes.
hex-encode
Encode a string's bytes into lowercase hexadecimal.
hmac
Compute an HMAC (keyed hash-based message authentication code) as a hex string.
md5
Compute the MD5 hash of the input. Returns the digest as a lowercase hex string (32 chars). MD5 is cryptographically broken — use only for non-security-critical checksums.
rand-hex
Generate cryptographically secure random bytes from the OS CSPRNG. Returns the bytes as a lowercase hex string.
rand
Generate cryptographically secure random bytes from the OS CSPRNG. Returns a vector of byte values (each 0-255).
sha256
Compute the SHA-256 hash of the input. Returns the digest as a lowercase hex string (64 chars).
sha512
Compute the SHA-512 hash of the input. Returns the digest as a lowercase hex string (128 chars).
dbus
12 symbolscall
Call a D-Bus method and return a Future; [await ...] for the reply.
connect
Connect to a D-Bus bus and complete the SASL auth + HELLO handshake synchronously, so the connection is ready for calls, subscriptions, and exports immediately.
disconnect
Close a connection's transport. Pending calls and name registrations reject with %Err{:message "connection closed"}; dbus/info afterwards reports :state :failed. The resource struct survives until GC, so calling dbus/disconnect twice is safe.
emit
Emit a broadcast signal (no destination) on a connection. Subscribers with a matching rule receive it via dbus/subscribe.
export
Export an object on a connection so other clients can call methods on it (server role). Handlers are pinned for the lifetime of the export.
info
Snapshot of a connection's state and outstanding work.
register-name
Request a well-known bus name from the daemon (RequestName). A well-known name (org.freedesktop.Notifications, org.deft.myapp) is a bus-level alias that at most one connection owns at a time — callers address the name and the bus routes to whoever owns it. Every other connection can still call and subscribe; only ownership is exclusive. Custom names are the standard way for separate deft processes to address each other.
send
Fire-and-forget method call: sends the message and drops the reply.
subscribe
Subscribe a closure to broadcast signals matching a D-Bus match rule (AddMatch). Signals are delivered while the VM event loop is pumped (e.g. during await, sleep, or vwait).
unexport
Remove an interface exported with dbus/export. Handler closures are unpinned and the export is dropped.
unique-name
The connection's unique bus name (e.g. ":1.5"), or nil before the HELLO handshake completes.
unsubscribe
Remove a signal subscription previously registered with dbus/subscribe and send RemoveMatch to the daemon.
debug
3 symbolsdeft
4 symbolsparse-forms
Parse arbitrary Deft source into %Sexpr{} form trees without evaluating it. Unlike deft/parse, which accepts only data literals, this runs the full kernel parser — calls, defs, control flow, decorators, and map literals all come back as structured forms with source positions, so tooling (importers, graph builders, syntax tools) can inspect code without invoking the compiler.
parse
Parse a Deft-literal string back into a value. Handles the output of deft/stringify. Data-only — no evaluation, no side effects.
stringify
Serialize any value to a parseable Deft-literal string. Round-trips through deft/parse for data types: nil, bool, number, string, keyword, vector, map, tagged-map, set.
syntax-highlight
Tokenize a Deft source string and return highlighted HTML wrapped as %__HtmlSafe{:value ""}. Each token whose type has a class is wrapped in …; lex failures fall back to plain HTML-escaped text.
dialog
9 symbolschecklist
Open a multi-selection list dialog.
confirm
Open a Yes/No confirmation dialog.
file-open
Open a file picker dialog.
file-save
Open a save-as dialog.
menu
Open a single-selection list dialog.
msgbox
Open a message box with a single OK button.
password
Open a masked text input dialog (for secrets).
prompt
Open a single-line text input dialog.
search
Open an incremental-search list dialog. Typing filters the list live — space-separated tokens are matched case-insensitively and all must be substrings of the item (AND semantics). The result value is the selected item text.
dns
10 symbolsaddr-info
Resolve a hostname to full getaddrinfo records — one map per address, carrying the family/socket/protocol metadata dns/lookup discards.
hostname
The local machine's hostname (gethostname).
ip?
Predicate: is the string an IPv4 or IPv6 literal?
ipv4?
Predicate: is the string an IPv4 literal?
ipv6?
Predicate: is the string an IPv6 literal?
local-addresses
Addresses assigned to the local machine's network interfaces (getifaddrs).
lookup
Resolve a hostname to address strings through the system resolver (getaddrinfo).
parse
Parse an IP literal into its canonical string form.
reverse
Reverse-resolve an IP literal to a hostname (getnameinfo).
servers
The nameservers configured in /etc/resolv.conf.
ffi
22 symbolsaddr
Get the raw pointer address of a native resource as a number.
alloc
Allocate native memory of given size in bytes.
call
Call a foreign function: [ffi/call $sym :ret-type @{:arg-types...} args...]
callback
Create a C callback from a Deft closure: [ffi/callback :ret @{:arg-types} $fn]
cdef
Parse C declarations (structs and function signatures) for FFI use.
close
Close a native resource (library, buffer, etc.)
cstring
Convert a Deft string to a nil-terminated C string resource.
gc
Attach a C destructor to a native resource: [ffi/gc $ptr $destructor_fn]
get
Read a struct field: [ffi/get $point "x"]
load
Load a shared library. Returns a native resource handle.
new
Allocate a struct instance: [ffi/new "Point"]
nullptr
Return a nil pointer native resource.
pin
Pin a value so GC won't collect it during FFI calls.
ptr
Wrap a raw pointer address (a number) into a native resource so it can be used with ffi/read, ffi/write, and :ptr argument marshaling. Inverse of ffi/addr. Essential for following pointer fields inside C structs (e.g. redisReply->element).
read-bytes
Read a byte range from native memory into a binary-safe Deft string — NUL bytes are preserved, unlike ffi/string. For buffer resources the range is bounds-checked.
read
Read a typed value from native memory: [ffi/read $buf offset :type]
set
Write a struct field: [ffi/set $point "x" 42]
sizeof
Get size of a C type or struct: [ffi/sizeof :i32] or [ffi/sizeof "Point"]
string
Read a C string from a native resource into a Deft string.
sym
Look up a symbol in a loaded library. Returns a callable handle.
unpin
Unpin a previously pinned value.
write
Write a typed value to native memory: [ffi/write $buf offset :type value]
fs
31 symbolsabs
Get absolute path.
absolute?
Check if path is absolute.
append
Append string to file. Returns %Ok{:value true} or %Err.
base
Get filename portion of path.
copy
Copy a file.
dir
Get directory portion of path.
dir?
Check if path is a directory.
exists?
Check if path exists.
ext
Get file extension.
file?
Check if path is a regular file.
glob
Find files whose basename matches a glob pattern (* and ?).
home
Get home directory.
join
Join path components.
link
Create a symlink at link-path pointing to target. Returns %Ok{:value true} or %Err.
list
List directory with metadata. Returns %Ok{:value list} or %Err.
local-dir
Conventional path .deft/local/, creating it (and parents) if needed. Idempotent.
local-path
Conventional path .deft/local//. Does not create directories.
mkdir
Create directory (and parents). Returns %Ok{:value true} or %Err.
read-lines
Read file as list of lines. Returns %Ok{:value list} or %Err.
read
Read file contents as string. Returns %Ok{:value string} or %Err.
readdir
List directory (names only). Returns %Ok{:value list} or %Err.
remove
Remove file or empty directory. Returns %Ok{:value true} or %Err.
rename
Rename/move a file. Returns %Ok{:value true} or %Err.
stat
Get file metadata: size, is-dir, modified. Returns %Ok{:value map} or %Err.
tempdir
Get system temp directory.
tmp-dir
Per-process scratch directory /tmp/deft-/. Created on first call.
tmp-path
Resolve a path inside the per-process scratch directory.
unwatch
Cancel a watch previously created by fs/watch.
watch
Watch a file or directory (recursive) for changes.
write-lines
Write list of lines to file. Returns %Ok{:value true} or %Err.
write
Write string to file (creates/truncates). Returns %Ok{:value true} or %Err.
gc
4 symbolscensus
Diagnostic: walk the live heap object list (without collecting) and report per-kind counts, total string bytes, and the 12 largest live strings with snippets. Run after [gc/collect] to see what is still reachable when :live-bytes will not come down.
collect
Force a full GC and trim glibc arenas. Returns vm bytes after collection.
pools
Diagnostic: walk every GC retention pool — per-kind free lists, small-string and small-keyword buckets, CHAMP buckets, slabs, vector-trie nodes, and the keyword table. O(pooled objects), so it is for leak triage, not hot paths.
stats
Return a map of GC statistics for the current VM's heap.
html
9 symbolsclose
Explicitly release a %HtmlDocument handle from html/open.
decode-entities
Decode HTML5 character references in a plain string — the full named set (&, ©, —, …) plus decimal and hex numeric references (A, 😀) — without parsing anything as markup.
from-markdown
Render markdown to HTML — a CommonMark-lite renderer covering the deft markdown dialect plus the standard extras scripts actually meet. All text is HTML-escaped on output, so the result is safe to embed.
open
Parse an HTML document once and return a %HtmlDocument handle, so repeated html/select / html/text / html/serialize calls run against the live parsed document instead of re-parsing the string every call.
parse
Parse an HTML document into a Deft tree. WHATWG-compliant tag-soup recovery: unclosed and stray tags, misnesting, and mangled tables recover the way a browser recovers, and character references (named like &, numeric like 😀) are decoded in text and attributes during the parse.
select
Query a parsed document with a CSS selector list and get the matching elements as Deft trees. .class, #id, attribute selectors, combinators (div > p, a b), pseudo-classes (:first-child, :has(), …) — the full selector language.
serialize
Serialize a parsed document back to HTML. Round-trips what the parser normalised — entity decoding is re-encoded, repaired markup comes out well-formed.
text
Extract readable plain text from HTML: script/style/head/template content is dropped, block tags and
become line breaks, list items get a - prefix, table cells join with | , and whitespace collapses the way a browser renders it. Entities are decoded by the parser.
become line breaks, list items get a - prefix, table cells join with | , and whitespace collapses the way a browser renders it. Entities are decoded by the parser.
to-markdown
Convert HTML to markdown in the deft markdown-viewer dialect — the pipeline for rendering HTML mail and documents with the markdown viewer. WHATWG parsing (tag soup recovers like a browser), then a DOM walk emitting exactly what the viewer renders.
http
38 symbolsclient
Create a reusable HTTP client with connection pooling.
close
Close an HTTP client handle.
cluster-metrics
Return the full cluster info map for a cluster started with http/serve-cluster.
cluster-reload
Trigger a new-generation cluster reload manually. Spawns fresh workers (each binding SO_REUSEPORT), then destroys the old workers and increments generation.
cluster-status
Return a lightweight health map for the cluster. Unlike http/cluster-metrics, this never errors when no cluster is running — it reports :stopped instead.
cluster-stop
Stop the cluster: close all workers' listener fds, destroy the worker runtimes, and clear the cluster state.
delete
HTTP DELETE request. Returns %{ status body headers }.
do
Execute request on a client handle: [http/do $client :METHOD url opts].
get
HTTP GET request. Returns %{ status body headers location }.
head
HTTP HEAD request. Returns %{ status headers } (no body).
header
Set response header: [http/header $res "name" "value"]
html
Write HTML response: [http/html $res "
hi
"]json
Write JSON response: [http/json $res $data]
patch
HTTP PATCH request. Returns %{ status body headers }.
post
HTTP POST request. Returns %{ status body headers }.
put
HTTP PUT request. Returns %{ status body headers }.
redirect
Send redirect: [http/redirect $res "/url" 302]
request
Full-control HTTP request: [http/request :METHOD url opts].
respond
Write response body: [http/respond $res "body" "content-type"]
router
Wrap a map as %Router{} and register it for http/serve.
serve-cluster
Start a cluster of N worker runtimes, each binding the same port with SO_REUSEPORT for kernel-level accept load-balancing. Each worker loads the app file independently (which calls http/serve itself).
serve
Start HTTP server: [http/serve port] or [http/serve port $router ...]
set-timeout
Set the request timeout for an HTTP client.
sse-close
Close a Server-Sent Events stream cleanly: queue the terminal chunk, flush pending bytes, fire :on-close, and close the connection.
sse-comment
Send an SSE comment line — the manual keep-alive form. Comments are ignored by EventSource clients but keep the connection and intermediaries alive.
sse-send
Send one Server-Sent Event on a stream. Multi-line data is split into one data: line per line.
sse
Open a Server-Sent Events stream on a %Response{} from an HTTP route handler. The text/event-stream headers and chunked transfer encoding are written and flushed immediately; the connection stays open until http/sse-close or the client disconnects.
status
Set response status: [http/status $res 404]
stop
Stop an HTTP server: [http/stop $server]
ws-close
Close a WebSocket connection.
ws-connect
Connect to a WebSocket server (ws:// or wss://).
ws-on-close
Register a callback fired when a WebSocket connection closes.
ws-on-message
Register a callback for incoming messages on a WebSocket connection.
ws-ping
Send a ping frame on a WebSocket connection.
ws-send-binary
Send a binary frame on a WebSocket connection.
ws-send
Send a text frame on a WebSocket connection.
ws-server
Start a WebSocket server (RFC 6455).
ws-stop
Stop a WebSocket server.
hypr
9 symbolsbind
Add a keybind by sending keyword bind on the command socket (the reply is discarded).
call
Send a command on Hyprland's command socket and return a Future for the raw reply line. j/-prefixed commands return JSON (parse with json/parse); others return "ok" or an error string. Replies are matched to calls FIFO.
connect
Connect to Hyprland's two IPC sockets (event socket + command socket). The sockets are non-blocking and serviced by the VM event loop, so subscriptions and calls can follow immediately.
disconnect
Close both of a connection's sockets. Pending hypr/call futures reject and hypr/info afterwards reports :state :failed.
info
Snapshot of a hypr connection's state.
send
Send a command on the command socket, discarding the reply. A placeholder keeps the reply FIFO aligned with later hypr/calls.
subscribe
Subscribe a closure to a named Hyprland event. The closure receives %{ :name "workspace" :payload "json…" }; :payload is the raw second line of the event (empty string when the event carries no payload), so parse it with json/parse when it is JSON. Re-subscribing to the same name replaces the previous closure.
unbind
Remove a keybind by sending keyword unbind on the command socket (the reply is discarded).
unsubscribe
Remove an event subscription by name. The closure is unpinned; later events with that name are not delivered.
image
20 symbolsbase64
Encode an image to bytes in its output format and return them as a standard base64 string — convenient for data URIs and JSON payloads.
bytes
Encode an image to bytes using its output format — the source format by default, or the format set by image/jpeg / image/png / image/webp.
crop
Crop to the rectangle ($x, $y, $w, $h) in pixels, returning a new value of the same type (Image or PixelBuffer). $x/$y are the top-left corner (0-based); $w/$h are the size. The size is clamped so the rectangle never runs past the image bounds, so [image/crop $img 6 4 100 100] on an 8×6 image yields a 2×2 crop.
decode
Decode image bytes already in memory into an Image. The format is sniffed from magic bytes (JPEG/PNG/WebP); garbage or empty input returns nil.
dims
Return the pixel dimensions of an Image or a PixelBuffer as %{ :w N :h N }.
encode
Encode an image to bytes in the named format, ignoring the image's own output format. Returns a binary-safe string.
flip
Mirror an Image or a PixelBuffer vertically (about the x-axis): the top row becomes the bottom row. Returns a new value of the same type.
flop
Mirror an Image or a PixelBuffer horizontally (about the y-axis): the left column becomes the right column. Returns a new value of the same type.
format
Return the image's source format — the format its bytes were decoded from.
free
Release an Image or PixelBuffer immediately. GC will also handle this when the value goes out of scope, but explicit free is useful for short-lived large images and video frames. Idempotent — a second call is a no-op.
jpeg
Return a copy of the image with its output format set to JPEG. This tags the image — encoding happens later in image/bytes, image/write, or image/base64.
load
Load an image file into a CPU-only RGBA pixel buffer. Thread-safe — no GL, safe from any thread including per-panel app threads. Unlike image/open (which returns an Image for the encode/transform pipeline), image/load returns a PixelBuffer whose pixel pointer is stable for its lifetime — the video-frame/GL-upload shape.
open
Load an image file and decode it to RGBA8. The format is sniffed from magic bytes (JPEG/PNG/WebP) — the file extension is ignored. Returns an Image or nil; a missing or undecodable file is never an error.
pixel-buffer
Create a zero-initialized RGBA pixel buffer whose pixel pointer stays stable for its lifetime — write new frames with image/pixel-write and draw/image :refresh reuses one GL texture (no per-frame texture allocation). CPU-only and thread-safe. Available in every native host, including the standalone scripting binary.
pixel-write
Copy RGBA bytes into a pixel buffer in place, optionally at a byte offset, keeping the pixel pointer stable. CPU-only and thread-safe.
png
Return a copy of the image with its output format set to PNG. Encoding with image/bytes / image/write then emits PNG (lossless).
resize
Resize to exactly width x height pixels, returning a new value of the same type (Image or PixelBuffer). Bilinear interpolation is the default; pass :filter :nearest for nearest-neighbour (keeps pixel art crisp).
rotate
Rotate an Image or a PixelBuffer clockwise by 90, 180, or 270 degrees, returning a new value of the same type. Angles outside 0–359 are normalised mod 360, so -90 means 270.
webp
Return a copy of the image with its output format set to WebP. This tags the image — encoding happens later in image/bytes, image/write, or image/base64.
write
Encode an image and write it to a file. The format comes from the path extension (.jpg/.jpeg/.png/.webp) when recognised, otherwise the image's output format is used.
import
1 symbolsinfo
9 symbolsdefs
List defs in current namespace, or in a named namespace
modules
List all namespace names
props
Get the metadata map for a value, namespace, or type. Passing a deftype name returns its reflection map.
protocols
List all protocol names
resolve
Resolve a symbol name through the namespace chain and return its value, or nil if not found.
sig
Get formatted signature string for a function
source
Get source file and namespace for a symbol
types
List all user-defined type names
vars
List all vars visible in current scope
json
3 symbolskeymap
15 symbolsapps
List all app names present in the live keymap, sorted alphabetically. App names are the first segment of the flat app/mode/chord registry keys.
chord
Build the canonical chord string for a key event map. Named-key events produce modifiers in the fixed order ctrl-alt-shift-key; :text events yield the literal character.
count
Return the total number of bindings in the live keymap, across every app, mode, and chord.
get
Look up one binding in the global keymap without any mode fallback. Returns the bound command name, or nil when unbound. This is raw access — use keymap/lookup for keypress-time resolution.
load
Load bindings from a keytable file into the live keymap. User/project files are nested three levels: %{ :app %{ :mode %{ "chord" cmd } } }; when the optional app is supplied the file is that app's two-level map: %{ :mode %{ "chord" cmd } }. A nil leaf means explicitly unbound and removes the binding.
lookup
Resolve a binding at keypress time: try the requested mode first, then fall back to the "default" mode. This is the consumer-side lookup apps should use, so :vi/:emacs sections only need to hold deltas.
modes
List the mode names that have bindings for an app, sorted. Modes are editor-style keysets ("default", "vi", "emacs"); single-keyset apps normally have only "default".
reset
Restore a binding to its per-package default (from the app's keys.dft). When no default exists for that key, the binding is removed entirely. Publishes a change event on the "keymap" pub/sub topic.
save-map
Write a caller-supplied nested map in the same shape keymap/scan returns to a keytable file. Used by the keys app to persist an edited binding set. Values are stringified; a nil value is written as nil (a disabled binding).
save-overrides
Diff the live keymap against the per-package defaults and write only the bindings that changed or were added. Defaults the user removed are written as nil so the disable survives a reload. This is the canonical save path for the keys app.
save
Write the entire live keymap to a nested-map keytable file: %{ :app %{ :mode %{ "chord" cmd } } }. Defaults to the workspace keytable (.deft/keytable.dft in a project). Write-then-rename, so the file is replaced atomically.
scan-overrides
Like keymap/scan, but returns only bindings whose value differs from the per-package defaults, plus keys the user added. Powers the keys manager UI.
scan
Return the effective keymap (package defaults plus user overrides) as a nested map. With an app argument the result is %{ "mode" %{ "chord" "cmd" } }; without one it is %{ "app" %{ "mode" %{ "chord" "cmd" } } }.
set
Bind a chord to a command name, replacing any prior binding. Publishes a change event on the "keymap" pub/sub topic. Returns the command as given.
unset
Remove a binding entirely, making the chord dead in that app/mode. Publishes a change event with :value nil. Returns true if the binding was present.
keyval
7 symbolsclose
Close a client: pending commands reject with %Err and the connection is torn down. The resource is marked closed and freed later by the GC.
cmd
Queue a command on a client and return a Future; [await ...] for the reply. Commands pipeline over one multiplexed connection and are matched FIFO, so blocking commands (BLPOP, WAIT, XREAD BLOCK) stay pending without stalling other calls.
connect
Create a Valkey/Redis (RESP2 + RESP3) client. The client dials lazily on the first keyval/cmd, and re-dials after a failed connection, so connect itself cannot fail on a dead server.
info
Snapshot of a keyval client's state.
on-message
Register (or clear) the callback for RESP3 push messages — pub/sub traffic and other server-initiated pushes, which are not matched to a command future.
resp-parse
Parse exactly one RESP frame (RESP2 or RESP3) from a byte string into a Deft value. Useful for server facades and tests; no server required.
resp-stringify
Encode a Deft value as a RESP reply frame — the other half of keyval/resp-parse, for building server facades.
lang
6 symbolscurrent
Get or set the process-wide current language. With no argument, returns the active language: the host's --lang flag if set, else $LANG with region/encoding stripped (es_ES.UTF-8 → "es", C/POSIX → "en"), else "en". With an argument, sets it process-wide and returns the argument.
get
Translate a phrase through the catalog. The first argument is the language, the second is the app/phrase key; remaining arguments fill the template's {name} placeholders positionally. Resolution order: exact language → region base (es-MX → es) → the app's :fallback → "en" → the raw key string, so untranslated phrases are self-labeling in the UI.
langs
Return the languages present in the catalog for an app, sorted, as a vector of strings.
load
Load a lang file into the catalog, replacing any existing entries for the app. The file is a nested map: %{ :fallback "en" :es %{ :welcome "Hola, {name}" } }. The app name defaults to the file's parent directory name.
set
Store a translation template under (lang, app/phrase), replacing any prior value. Publishes a change event on the "lang" pub/sub topic and writes the app's catalog back to its source lang file. Returns the stored value.
unset
Remove a translation. Publishes a change event on the "lang" pub/sub topic with :value nil and writes the app's catalog back to its source lang file. Returns true if the phrase was present.
log
4 symbolsdebug
Log a debug message. Written to /tmp/deft.log; not surfaced to the workspace error console.
error
Log an error. Written to /tmp/deft.log and the workspace error console.
info
Log an info message. Written to /tmp/deft.log and the workspace error console.
warn
Log a warning. Written to /tmp/deft.log and the workspace error console.
macro
6 symbolscompile-when
Compile-time conditional: evaluate cond during compilation and emit body only if truthy. If falsy, body is skipped entirely — it produces zero runtime code (a single push_null), not even a branch.
gensym
Generate a unique keyword value of the form :prefix#N. Each call returns a distinct value; the counter is monotonic per process.
quote
Build code from a template while preserving $param references as literal symbols. Use [macro/unquote ...] inside to selectively substitute parameters.
splice
Inline the *elements* of a list into the surrounding form during macro expansion. Also written macro/unquote-splice.
syntax-quote
Like macro/quote, but with two differences aimed at hygienic macro code generation:
unquote
The escape hatch inside macro/quote — substitute a parameter (or any expression) into an otherwise-literal code template.
math
22 symbolsacos
Arc cosine; returns an angle in radians.
asin
Arc sine; returns an angle in radians.
atan
Arc tangent; returns an angle in radians.
atan2
Two-argument arc tangent of y/x, using the signs of both arguments to determine the quadrant.
avg
Return the average (arithmetic mean) of all numeric arguments.
cos
Cosine of an angle in radians.
euler
Return Euler's number (e).
exp
Euler's number raised to the power of x.
hypot
Hypotenuse: sqrt(x*x + y*y), computed without undue overflow or underflow.
lerp
Linear interpolation between a and b by factor t.
ln
Natural logarithm (base e) of x.
log10
Base-10 logarithm of x.
log2
Base-2 logarithm of x.
pi
Return the value of π (pi).
pow
Raise a base number to the power of an exponent.
random-range
Return a random number between $min and $max.
sign
Return -1, 0, or 1 based on the sign of a number.
sin
Sine of an angle in radians.
sqrt
Return the square root of a number.
sum
Return the sum of all numeric arguments.
tan
Tangent of an angle in radians.
trunc
Truncate a number towards zero (drop the fractional part).
mcp
5 symbolsadd
Add a deft function as a tool: [mcp/add :name $fn "doc"]
create
Create an MCP tool server: [mcp/create :name]
dispatch
Dispatch a JSON-RPC request string: [mcp/dispatch :name json-string] → json-response-string
http-serve
Start MCP HTTP server (blocks): [mcp/http-serve :name 3001]
serve
Start MCP stdio server (blocks): [mcp/serve :name]
net
19 symbolsclose-conn
Close a connection.
close
Permanently close a server and all its connections.
connect-tls
Create an outbound TLS client connection (mbedTLS).
connect
Create an outbound TCP client connection.
connections
List active connections for a server.
info
Get info about a server.
list
List all registered servers.
on-close
Register close callback on a connection.
on-data
Register raw data callback on a connection.
on-line
Register line-mode callback on a connection.
recv
Read available data from a connection.
send
Send data on a connection. [net/send conn data]
start
Restart a stopped server.
starttls
Upgrade an established plaintext client connection to TLS (STARTTLS), after the protocol's cleartext negotiation has already happened. From this point the connection uses mbedTLS transparently and its existing net/on-data/net/on-line/net/on-close callbacks stay live.
stop
Stop a server (stop accepting, keep resource).
tcp
Create a TCP server. [net/tcp port on-connect-closure]
tls-error
The recorded TLS failure reason for a connection (connect, certificate verification, or handshake), or nil when there is none.
udp-send
Send UDP datagram. [net/udp-send server addr port data]
udp
Create a UDP server. [net/udp port on-data-closure]
os
16 symbolsargs
Return the script's command-line arguments as a vector of strings.
chdir
Change the process working directory to path. Returns nil.
cpu-count
Return the number of logical CPUs available to the process. Used to size worker pools (os/run-async, http/serve-cluster).
cwd
Get current working directory.
env
Get an environment variable by name.
exit
Terminate the process with the given exit code.
kill
Send a signal by name to a process id. Accepts the catchable os/on-signal set plus :sigkill and :sigstop (send-only — the kernel never delivers those to a handler).
lines
Run command with args, return stdout split into lines.
off-signal
Remove every handler registered for a signal and return how many were removed. When the last handler for a signal goes, the signal is unblocked and its default disposition is restored; when the last handler overall goes, the signalfd is torn down so [vwait] can exit.
on-signal
Register a handler closure for an OS signal. Catchable set: :sigint, :sigterm, :sighup, :sigquit, :sigusr1, :sigusr2, :sigalrm — names are keywords or strings, case-insensitive, with or without the sig prefix. Handlers fire only while the event loop pumps ([vwait], [update], REPL, servers).
pid
Return the current process id.
run-async
Run a command off-thread on the shared per-runtime executor pool and return a Future resolving to the same %{ :status :stdout :stderr } map that os/run returns. Output is buffered and delivered at completion; a hung command pins a pool thread, so use os/run for a simpler blocking call.
run
Run command with args, return %{ status N stdout "..." stderr "..." }.
shell
Run shell command string, return %{ status N stdout "..." stderr "..." }.
signals
Return the list of signal names that can be handled with os/on-signal. The send-only signals sigkill and sigstop are not included.
status
Run command with args, return exit code as number.
pg
15 symbolsbegin
Begin a transaction. Returns a Future.
close
Close a PostgreSQL client (sends Terminate, rejects pending requests). Returns :ok.
columns
Get column info for a table. Returns a Future of %{ :name :type :not_null :default } maps.
commit
Commit the open transaction. Returns a Future.
connect
Create a PostgreSQL client (lazy dial on first command).
exec
Execute SQL (CREATE/INSERT/UPDATE/DELETE). Returns a Future of %{ :tag :command :rows }.
info
Get client state: %{ :state :host :port :user :database :sslmode :ssl :txn :pending :pid :server-version }.
on-notice
Register a callback for server notices/warnings. Returns nil.
on-notify
Register a callback for LISTEN/NOTIFY pushes. Returns nil.
query-one
Query the first row as a map, or nil. Returns a Future.
query-seq
Query rows as a cursor-backed lazy sequence (decode-on-iteration). Returns a Future.
query
Query rows as a vector of maps keyed by column name. Returns a Future.
rollback
Roll back the open transaction. Returns a Future.
scalar
Query the first column of the first row as a single value, or nil. Returns a Future.
tables
List user table names (excludes pg_catalog and information_schema). Returns a Future of strings.
pkg
13 symbolsavailable
List packages available in the current registry.
fetch
Download a package tarball without installing.
fund-info
Return the funding-relevant fields of a package's manifest for an "owner/name" id. Status defaults to "standard" when the manifest has none; :raised-usd is the last published value — query the escrow backend for live progress.
get-registry
Return the current package registry URL.
info
Show package detail from the registry. Reads package.dft without downloading the tarball.
install-bytes
Install a package from raw gzip+tar bytes. Synchronous; never touches the network.
install
Install a package by owner/name id. Fetches synchronously from the registry and installs under .deft/packages////.
list-paths
Return the configured package search roots.
list
List packages across all configured search roots (prelude :pkgs).
mount
Register a mount for an installed package, wiring its export path to a directory for import resolution.
read-manifest
Read and validate a package.dft manifest from a directory.
set-registry
Set the package registry URL. Pass nil to reset to local virt-pkg.
uninstall
Uninstall a package by owner/name id from the install root.
pub
5 symbolsre
11 symbolscaptures
Extract all capture groups as a map (positional + named)
clear-cache
Free all compiled regex patterns from the internal cache
escape
Escape regex metacharacters in a string
find-all
Find all non-overlapping regex matches
find-at
Find first regex match starting at byte offset
find
Find first regex match, returning map with match/start/end/groups or nil
match
Test if string matches a PCRE2 regex pattern
replace-all
Replace all regex matches (supports $1, ${name} backrefs)
replace
Replace first regex match (supports $1, ${name} backrefs)
scan-first
Find the earliest anchored match across multiple patterns at offset. Returns %{ index N match S start N end N groups ... } or nil
split
Split string by regex pattern
result
3 symbolsrpc
1 symbolsruntime
12 symbolscreate
Create a named child runtime. Returns the name on success.
current
Return the current runtime's id.
destroy
Destroy a named child runtime. Returns :ok or :error.
eval-async
Queue source on a child runtime's loop thread; returns a request id immediately.
eval
Evaluate source code in a named runtime.
exists?
Check if a named child runtime exists.
list-defs
List definitions in a child runtime's current namespace. Faster than runtime/eval "[info/defs]" — avoids the source-string round-trip.
list
List all child runtime names.
mem-stats
Return process & VM memory snapshot as a map.
on-shutdown
Register a zero-arg callable to be invoked at VM shutdown, before any state is torn down. Used to deterministically close long-lived native resources (DB handles, sockets) that would otherwise rely on GC finalizers.
run
Run a .dft file in a named runtime.
spawn
Spawn a .dft file in a child runtime on a dedicated OS thread (non-blocking).
schema
2 symbolsfrom-value
Validate and convert a value into a real %Type{...} tagged map. Missing fields are filled from :default, fields with :coerce true are converted ("8080" → 8080, "true" → true, "open" → :open), :many values are wrapped into vectors, and nested :Type/:of values are converted recursively. This is the entry point for turning parsed Deft/JSON/YAML/XML data into typed values.
validate
Check a value (a plain or tagged map) against a deftype schema. Deep and recursive: nested :Type fields and :of element types are checked too.
sqlite
22 symbolsbegin-async
Async twin of sqlite/begin — start a transaction off-thread. Returns a Future resolving to true.
begin
Begin a transaction.
close
Close a database handle.
columns-async
Async twin of sqlite/columns — fetch column metadata for a table off-thread via PRAGMA table_info. Returns a Future of row maps.
columns
Get column info for a table.
commit-async
Async twin of sqlite/commit — commit the open transaction off-thread. Returns a Future resolving to true.
commit
Commit a transaction.
exec-async
Async twin of sqlite/exec — run DDL/DML off-thread on the handle's dedicated executor. Returns a Future.
exec
Execute SQL (CREATE/INSERT/UPDATE/DELETE). Returns rows changed.
open
Open a SQLite database. Use ":memory:" for in-memory.
query-async
Async twin of sqlite/query — run a SELECT off-thread on the handle's executor. Returns a Future of materialized row maps.
query-cols-async
Async twin of sqlite/query-cols — return a query's result-set column names in SELECT order off-thread, without executing the statement. Returns a Future.
query-cols
Return a query's result-set column names in SELECT order, without executing the statement. Result rows are maps (hash-ordered), so keys of a row is unreliable for headers — use this to render them in the right order.
query-one-async
Async twin of sqlite/query-one — fetch the first matching row off-thread. Returns a Future of a row map or nil.
query-one
Query first row as a map, or nil.
query
Query rows as a lazy sequence of maps (cursor-backed).
rollback-async
Async twin of sqlite/rollback — roll back the open transaction off-thread. Returns a Future resolving to true.
rollback
Rollback a transaction.
scalar-async
Async twin of sqlite/scalar — read the first column of the first row off-thread. Returns a Future of a value or nil.
scalar
Query single scalar value from first column of first row.
tables-async
Async twin of sqlite/tables — list table names off-thread. Returns a Future of strings.
tables
List all table names.
task
6 symbolsfuture-ready?
Returns true if the future is settled (resolved or rejected), without blocking.
stream-close
Signal that the consumer is done reading.
stream-collect
Collect all remaining stream values into a list.
stream-done?
Returns true if the stream producer has finished (no more values will arrive).
stream-next
Read the next value from a task stream. Returns nil when done.
stream-try-next
Non-blocking read from a task stream. Returns nil immediately if no value is ready.
test
3 symbolsfilter
Set a substring filter for which tests run. Matches suite name, test name, or the "::" key.
mode
Enable or disable test mode on the current VM. When enabled, defsuite/deftest blocks execute; otherwise they are no-ops.
results
Return structured per-test results collected since test mode was enabled. Call after running a test file.
theme
7 symbolscurrent
The ACTIVE workspace theme as the full map. Identical to [tui/theme] and [draw/theme ctx] in TUI hosts.
get
Read a value from a loaded theme map by a variadic path of section/key keywords.
list
List every theme file visible through the standard theme directory chain, as sorted file stems.
load
Load a theme file from disk and return its full parsed map.
save
Write a theme map back to disk as a canonical theme .dft file.
set
Return a new theme map with a value deep-set at a variadic path. The original map is never mutated — rebind the result.
unset
Return a new theme map with the key at a variadic path removed. The original map is never mutated — rebind the result.
uuid
4 symbolsnil
Return the nil UUID — the all-zero sentinel defined by RFC 4122, used to represent "no UUID" in the same way nil represents "no value".
v4
Generate a random version-4 UUID (RFC 4122 §4.4). All 122 random bits come from the OS CSPRNG — no timestamp component, no predictability across calls.
v7
Generate a time-ordered version-7 UUID (RFC 9562 §5.7). The first 48 bits are the unix-epoch millisecond timestamp; the remaining 74 bits are random from the OS CSPRNG.
valid?
Test whether a value is a well-formed canonical UUID string. Accepts lowercase and uppercase hex; any version/variant nibble passes. Non-string values return false (no error).
vfs
3 symbolslist
All active VFS mounts (prelude-seeded and runtime-registered) as a map of name → parsed spec. The global mount table is authoritative — this includes mounts inherited from the workspace prelude, visible to every runtime in the process.
mount
Register (or replace) a VFS mount. After mounting, fs/* calls whose leading path segment(s) name the mount route to its driver instead of the native filesystem. Publishes a change event on the "vfs" pub/sub topic.
unmount
Remove a VFS mount. Paths under the name fall back to native resolution. Publishes a change event on the "vfs" pub/sub topic with :value nil.
vg
3 symbolsworker
5 symbolshandlers
List the @worker-marked handler names a worker exposes.
jobs
Number of jobs queued on a worker's mailboxes, or the sum over a pool.
send
Dispatch a job to a worker or pool and return a Future for the handler's result. Handlers are the @worker-marked defs in the worker file.
stop
Stop a worker or pool: stop accepting jobs, drain queued ones (their futures/streams complete normally), join the worker thread(s), and free the child runtime(s).
stream
Streaming variant of worker/send: yield inside the handler pushes values incrementally onto the returned stream instead of producing one final result.
xml
6 symbolsescape
Escape XML special characters as entity references so arbitrary text can be embedded in markup.
load
Read an XML file from disk and parse it into a Deft value.
parse
Parse an XML document string into a Deft value. Compact by default; %{ :compact false } (or :tree) returns document-order tree nodes.
pretty
Convert a Deft value to indented XML. Accepts the same shapes and applies the same rules as xml/stringify.
stringify
Convert a Deft value (compact or tree shape) to a compact XML element string.
unescape
Expand predefined and numeric character references in a string.
yaml
3 symbolsTUI 201 symbols
Host APIs for panels, drawing, audio, surfaces, and scenes in retro / retra / hydra.
The editor/* namespace now ships with the editor app:
Editor help.
audio
14 symbolsavailable?
True when the host was compiled with SDL3 audio (retro, hydra); always false on the ANSI host (retra), where the namespace compiles without libSDL3 and every other audio/* call returns a clean %Err.
beep
Play a quick sine beep — a convenience wrapper over audio/tone with the default sine wave and envelope.
pause
Pause the shared SDL audio device — every voice and push stream bound to it stops advancing until audio/resume.
play
Play a WAV sound effect on the shared SDL audio device. Files are decoded once and cached by path; concurrent voices are mixed by SDL.
quit
Close the shared audio device and free every cached WAV, voice, and push stream. The next audio/* call re-opens the device lazily.
resume
Resume a device paused with audio/pause, continuing all voices and push streams where they stopped. The device is also resumed automatically at open time.
stop
Stop a playing voice or push stream, or everything at once.
stream-clear
Drop all PCM queued in a push stream without destroying the stream — the seek/stop flush.
stream-close
Destroy a push stream and release its device binding.
stream-open
Open a raw PCM push stream for continuous audio (the video-soundtrack path). Samples are resampled and mixed into the shared device spec (S16, 44.1 kHz stereo).
stream-push
Append interleaved PCM bytes to a push stream. SDL copies the data before returning, so GC-owned Deft strings are safe.
stream-queued
Bytes of PCM still queued in a push stream — the backpressure gate before pushing more.
tone
Synthesize and play a tone (stereo S16 at 44.1 kHz) through the shared playback device.
volume
Get or set the master playback gain. The device-wide gain scales every voice and push stream (individual :volume values still apply on top).
clipboard
2 symbolscolor
17 symbolsalpha
Get or set a color's alpha channel (0-255). With one argument returns the current alpha as a number; with two returns a new color with the alpha set.
complement
Rotate the hue 180° — the complementary color. Saturation, lightness and alpha are preserved.
contrast-text
Pick whichever of two candidate colors contrasts more with a background, using the WCAG contrast ratio. Defaults to black vs white — the standard "readable text on this background" decision.
darken
Darken a color in HSL space by amount (0-1, default 0.1). Hue, saturation and alpha are preserved; lightness clamps at black.
desaturate
Decrease saturation in HSL space by amount (0-1, default 0.1). Lightness, hue and alpha are preserved.
fade
Multiply a color's alpha by factor (0-1, default 0.5). RGB is unchanged; a fully transparent result stays transparent.
grayscale
Fully desaturate a color (saturation = 0). Lightness and alpha are preserved.
hex
Normalize any color form to "#rrggbb"
invert
Invert the RGB components (1 - component). Alpha is preserved.
lighten
Lighten a color in HSL space by amount (0-1, default 0.1). Hue, saturation and alpha are preserved; lightness clamps at white.
luminance
WCAG relative luminance of a color: 0 for black, 1 for white, gamma-correct per the sRGB spec. Use it to pick readable foregrounds — or call color/contrast-text directly.
mix
Blend two colors linearly: t 0 = first color, 1 = second (default 0.5). Alpha blends too.
names
The named color palette as %{ "name" "#hex" }
parse
Parse any color form (hex/named/ANSI-256/%{r g b a}) → %{ :r :g :b :a } or nil
rgb
Build a color map from components: [color/rgb r g b ?a] (0-255)
rotate-hue
Rotate the hue by degrees (any sign, wraps at 360). Saturation, lightness and alpha are preserved.
saturate
Increase saturation in HSL space by amount (0-1, default 0.1). Alpha is preserved. Achromatic (gray) input is returned unchanged — there is no hue to boost, and boosting toward hue 0 would arbitrarily tint it red.
draw
26 symbolsbezier
Pixel-mode cubic Bezier curve. Args: ctx x0 y0 x1 y1 x2 y2 x3 y3 color [width=1] [segments=24].
bounds
Get component bounds as %{ x y width height }.
canvas
Create a retained pixel-space canvas element (a draw/* target, rendered as a per-app layer)
cell
Set a single cell. Args: ctx col row char [fg] [bg]
circle-outline
Circle outline: [draw/circle-outline $target cx cy r $color ?width] — polymorphic target
circle
Filled circle: [draw/circle $target cx cy r $color] — polymorphic target (panel DrawContext, surface id, canvas)
clear
Pixel-mode clear background. Args: ctx color
fill-bg
Fill component bounds with background color. Args: ctx color-string
fill-cells
Fill a cell rect with one char: [draw/fill-cells $ctx col row w h char fg bg] (panel contexts)
fill-rect
Pixel-mode filled rectangle. Args: ctx x y w h color
frame
Replace a surface's whole staging frame with RGBA bytes: [draw/frame $sid bytes w h] (the decode/video fast path)
image-dims
Get image dimensions as %{ width N height N }. Safe from any thread — uses the vendored image codecs, no GL.
image-preview
Render image preview using half-block characters. Args: ctx col row width height path
image
Draw an image — unified blit for panels and surfaces. GL hosts render a hi-res texture; ANSI hosts fall back to half-block cells.
line
Pixel-mode line. Args: ctx x1 y1 x2 y2 color [width]
path
Pixel-mode polyline. Args: ctx points color [width=1] [closed=false]. points is a vector of [x y] pairs.
pixel
Set one pixel: [draw/pixel $target x y $color ?mode] — surface targets accept raster ops (:alpha :add :mult :xor :and :or)
pop-clip
Pop the current clip rect, restoring the previous one (or no clipping if the stack is empty).
push-clip
Push a clip rect in local component coordinates, intersecting with any existing clip. Subsequent draw calls are scissored to the intersection. Must be paired with a matching draw/pop-clip.
rect
Pixel-mode rectangle outline. Args: ctx x y w h color
scrollbar
Draw a vertical scrollbar on the right edge. Args: ctx scroll-pos total-lines visible-lines [col-offset]
set-bounds
Reposition canvas (cell coords)
text-fit
Put text truncated or space-padded to exactly width cells at (col, row). Unlike [draw/text] with a Deft-built padded string, the padding happens in the cell grid — no string allocation per row/cell per frame.
text-px
Pixel-mode text at (x, y). Args: ctx x y text [color]. Coords are component-local pixels.
text
Put text at (col, row). Args: ctx col row text [fg] [bg]
theme
Get theme colors as a map. Args: ctx
gl
17 symbolsbg
Set scene clear/background color
clear
Clear 3D scene vertex buffer
depth
Enable/disable depth testing
identity
Reset model matrix to identity
line
Push 3D line: x0 y0 z0 x1 y1 z1 color [width]
lookat
Set view matrix: eye-xyz center-xyz up-xyz
perspective
Set perspective projection: fov aspect near far
present
Mark scene+canvas dirty for rendering
quad
Push quad: 4×(x y z) color
reset
Clear the calling app's 3D scene vertex buffer for the next frame. The background color (gl/bg) and the projection/view/model matrices are untouched.
rotate-x
Rotate model around X axis (degrees)
rotate-y
Rotate model around Y axis (degrees)
rotate-z
Rotate model around Z axis (degrees)
scale
Scale model matrix: sx sy sz
scene
Attach a 3D scene to a canvas element
translate
Multiply translation into model matrix
triangle
Push triangle: x0 y0 z0 x1 y1 z1 x2 y2 z2 color
scene
9 symbolsadd
Add a free-floating node to the workspace world layer. World-layer nodes live above the panel tree and are anchored to absolute screen coordinates. They are GL-only; ANSI builds ignore the call (returns 0).
clear
Remove every world-layer node.
count
Number of nodes currently in the world layer.
hit-test
Hit-test the calling app's world layer at panel-local coords (x, y). Returns the id of the topmost visible node containing the point, or 0 if none. Coords are in pixels with origin at the panel's content top-left.
node-get
Return a map describing a world-layer node, or nil if no node has that id.
node-set
Mutate a world-layer node in place. The first argument is the node id returned by scene/add. Remaining arguments are keyword/value pairs.
remove
Remove a world-layer node by id. Returns true on success.
select
Select a world-layer node for direct manipulation. Halo handles will be drawn around it. Pass 0 to clear the selection. Returns true on success.
selected
Return the id of the currently selected world-layer node, or 0 if nothing is selected.
surface
11 symbolsclose
Close a surface
events
Drain pending event maps (canonical shapes)
flush
Present the staged frame (low-level path; the Surface protocol host flushes automatically)
keep-alive
Keep the process alive after all surfaces close
list
List open surfaces → %{ :id :title :w :h :closed }
open
Open an SDL surface: [surface/open %{:title "app" :w 640 :h 480}] → surface id (own OS window on hydra, in-panel virtual surface on retro; errors on retra)
quit
Close the caller's surfaces and fire the host quit hook (hydra exits the instance; retro closes the panel)
read
Snapshot the staging frame → %{ :data w*h*4 RGBA bytes :w :h } (tests/screenshots)
resize
Resize a surface's staging buffer and window
set-title
Set the window title of a surface
size
Current logical size → %{ :w :h }
term
11 symbolsdispose
Tear down the session, killing the child if still alive.
draw
Render the session's screen into the given draw context. Call from a Deft draw method: [term/draw $ctx $self~handle]. The session is auto-resized to fill the bounds. Substitutes the active theme's fg/bg for VT default colors. Also registers the session as 'watched' so the app thread re-renders when new output arrives.
exited?
Returns nil while running, or the exit code (number) if the child has exited.
forward-event
Forward the InputEvent currently being dispatched to the session. Call from a Deft on-event method: [term/forward-event $self~handle]. Returns true if the event was consumed.
paste
Paste text (wrapped in bracketed-paste markers when the shell enabled them).
resize
Resize the PTY window. Sends SIGWINCH to the foreground process group.
scroll
Scroll the viewport by delta lines (negative = back).
snapshot-version
Current snapshot version. Increases each time the screen is updated by the reader thread.
spawn
Spawn a PTY-backed terminal session. Optional opts map: %{cmd cols rows cwd argv term}. Returns a session handle (native resource) or nil.
title
Latest OSC 0/2 title set by the running program.
write
Write bytes/string to the PTY (keystrokes, ANSI escapes).
tui
94 symbolsadd-to-group
Add a new empty panel as a child inside a group. The new panel appears alongside the group's existing children.
adopt
Reuse a docked (minimized) app instance by rebinding its thread onto the given panel, displacing its current app — used to switch rather than spawn.
app-threads
List active app threads with per-app metrics. Returns a list of maps, one per running app thread:
auto-tag
Auto-assign a unique instance tag on the calling panel. Returns the assigned tag string.
backend
The host backend as a keyword — the canonical capability probe. [capabilities]'s :backend carries the same value.
badge
Get or set a panel's workspace badge level — the colored dot in the [● name] badge shown when a panel is minimized (on group title bars and the bottom workspace taskbar).
begin-scene-drag
Begin a cross-panel scene-node drag from the calling app. Pass a map describing the node to drag (e.g. %{ :kind :text :text "hello" :color "#ff0" }). The main thread renders a semi-transparent ghost that follows the cursor; on mouse-up the target panel receives a :scene-drop event and the source receives :scene-drag-end with :dropped and :same-panel flags. Returns true if the drag was accepted (always true on GL backends, false on ANSI). GL-only.
cell->px
Convert cell coordinates to a pixel point in workspace space.
cell-size
Return the current font cell size in pixels as @{w h}. Useful for converting cell-coord mouse events to panel-local pixels for scene/hit-test. Returns @{0 0} on cell-only backends (ANSI).
clear-focus
Empty the calling panel's widget-focus slot. No widget receives keyboard events exclusively afterward — the panel returns to browse mode.
close
Close a panel (focused if no arg, or by ID).
cycle-focus
Cycle widget focus to the next/previous Focusable widget in tab-index order. The framework's default action when nothing consumes a Tab keypress.
dispatch-tree-event
Dispatch the current input event to a widget tree (target+bubble): the focused widget or hit-tested leaf consumes first, leftovers fall through. Legacy — tui/set-widget-tree panels must NOT call this (double-dispatch).
dock/anchor
Re-attach a floating dock back onto its edge (the ↙ button does the same). The content size survives the transition.
dock/blur
Return keyboard focus from the dock to the panel content (clicking the panel content does this implicitly).
dock/close
Close the calling panel's dock region; the app content expands back over the carved area. Fires the app's dock-close method.
dock/float
Detach the dock from its anchor edge into a workspace-level floating frame — draggable by its title bar, resizable from its bottom/right edges. Re-attach with tui/dock/anchor.
dock/focus
Give the dock keyboard focus: key and text events route to the app's dock-event method with :dock true, and the panel's widget tree / on-key path is suspended until tui/dock/blur or a click on the panel content.
dock/focused?
True when the calling panel's dock holds keyboard focus.
dock/open
Open (or re-anchor) the calling panel's dock — an app-owned tool region anchored to a panel edge, OpenOffice-style. One dock per panel; the app must implement the dock-draw Panel method (and receives input via dock-event).
dock/state
The calling panel's dock geometry, or nil when no dock is open.
dock/update
Update the open dock's spec — any subset of :edge / :size / :title, using the same map as tui/dock/open.
dock-back
Dock a popped-out panel back into the workspace grid (split off the focused panel). Counterpart of tui/pop-out.
draw-tree
Draw a widget tree into a DrawContext (leaf tagged map, container with children, or plain map). Walks the tree invoking each draw method.
eval-file
Read a file and eval its contents in a target panel's runtime.
eval
Eval source text in a target panel's runtime.
file-save
Request the save-as dialog for the focused panel. Optional arg: default filename.
find-panel
Find a panel by its string tag. Returns panel ID or 0.
focus-down
Move focus to the panel below.
focus-id
Focus panel by panel ID.
focus-left
Move focus to the left panel.
focus-right
Move focus to the right panel.
focus-up
Move focus to the panel above.
focus-widget
Set the calling panel's authoritative widget-focus slot to the widget with the given :id. The focused widget receives keyboard events exclusively.
focus
Focus panel by 1-based index.
focused-panel
Tag string of the currently focused panel, or nil if no tag is set.
focused-tag
Alias for tui/focused-panel — returns the tag string of the currently focused panel.
focused-widget-id
Return the :id of the calling panel's currently focused widget, or nil if no widget holds focus.
font-list
Enumerate the monospaced font families available to tui/set-font — display names, sorted case-insensitively.
font
The currently applied font — the file path behind the workspace cell grid and the pixel size it was rasterized at.
get-child-value
Get the current value of a mounted child widget by child index.
get
Get workspace state value.
gl?
True on a GL host, where pixel draw commands, textures, and embedded surface windows render at native resolution. Use it to gate pixel-only features such as 3D scenes and SDL surfaces.
groups
List all panel groups in the workspace.
hover-cell
Panel-local cell under the pointer as @[col row], using the same content-relative frame as mouse events (the title bar row is excluded). nil when the pointer is outside the calling panel or no hover has been recorded.
input-value
Get text from a text input component.
launch
Launch a Deft app in a panel's own thread.
layer-set
Set per-panel display attributes. Honored by both the ANSI cell-blit path and the GL pixel path.
menu-set
Set the app menu bar from a map of menu-name → list of %MenuItem{}.
menu-update
Re-evaluate the panel's get-menu function and update the menu bar.
mount-widget
Mount a Deft widget as an event-handling child of a panel's component tree. Unlike tui/mount (mounts a whole component instance as panel content), this attaches a single widget that participates in target-phase dispatch.
mount
Mount a Deft component instance on a panel.
panel-app
Set app name for a panel.
panel-box
Set a box component as panel content. Args: id, optional :border, optional title string.
panel-child-label
Add a label child to panel's component tree.
panel-count
Number of leaf panels.
panel-input
Add a text input child to panel's component tree. Args: id [placeholder].
panel-label
Set a label component as panel content.
panel-layout
Set layout direction for panel's component root.
panel-status-bar
Add a status bar child to panel's component tree. Args: id, left-text [right-text].
panel-tag
Get the tag string of a panel. Accepts a numeric panel ID or a string tag to identify the panel.
panels
List all leaf panel IDs.
pie-update
Re-evaluate the calling panel's get-pie function and store its result as the app pie. No-op when get-pie is not defined. Mirror of tui/menu-update.
pop-out
Pop a panel out into its own OS window. The app keeps its runtime, focus, taskbar identity, and panel id; dock it back with tui/dock-back or the window's ↙ button.
px->cell
Convert a pixel point in workspace space to cell coordinates (floored).
resize
Resize focused panel by delta (-1.0 to 1.0).
run
Run an imported Deftlet module in the current panel. Calls get-panel and mounts the result.
save
Save the current workspace layout as a declarative spec to ~/.deft/workspaces/.dft.
self
Return the calling panel's own ID (0 in CLI mode).
set-child-text
Set the text content of a mounted child widget via its Editable.set-text protocol method.
set-child-value
Replace the value of a mounted child widget directly (no protocol method call). The new value must be a tagged map.
set-font
Apply a monospaced font live — the workspace grid, popped panel windows, and surface text all re-render at the chosen face and size on the next host frame.
set-margins
Set selection margins for the calling panel. Insets for workspace text selection: left, right, top, bottom.
set-menu
Set app menu bar from a map of menu-name → list of %MenuItem{}.
set-pie
Set the calling app's pie menu — the radial command menu opened from the workspace pie hub. Mirror of tui/set-menu.
set-theme
Apply one of the loaded themes by display name (e.g. "Dracula"). The switch is deferred to the host main loop.
set-widget-tree
Register the calling panel's widget-tree ref for framework-driven target-phase dispatch. The framework runs the focused-widget / hit-test target phase *before* the panel's typed event methods, turning it into a pure bubble handler.
set
Set workspace state value.
shelf-close
Close the shelf.
shelf-launch
Launch an app in the shelf.
shelf-open
Open the shelf. Optional arg: edge keyword (:top :bottom :left :right).
shelf-size
Set shelf size in cells.
shelf-terminal
Launch a terminal in the shelf.
shelf-toggle
Toggle the shelf panel open/closed.
shutdown
Shut down the app in a panel.
split
Split focused panel. Args: :vertical or :horizontal, optional panel ID.
state
Return the live component state of the current panel.
swap
Swap contents of two panels.
tag
Set a string tag on the calling panel.
terminal
Launch a terminal emulator in a panel.
theme-reload
Rescan the theme directories (project overrides, prelude :themes :dir, user home, stdext defaults, legacy ./themes/) and rebuild the loaded theme set, re-applying the currently active theme by name. The reload is deferred to the host main loop.
theme
Return the FULL current workspace theme as a map. No parameters required.
tooltip
Show a tooltip on the far right of the workspace bar (the bottom taskbar). The same slot also displays hover help for panel title-bar elements — the right-side buttons show "minimise" / "maximise" / "restore" / "close", the panel-name area shows "panel menu", an open panel-name palette's items show "show config" / "edit source" / "pop out to window" / "app help", and hovering a panel's title icon shows the app name and source path. Hover help takes precedence over the app-set text for as long as the hover lasts.
zoom
Toggle zoom on focused panel.