# Stdlib Stdlib functions are the built-in functions registered by the runtime. This page is a catalogue organised by namespace. See [Lazy Sequences](lazy-sequences), [Transducers](transducers), and [Collections](collections) for in-depth treatment of the collection operations. ## How To Read This Page Each entry lists the stdlib function name, argument shape, and brief purpose. The canonical form for invocation depends on context — see [Syntax and Style](syntax-and-style). Quick rules: - Bare names work at statement position for top-level calls: `echo $x`, `incr i`. - Postfix `$var(call)` works for single-arg calls on a variable: `$x(len)`, `$xs(first)`. - Prefix `[name args]` is canonical and required inside larger expressions or for slash-namespaced calls: `[fs/read "path"]`, `[sqlite/query $db "sql"]`. ## Bare (no namespace) ### I/O | Function | Purpose | |---|---| | `echo $args...` | Print values to stdout + newline | | `puts ?target $value` | Write a line to a channel (default `:stdout`); strings raw, other values formatted like `echo` | | `gets ?target` | Read a line from a channel (default `:stdin`); nil at EOF | | `open "path" ?mode` | Open a file as an opaque `%Chan` (`"r"`/`"w"`/`"a"`/`"rw"`); `%Err` on failure | | `close $chan` | Close a channel; true if this call closed it, false if already closed | | `log $args...` | Append values to `/deft.log` (bypasses capture) | Channel targets are `%Chan` handles from `open` or the `:stdin` / `:stdout` / `:stderr` keywords — raw file descriptors are never values. ### Math (general-purpose) | Function | Purpose | |---|---| | `abs n` | Absolute value | | `floor n`, `ceil n`, `round n` | Rounding | | `min a b`, `max a b` | Ordering | | `clamp n lo hi` | Clamp to range | | `random`, `random n` | Random integer | | `mod a b` | Modulo | | `int x` | Coerce to integer | ### Strings String indexing is **codepoint-based**: `len` counts characters, `$s(a..b)` slicing, `nth`, `char-at`, and `index-of` all operate on whole characters — slicing can never land mid-character. Internally strings are UTF-8 byte arrays (and binary-safe); `bytes/len` / `bytes/slice` / `byte-at` give raw byte access for binary data. Display width (East Asian Wide glyphs take 2 cells) is a separate concern — see the layout verbs below. Full story: [String Representation](string-representation). | Function | Purpose | |---|---| | `str $xs...` | Concatenate values to a string | | `format fmt args...` | Printf-style formatting (`%d %x %f %s ...` with flags/width/precision) | | `upper s`, `lower s` | Case | | `trim s` | Strip whitespace | | `split s sep` | Split into list (empty sep → characters) | | `join xs sep` | Join list into string | | `replace s old new` | Replace all | | `replace-first s old new` | Replace first occurrence | | `starts-with? s prefix`, `ends-with? s suffix` | Predicates | | `repeat s n` | Repeat | | `lines s` | Split on newlines | | `words s` | Split on whitespace | | `contains s substr` | Substring check | | `reverse s` | Reverse by codepoint | | `char-at s i` | Character at codepoint index | | `index-of s sub` | Find substring (codepoint index) | | `chars/count s`, `chars/slice s a b` | Explicit character count / range | **Layout (display width)** — use these, not `len`, when positioning text in a terminal-cell UI: | Function | Purpose | |---|---| | `width s` | Display width in cells (East Asian Wide = 2) | | `cells s` | Per-character `@{char-index char width}` triples | | `truncate-width s w ?tail` | Longest prefix fitting `w` cells (optional "…" tail) | | `pad-width-left/right s w ?fill` | Pad to display width | | `wrap-width s w` | Word wrap at display width → list of lines | | `pad-left s n ch`, `pad-right s n ch` | Pad to a character count | **Bytes (binary data)** — for `fs/read` bodies, crypto, and protocol offsets, where chunk boundaries must not drift: | Function | Purpose | |---|---| | `bytes/len s` | Byte length | | `bytes/slice s a b` | Raw byte range | | `byte-at s i` | Byte value (0-255) | ### Types and predicates | Function | Purpose | |---|---| | `type x` | Type name as string | | `is? type-name x` | Type check by name (string) | | `nil? x` | Nil check | | `future? x` | Future check | | `empty? xs` | Empty check | | `num x` | Coerce to number | | `keyword x` | Coerce to keyword | | `meta fn key` | Read metadata | | `with-meta val meta` | Attach metadata | ### Result type | Function | Purpose | |---|---| | `ok value` | Construct `%Ok{ :value value }` | | `err message` | Construct `%Err{ :message message }` | | `ok? x`, `err? x` | Result predicates | | `unwrap result ?default` | Extract value or default | | `throw value` | Raise an error | ### Atoms | Function | Purpose | |---|---| | `atom value` | Create atom | | `deref atm` | Read current value | | `atom? x` | Atom predicate | | `reset! atm value` | Set value | | `swap! atm f args...` | Apply f to current value, store | | `add-watch atm key fn` | Add watcher | | `remove-watch atm key` | Remove watcher | ### Lists | Function | Purpose | |---|---| | `len xs` | Length (works on lists, maps, sets, strings) | | `first xs`, `last xs` | Edges | | `rest xs` | All but first | | `nth xs i` | Index | | `slice xs start end` | Sublist/substring | | `reverse xs` | Reversed | | `range start end step?` | Numeric list | | `in? xs v` | Membership (`v in? xs` also works) | | `append xs v` | Pure-functional append | | `flatten xs` | Concatenate nested lists | | `sort xs`, `sort xs cmp` | Sort | | `unique xs` | De-duplicate | | `take xs n`, `drop xs n` | First/remaining N (lazy) | | `zip as bs` | Pair up | | `from-entries pairs` | Build a map | | `set-nth xs i v`, `insert-nth xs i v`, `remove-nth xs i` | Index ops | ### Maps | Function | Purpose | |---|---| | `keys m` | Keys as list | | `values m` | Values as list | | `entries m` | Pairs as list | | `merge m1 m2 ...` | Merge maps | | `get m key default?` | Lookup | | `assoc m k v` | Add/overwrite | | `dissoc m k` | Remove | | `tag m keyword` | Tagged map | | `untag m` | Strip tag | | `assoc-in m path v` | Nested assoc | | `get-in m path default?` | Nested lookup | ### Arrays (mutable) | Function | Purpose | |---|---| | `array values...` | Create mutable array | | `array-of n v` | Pre-filled | | `aget arr i`, `aset arr i v` | Index access | ### Sets | Function | Purpose | |---|---| | `union a b`, `intersection a b`, `difference a b` | Set ops | | `subset? a b`, `superset? a b` | Relation predicates | ### Higher-order functions (lazy) | Function | Returns | Notes | |---|---|---| | `map xs f` / `map f` | Lazy seq / transducer | | | `filter xs pred?` / `filter pred?` | Lazy seq / transducer | | | `take xs n` / `take n` | Lazy seq / transducer | | | `drop xs n` / `drop n` | Lazy seq / transducer | | | `mapcat xs f` / `mapcat f` | Lazy seq / transducer | | | `reduce xs init f` | Folded value | | | `each xs f` | nil | Side-effecting walk | | `find xs pred?` | First match or nil | | | `any? xs pred?`, `all? xs pred?` | Boolean | | | `collect lazy-seq` | List | Realise lazy seq | | `group xs f` | Map | Partition by f | | `count xs` | Number | Length after realisation | ### Transducers | Function | Purpose | |---|---| | `comp xf1 xf2 ...` | Compose transducers | | `transduce xf rfn init xs` | Fold via transducer | | `into target xf xs` | Conj into collection | | `completing f` | Wrap as `%Reducer` | | `reduced x`, `reduced? x`, `unreduced x` | Early-termination protocol | ### Utility | Function | Purpose | |---|---| | `identity x` | Returns x | | `apply f args` | Apply function to list | | `curry f args...` | Partial application — returns a closure awaiting the rest | | `eval code-string` | Evaluate a string | | `reload "path"` | Reload a module | | `pretty x`, `pretty-str x indent?` | Pretty-print | ## Namespaced Stdlib functions ### `math/` `math/sqrt`, `math/pow`, `math/sum`, `math/avg`, `math/sin`, `math/cos`, `math/tan`, `math/asin`, `math/acos`, `math/atan`, `math/atan2`, `math/exp`, `math/ln`, `math/log10`, `math/log2`, `math/sign`, `math/trunc`, `math/hypot`, `math/lerp`, `math/random-range`, `math/pi`, `math/euler`. ### `chars/` Single-character classification: `chars/word?`, `chars/digit?`, `chars/alpha?`, `chars/upper?`, `chars/lower?`, `chars/space?`, `chars/ident-start?`, `chars/ident-cont?`. ### `clock/` TCL-style clock ensemble: `clock/seconds`, `clock/millis`, `clock/micros`, `clock/clicks` (monotonic ns), `clock/format`, `clock/scan`, `clock/add`. ### `re/` — PCRE2 Regex `re/match`, `re/find`, `re/find-all`, `re/replace`, `re/replace-all`, `re/split`, `re/captures`, `re/find-at`, `re/escape`, `re/clear-cache`, `re/scan-first`. ### `log/` Leveled logging: `log/debug`, `log/info`, `log/warn`, `log/error`. ### `fs/` Filesystem: `fs/read`, `fs/write`, `fs/append`, `fs/exists?`, `fs/remove`, `fs/rename`, `fs/copy`, `fs/link`, `fs/mkdir`, `fs/read-lines`, `fs/write-lines`, `fs/stat`, `fs/list`, `fs/readdir`, `fs/glob`, `fs/join`, `fs/abs`, `fs/dir`, `fs/base`, `fs/ext`, `fs/file?`, `fs/dir?`, `fs/absolute?`, `fs/tempdir`, `fs/home`, `fs/watch`, `fs/unwatch`, `fs/local-path`, `fs/local-dir`, `fs/tmp-dir`, `fs/tmp-path`. Paths whose leading segment names a VFS mount ([VFS](../02-Platform/vfs)) route to that mount's driver instead of the native filesystem. For line-oriented I/O on an open file (instead of whole-file reads/writes), use the bare channel functions — `open`, `puts`, `gets`, `close` (see [I/O](#io) above). ### `os/` Process & subprocess: `os/args`, `os/exit`, `os/env`, `os/cwd`, `os/chdir`, `os/run`, `os/status`, `os/shell`, `os/lines`. ### `vfs/` Virtual filesystem mounts behind the `fs/` namespace — route `fs/*` paths to a local anchor directory or a remote host over ssh by their leading path segment. See [VFS](../02-Platform/vfs): `vfs/mount`, `vfs/unmount`, `vfs/list`. ### `json/` / `yaml/` `json/parse`, `json/stringify`, `json/pretty`. `yaml/parse`, `yaml/load`, `yaml/stringify`. ### `crypto/` `crypto/sha256`, `crypto/sha512`, `crypto/blake3`, `crypto/md5`, `crypto/hash`, `crypto/hmac`, `crypto/rand`, `crypto/rand-hex`, `crypto/b64-encode`, `crypto/b64-decode`, `crypto/hex-encode`, `crypto/hex-decode`, `crypto/encrypt`, `crypto/decrypt`. ### `compress/` `compress/tar-create`, `compress/tar-extract`, `compress/gzip`, `compress/gunzip`, `compress/tgz-create`, `compress/tgz-extract`, `compress/list-tgz`. ### `sqlite/` See [SQLite](../02-Platform/sqlite): `sqlite/open`, `sqlite/close`, `sqlite/exec`, `sqlite/query`, `sqlite/query-one`, `sqlite/scalar`, `sqlite/tables`, `sqlite/columns`, `sqlite/begin`, `sqlite/commit`, `sqlite/rollback`. ### `http/` (client) See [HTTP Client](../04-App-Server/http-client): `http/get`, `http/post`, `http/put`, `http/patch`, `http/delete`, `http/head`, `http/request`, `http/client`, `http/close`, `http/do`, `http/set-timeout`. ### `http/` (server) See [HTTP Server](../04-App-Server/http-server): `http/router`, `http/serve`, `http/stop`, `http/respond`, `http/json`, `http/html`, `http/status`, `http/header`, `http/redirect`. Cluster stdlib functions (`http/serve-cluster`, `http/cluster-*`) are documented in [App Server](../04-App-Server/app-server). ### `http/` (websockets) See [WebSockets](../03-Network/websockets): `http/ws-server`, `http/ws-connect`, `http/ws-send`, `http/ws-send-binary`, `http/ws-ping`, `http/ws-close`, `http/ws-stop`, `http/ws-on-message`, `http/ws-on-close`. ### `net/` See [TCP/UDP](../03-Network/tcp-udp): `net/tcp`, `net/udp`, `net/stop`, `net/start`, `net/close`, `net/list`, `net/info`, `net/connections`, `net/connect`, `net/connect-tls`, `net/send`, `net/recv`, `net/on-data`, `net/on-line`, `net/on-close`, `net/close-conn`, `net/udp-send`. ### `mcp/` See [MCP](../05-AI/mcp): `mcp/create`, `mcp/add`, `mcp/serve`, `mcp/http-serve`, `mcp/dispatch`. ### `pkg/` See [Packages](../07-Tooling/packages): `pkg/set-registry`, `pkg/get-registry`, `pkg/install`, `pkg/install-bytes`, `pkg/uninstall`, `pkg/list`, `pkg/list-paths`, `pkg/available`, `pkg/info`, `pkg/fetch`, `pkg/read-manifest`, `pkg/mount`. ### `dialog/` See [Dialogs](../06-TUI/dialogs): `dialog/prompt`, `dialog/password`, `dialog/confirm`, `dialog/msgbox`, `dialog/menu`, `dialog/checklist`, `dialog/search`, `dialog/file-open`, `dialog/file-save`. ### `pub/` See [Pubsub](../02-Platform/pubsub): `pub/subscribe`, `pub/publish`, `pub/unsubscribe`, `pub/topics`, `pub/subscribers`. ### `runtime/` and `gc/` See [Runtimes](../02-Platform/runtimes): `runtime/create`, `runtime/destroy`, `runtime/list`, `runtime/eval`, `runtime/eval-async`, `runtime/list-defs`, `runtime/run`, `runtime/spawn`, `runtime/current`, `runtime/exists?`, `runtime/mem-stats`, `runtime/on-shutdown`, `gc/collect`, `gc/stats`. ### `config/` See [Config](../02-Platform/config): `config/get`, `config/set`, `config/unset`, `config/scan`, `config/keys`, `config/count`, `config/load`, `config/save`, `config/save-map`, `config/save-overrides`. ### `theme/` Load, edit, and save theme `.dft` files (the same files the TUI hosts scan at startup and stdext ships under `src/themes/`): `theme/load` (stem, display name, or path → full theme map), `theme/get` (deep read by keyword path), `theme/set` (persistent deep update — new sections auto-created), `theme/unset`, `theme/save` (canonical write; shadow-copies into `.deft/local/themes/` when the origin is a shipped stdext file), `theme/list` (sorted available stems). Available in every host and the scripting binary; pair with `tui/theme-reload` / `tui/set-theme` for a live edit → save → apply loop in the TUI hosts. ### `deft/` | Function | Purpose | |---|---| | `deft/stringify value` | Serialize value to literal string | | `deft/parse str` | Parse literal back to value | ### `info/` | Function | Purpose | |---|---| | `info/modules` | Loaded modules | | `info/defs` | Defs in current ns | | `info/vars` | Vars in current ns | | `info/types` | Registered types | | `info/protocols` | Registered protocols | | `info/props value` | Metadata map | | `info/sig value` | Signature | | `info/source value` | Source text | | `info/resolve name` | Resolve name to source | ### `task/` Stream and future consumer side: `task/stream-next`, `task/stream-collect`, `task/stream-try-next`, `task/stream-close`, `task/stream-done?`, `task/future-ready?`. ### `capture/` `capture/start`, `capture/flush`, `capture/clear`, `capture/with` — used by tests and tooling to intercept `echo` output. ### `capabilities` `capabilities` — compiled-in feature map (e.g. whether FFI/TUI are enabled). Useful for portability checks. ## TUI-only Stdlib functions Available when built with `-Denable-tui=true` (the `retro` and `retra` binaries). See [TUI](../06-TUI/tui-overview) for the full surface. | Namespace | Purpose | |---|---| | `tui/` | Workspace management, panels, focus, widget tree, capability probes | | `draw/` | ALL 2D raster output — polymorphic on target (panel ctx, surface id, canvas) | | `surface/` | SDL surface lifecycle (retrs OS windows, retro in-panel surfaces) | | `scene/` | World-layer scene nodes | | `gl/` | 3D scene | | `color/` | Color parsing, normalization and tweaks (lighten/darken/mix/contrast) | | `clipboard/` | System clipboard | | `editor/` | Editor integration (diagnostics, semantic info) | | `media/` | Pixel buffers, image decode/transforms, Image converters | | `term/` | PTY terminal sessions | The full list of `tui/*` stdlib functions is large; see [TUI Overview](../06-TUI/tui-overview) and [Graphics](../06-TUI/graphics) for the most useful ones. ## FFI-only Stdlib functions Available when built with `-Dffi=true`. See [FFI](../08-Extending/ffi): `ffi/load`, `ffi/sym`, `ffi/call`, `ffi/close`, `ffi/alloc`, `ffi/cstring`, `ffi/string`, `ffi/read`, `ffi/write`, `ffi/addr`, `ffi/ptr`, `ffi/nullptr`, `ffi/pin`, `ffi/unpin`, `ffi/cdef`, `ffi/sizeof`, `ffi/new`, `ffi/get`, `ffi/set`, `ffi/callback`, `ffi/gc`. ## Debug Stdlib functions | Function | Purpose | |---|---| | `debug/serve`, `debug/stop`, `debug/list` | In-process debug server (see [Debug Server](../07-Tooling/debug-server)) | ## Discovering Stdlib functions at Runtime
 [capabilities]                                # what's compiled in
[info/modules]                                # what's loaded 
For up-to-date listings, the canonical sources are the plugin files under `src/host/plugins/` and `src/host/stdext/` in the codebase. The plugin registry is auto-generated at build time.