zooi is a small Zig library for keyboard-driven, full-screen terminal programs. It handles raw mode, the alternate screen, resize events, key decoding, and retained rendering. The application handles state, key bindings, and layout.
┌─ journal pqhx ────────────────────────────────────────────────────┐
│ │
│ 24 0 git status │
│ 25 0 zig build test │
│ > 26 1 zig build │
│ * 27 0 git diff │
│ │
├───────────────────────────────────────────────────────────────────┤
│ ↑↓ move space select p pin t tag n name d delete q quit │
└───────────────────────────────────────────────────────────────────┘
zooi provides an event loop, a screen buffer, and styled text.
Use zooi for small programs such as list browsers, pickers, log viewers, and dashboards. It works best for a single screen with keyboard input and custom layout code.
Use libvaxis if you need widgets, a layout engine, mouse input, terminal graphics, capability negotiation, or a component library. See Non-goals.
- Zig 0.17.0
zunic, fetched automatically as a pinned Zig package dependency- No libc on Linux. Calls use
std.posixorstd.os.linuxwhen Zig has no POSIX wrapper. macOS useslibSystem.
zooi does not call linkLibC(). If the application links libc, zooi uses it.
Add the dependency:
zig fetch --save git+https://github.com/vrypan/zooi.git#v0.4.0Add the module in build.zig:
const zooi = b.dependency("zooi", .{});
exe.root_module.addImport("zooi", zooi.module("zooi"));Use Zig's package support rather than copying src/: zooi also depends on
zunic. See examples/minimal for a complete consumer
project with its own build.zig, build.zig.zon, and src/main.zig.
Run the example browser:
zig build runUse j/k or the arrow keys to move. space selects, v starts a range,
p pins, t tags, n names, d deletes, Enter inspects, and q quits.
The source is examples/browser.zig.
For a variable-height list whose items wrap across terminal rows, run:
zig build run-wrappedIts source is examples/wrapped_list.zig.
It includes labeled 200-, 500-, and 1,000-column samples so a normal terminal
shows multiple visual rows and makes PageUp/PageDown useful.
This program draws a list, moves a cursor, and quits on q:
const std = @import("std");
const zooi = @import("zooi");
const items = [_][]const u8{ "alpha", "beta", "gamma", "delta" };
pub fn main() !void {
var debug: std.heap.DebugAllocator(.{}) = .init;
defer _ = debug.deinit();
const gpa = debug.allocator();
var ui = try zooi.Ui.init(gpa, .{});
defer ui.deinit();
var cursor: usize = 0;
var running = true;
try render(&ui, cursor);
// Apply a short burst of queued input, then render once. The limit keeps a
// continuous producer from starving the display.
const max_events_per_frame = 64;
while (running) {
const first = (try ui.nextEvent()) orelse break;
var pending: ?zooi.Event = first;
var handled: usize = 0;
while (pending) |event| {
switch (event) {
.key => |key| switch (key) {
.up => cursor -|= 1,
.down => cursor = @min(cursor + 1, items.len - 1),
.ctrl_c => running = false,
.character => |c| if (c == 'q') {
running = false;
},
else => {},
},
.resize => {},
}
handled += 1;
if (!running or handled == max_events_per_frame) break;
pending = try ui.pollEvent();
}
if (running) try render(&ui, cursor);
}
}
fn render(ui: *zooi.Ui, cursor: usize) !void {
const screen = ui.screen();
screen.begin();
for (items, 0..) |item, i| {
screen.move(@intCast(i), 0);
if (i == cursor) {
screen.writeStyled("> ", .{ .bold = true });
screen.writeStyled(item, .{ .reverse = true });
} else {
screen.write(" ");
screen.write(item);
}
}
try screen.present();
}Screen drawing functions return void. present() returns the first drawing
or output error. This keeps error handling out of layout code.
The application owns the loop. nextEvent() returns one event and blocks when
there is no input.
- Keep one
Uialive for the terminal session and immediatelydefer ui.deinit()after initialization. - Draw the complete logical frame between
begin()andpresent(). - After
nextEvent(), usepollEvent()to apply queued input before rendering. Put a limit on each batch so continuous input cannot starve the display. - Do not print directly to the active terminal or generate application-side
ANSI sequences. Let
Screenown terminal output. - Handle
ctrl_c; zooi returns it as a key instead of raisingSIGINT. - Propagate errors from
present(). Install the restoration hook described in Terminal restoration if the application can panic or handles fatal signals.
The terminal session.
pub fn init(gpa: Allocator, options: Options) !Ui
pub fn deinit(self: *Ui) void
pub fn screen(self: *Ui) *Screen
pub fn size(self: *const Ui) Size
pub fn nextEvent(self: *Ui) !?Event
pub fn pollEvent(self: *Ui) !?EventnextEvent blocks until a key is pressed or the terminal is resized. It returns
null when the input stream ends. pollEvent returns a queued event without
blocking, or null if none is ready. Use it to process an input burst before
rendering once.
pub const Options = struct {
/// Override the terminal descriptor. Null opens /dev/tty.
tty: ?std.posix.fd_t = null,
alternate_screen: bool = true,
synchronized_output: bool = true,
/// Compress long runs of styled spaces with REP. See Rendering model.
repeat_sequences: bool = false,
/// How long a lone ESC waits for the rest of a sequence.
escape_timeout_ms: u16 = 25,
};Input and output descriptors are selected separately. Input prefers a terminal
on stdin or stderr. Output prefers stdout, then stderr. /dev/tty is the
fallback. This prevents redirected output from receiving terminal control
sequences.
On macOS, poll() returns POLLNVAL for a newly opened /dev/tty. zooi
therefore prefers an inherited terminal for input. If both stdin and stderr are
redirected, /dev/tty input does not work on macOS. It works on Linux.
pub const Event = union(enum) {
key: Key,
resize: Size,
};
pub const Size = struct { rows: u16, cols: u16 };Repeated resize notifications are coalesced. No event is returned if the size
did not change. rows and cols may be 0; rendering clips to the reported
size.
pub const Key = union(enum) {
up, down, left, right,
page_up, page_down, home, end,
shift_up, shift_down,
shift_page_up, shift_page_down,
shift_home, shift_end,
enter, escape, backspace, delete,
tab, shift_tab,
character: u21,
ctrl_c,
};character contains one printable Unicode codepoint decoded from UTF-8. Other
control bytes are dropped, Ctrl-Z among them; see Non-goals.
zooi disables ISIG, so Ctrl-C is returned as ctrl_c instead of raising a
signal. Applications must handle it.
Both CSI (ESC [ A) and SS3 (ESC O A) forms are supported for arrows,
Home, and End. Shift-Tab is read from ESC [ Z. Shift-modified arrows,
PageUp/PageDown, Home, and End are returned as their corresponding shift_*
variants.
Viewport provides allocation-free cursor and scroll-offset arithmetic for
lists. It does not consume keys, own application data, or render rows.
pub const Viewport = struct {
cursor: usize = 0,
offset: usize = 0,
pub const Range = struct { start: usize, end: usize };
pub fn normalize(self: *Viewport, item_count: usize, visible_rows: usize) void
pub fn setCursor(self: *Viewport, index: usize, item_count: usize, visible_rows: usize) void
pub fn move(self: *Viewport, delta: isize, item_count: usize, visible_rows: usize) void
pub fn visibleRange(self: Viewport, item_count: usize, visible_rows: usize) Range
};Movement clamps at both ends and adjusts offset only enough to keep the
cursor visible. An empty list resets both fields to zero. With zero visible
rows the cursor remains clamped, offset equals the cursor, and the returned
range is empty. Range.end is exclusive.
wrap.iterator splits borrowed text into visual-row fragments. Fragment
offsets are byte offsets into the original text, while columns is a terminal
cell count. It allocates nothing. Cell mode is the direct, greedy choice; word
mode follows the default Unicode line-break opportunities and otherwise falls
back to a grapheme boundary.
var fragments = try zooi.wrap.iterator(label, available_columns, .word);
while (fragments.next()) |fragment| {
screen.move(row, 0);
if (fragment.kind == .replacement) {
screen.write("?");
} else {
screen.write(label[fragment.start..fragment.end]);
}
row += 1;
}The iterator never splits a grapheme cluster. Newlines create rows; malformed
UTF-8, tabs, other controls, and leading orphan marks take no cells. A cluster
that cannot fit is returned as .replacement, which occupies one cell.
RowIndex maps logical items to their wrapped row ranges using caller-owned
prefix storage. VariableViewport then keeps one selected visual row visible
without changing the existing item-based Viewport API.
const heights = [_]usize{ 2, 1, 4 };
var offsets: [heights.len + 1]usize = undefined;
const index = try zooi.RowIndex.build(&heights, &offsets);
var view: zooi.VariableViewport = .{};
view.moveRows(1, index, terminal_rows);
var visible = view.visibleItems(index, terminal_rows);
while (visible.next()) |item| {
// item.first_row, item.row_count, and item.screen_row identify the
// already-cached fragments that belong on screen.
}The index borrows its offset storage. Rebuild both the fragment cache and the
index when text or available columns change; moving the cursor needs neither.
cursor selects a logical item, while row_in_item identifies its focused
visual row. moveItems resets that row when selection changes; moveRows and
page move through visual rows.
pub fn begin(self: *Screen) void
pub fn move(self: *Screen, row: u16, col: u16) void
pub fn write(self: *Screen, text: []const u8) void
pub fn writeStyled(self: *Screen, text: []const u8, style: Style) void
pub fn clearToEndOfLine(self: *Screen) void
pub fn fillToEndOfLine(self: *Screen, style: Style) void
pub fn showCursor(self: *Screen, row: u16, col: u16) void
pub fn setSynchronizedOutput(self: *Screen, enabled: bool) void
pub fn setRepeatSequences(self: *Screen, enabled: bool) void
pub fn present(self: *Screen) !void
pub fn frame(self: *const Screen) []const u8
size: Size // field: current terminal dimensionsRows and columns are 0-based. begin() starts a frame, present() writes
the changed cells to the terminal in a single write.
showCursor sets the cursor position for present(). If it is not called, the
cursor stays hidden.
fillToEndOfLine writes explicit spaces in the supplied style without moving
the logical cursor. Use it for full-width highlighted or colored rows.
clearToEndOfLine instead restores true blanks in the terminal's default
style.
pub const Style = struct {
fg: ?Color = null,
bg: ?Color = null,
bold: bool = false,
dim: bool = false,
italic: bool = false,
underline: bool = false,
reverse: bool = false,
};
pub const Color = union(enum) {
ansi: u4, // the terminal's own 16 colors
indexed: u8, // 256-color palette
rgb: struct { r: u8, g: u8, b: u8 },
};null uses the terminal's default color. .ansi uses the terminal's configured
16-color palette.
The zooi.testing namespace provides a read-only view of the last successfully
presented logical frame:
pub const CellView = struct {
text: []const u8,
style: Style,
columns: u2,
continuation: bool,
};
pub fn presentedSize(screen: *const Screen) ?Size
pub fn inspectCell(screen: *const Screen, row: u16, col: u16) ?CellViewBoth functions return null before a successful presentation or after a
failed one. inspectCell also returns null outside the presented size.
CellView.text borrows screen storage and must be consumed before the next
present() or Screen.deinit().
pub fn displayWidth(text: []const u8) usizeReturns the number of terminal columns used by a string after the same
filtering and grapheme grouping as Screen. For example, é uses one column,
世 uses two, and 👩💻 uses two. Malformed UTF-8 and controls use no
columns.
pub fn restore() voidRestores terminal state. It is allocation-free, async-signal-safe, and does
nothing when no Ui is active. See Terminal restoration.
Draw the full logical frame between begin() and present(). Screen compares
front and back cell grids and writes only changed row spans. Moving a cursor
usually updates two rows.
The grids, text storage, and ANSI output buffer are reused. Steady-state frames do not allocate. A resize clears and repaints the screen once.
begin() captures size for the whole frame. A resize that arrives part-way
through — pollEvent() called mid-render, for instance — does not change the
geometry of the frame being drawn; it takes effect at the next begin(), which
repaints from a clear screen. Read size in render as usual.
A cell retains one grapheme cluster, with a 32-byte storage limit. Longer clusters are truncated at a UTF-8 boundary, so text from an untrusted source cannot make one cell grow without bound. Emoji ZWJ sequences and flags are placed as one two-column cluster.
To highlight a complete row, draw its text and then fill its remaining cells:
screen.writeStyled(label, selected_style);
screen.fillToEndOfLine(selected_style);Long runs of styled spaces can be compressed into a REP sequence (CSI Ps b),
which saves under 100 bytes on a typical frame. It is off by default: a
terminal that does not implement REP drops the sequence silently and paints
styled backgrounds truncated to the width of their text. Set
repeat_sequences = true when the terminal is known to support it.
Synchronized output is enabled by default. Supporting terminals hold mode 2026
frames until present() writes the closing sequence. Other terminals normally
ignore the mode. Set synchronized_output = false if needed.
Clipping uses terminal columns, not byte length. Text past the right edge is truncated. A two-column cluster that would cross the edge is replaced with a space. Writes outside the screen are ignored. Control bytes, malformed UTF-8, and newlines are dropped.
The application decides how to handle a terminal that is too small.
deinit() restores the alternate screen, cursor, and original termios:
var ui = try zooi.Ui.init(gpa, .{});
defer ui.deinit();This handles normal returns and errors. For panics, call restore() from a
panic handler:
pub const panic = std.debug.FullPanic(struct {
fn f(msg: []const u8, first_trace_addr: ?usize) noreturn {
zooi.restore();
std.debug.defaultPanic(msg, first_trace_addr);
}
}.f);Call restore() from SIGTERM or SIGHUP handlers as well, if present.
Keep state changes in an update function and drawing in a render function.
Both can be tested without a terminal:
test "cursor stops at the end of the list" {
var model: Model = .{ .cursor = 0, .items = &.{ "a", "b" } };
update(&model, .{ .key = .down });
update(&model, .{ .key = .down });
try std.testing.expectEqual(@as(usize, 1), model.cursor);
}frame() contains the ANSI bytes emitted by the most recent present(). Use it
for encoder assertions and to compare retained-diff size. The first frame
paints the screen; later frames contain only changes from the previous
successful frame.
For logical render assertions, inspect the last successfully presented frame:
const fd = try std.posix.openatZ(
std.posix.AT.FDCWD,
"/dev/null",
.{ .ACCMODE = .WRONLY },
0,
);
defer _ = std.posix.system.close(fd);
var screen = zooi.Screen.init(std.testing.allocator, fd, .{ .rows = 3, .cols = 20 });
defer screen.deinit();
screen.begin();
screen.writeStyled("selected", .{ .reverse = true });
screen.fillToEndOfLine(.{ .reverse = true });
try screen.present();
const cell = zooi.testing.inspectCell(&screen, 0, 19).?;
try std.testing.expectEqualStrings(" ", cell.text);
try std.testing.expect(cell.style.reverse);The returned text is borrowed; assert on it before the next present(). Keep
application state in the model: production layout, navigation, and event
handling should not read values back from the screen.
Terminal behaviour itself needs a real terminal, and that is the one place
where unit tests cannot help. zooi's own suite covers it in
test/pty_test.zig: raw-mode lifecycle, alternate-screen
lifecycle, key decoding through a pty, escape timing in both directions,
resize delivery and coalescing, and restoration after SIGTERM and after a
panic. test/pty.zig is the harness, and it is worth copying
the one rule it follows — every wait is for a marker the program emits, never
for a duration. A terminal suite built on sleeps is one everybody learns to
ignore.
Run the benchmarks with optimizations enabled:
make benchmark
# Or:
zig build benchmark -Doptimize=ReleaseFastFor a quick check of every workload:
zig build benchmark -Doptimize=ReleaseFast -- --smokeThe harness in bench/benchmark.zig reports median and
minimum time across seven samples after warming its buffers. Rendering cases
draw complete logical frames at 80×24 and 200×60: all ASCII cells changing,
all wide Unicode cells changing, unchanged content, and a selection moving
between two rows. Results include emitted bytes per frame. Timings include
frame construction, retained diffing and writes to /dev/null; they exclude
terminal-emulator work and initial allocation.
Wrapping cases process approximately 16 KiB of ASCII, CJK, and emoji with
combining marks in both cell and word modes at 80 columns. They report time
per input, input throughput in MiB/s, and fragments per input as lines/input.
Checksums keep the wrapping work observable to the optimizer, and the harness
checks fragment bounds and consistent results outside the timed loops.
Compare runs on the same machine, Zig version and optimization mode. Smoke runs use fewer iterations and three samples; use full runs for comparisons. CI runs the smoke workloads without imposing timing thresholds.
| Platform | Status | libc |
|---|---|---|
| Linux x86_64 | verified on hardware, and on every CI run | none |
| Linux aarch64 | builds | none |
| macOS aarch64 / x86_64 | verified | libSystem (unavoidable) |
zig build verify builds a standalone binary that checks zooi's primitives
against the machine it runs on and reports PASS/FAIL per check. CI runs it on
Linux under a pty, built for x86_64-linux-none, so each push proves the
libc-free build both links and runs. On an unusual terminal, run it and paste
the output.
Cross-compiling requires only Zig:
zig build -Dtarget=x86_64-linux-none # static, no libc
zig build -Dtarget=aarch64-macosThe target ABI does not enable libc by itself. -lc or linkLibC() enables it.
For example, -Dtarget=x86_64-linux-gnu without -lc is libc-free.
zooi does not provide widgets, layout containers, focus management, mouse or clipboard input, terminal graphics, async jobs, background workers, filesystem watching, plugins, themes, configurable key bindings, or multiple panes.
Known limits:
- Unicode line breaking uses default UAX #14 rules. It does not apply locale tailoring or dictionary segmentation for complex South East Asian scripts.
- The retained grid is not application state. Tests can inspect the last successfully presented frame through a read-only diagnostic view, but production code should not recover its model from rendered cells.
- Single-threaded. All rendering and all state changes happen on the loop.
- No job control.
ISIGis off and Ctrl-Z is not delivered as a key, so a zooi application cannot be suspended and resumed.
0.1.0 was the first release. The API may change before 1.0.0. Pin the v0.4.0
tag for reproducible builds.
See CHANGELOG.md for changes by version.
MIT. See LICENSE.