Files
ghostty/example/zig-formatter/src/main.zig
Mitchell Hashimoto 2044e5030f terminal: make stream processing infallible
The terminal.Stream next/nextSlice functions can now no longer fail.
All prior failure modes were fully isolated in the handler `vt`
callbacks. As such, vt callbacks are now required to not return an error
and handle their own errors somehow.

Allowing streams to be fallible before was an incorrect design. It
caused problematic scenarios like in `nextSlice` early terminating
processing due to handler errors. This should not be possible.

There is no safe way to bubble up vt errors through the stream because
if nextSlice is called and multiple errors are returned, we can't
coalesce them. We could modify that to return a partial result but its
just more work for stream that is unnecessary. The handler can do all of
this.

This work was discovered due to cleanups to prepare for more C APIs.
Less errors make C APIs easier to implement! And, it helps clean up our
Zig, too.
2026-03-13 13:56:14 -07:00

43 lines
1.2 KiB
Zig

const std = @import("std");
const ghostty_vt = @import("ghostty-vt");
pub fn main() !void {
var gpa: std.heap.DebugAllocator(.{}) = .init;
defer _ = gpa.deinit();
const alloc = gpa.allocator();
// Create a terminal
var t: ghostty_vt.Terminal = try .init(alloc, .{ .cols = 150, .rows = 80 });
defer t.deinit(alloc);
// Create a read-only VT stream for parsing terminal sequences
var stream = t.vtStream();
defer stream.deinit();
// Read from stdin
const stdin = std.fs.File.stdin();
var buf: [4096]u8 = undefined;
while (true) {
const n = try stdin.readAll(&buf);
if (n == 0) break;
// Replace \n with \r\n
for (buf[0..n]) |byte| {
if (byte == '\n') stream.next('\r');
stream.next(byte);
}
}
// Use TerminalFormatter to emit HTML
const formatter: ghostty_vt.formatter.TerminalFormatter = .init(&t, .{
.emit = .html,
.palette = &t.colors.palette.current,
});
// Write to stdout
var stdout_writer = std.fs.File.stdout().writer(&buf);
const stdout = &stdout_writer.interface;
try stdout.print("{f}", .{formatter});
try stdout.flush();
}