How to properly use std.Io.Terminal.setColor() in Zig 0.17?

Hi! I’m learning Zig 0.17.0-dev and I’m trying to understand the new std.Io.Terminal API.

I can write to stdout like this:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
    const io = init.io;
    var stdout_writer = std.Io.File.stdout().writer(io, &.{});
    const stdout = &stdout_writer.interface;
    try stdout.print("Hello world!\n", .{});
}

But I can’t figure out how to use std.Io.Terminal.setColor() correctly.

From what I understand, setColor needs a Terminal and a Color, but I’m not sure how I’m supposed to obtain/create the Terminal object from std.process.Init / init.io, and how it should be connected to the stdout writer.

What is the intended Zig 0.17 way to do something as simple as:

print “Hello” in green
print " world" in default color

I’d also appreciate an explanation of what the Terminal abstraction represents here and how it differs from simply writing ANSI escape sequences to stdout.

Thanks!

const std = @import("std");

pub fn main(init: std.process.Init) !void {
    const io = init.io;
    var stdout_writer = std.Io.File.stdout().writer(io, &.{});
    const stdout = &stdout_writer.interface;
    const terminal: std.Io.Terminal = .{
        .writer = stdout,
        .mode = try .detect(io, .stdout(), false, false),
    };
    try terminal.setColor(.green);
    try stdout.writeAll("Hello");
    try terminal.setColor(.reset);
    try stdout.writeAll(" world\n");
    try stdout.flush();
}

std.Io.Terminal is cross platform in that it works with escape codes and windows terminal colors. Or it can not write colors depending on the mode. std.Io.Terminal.Mode.detect checks if the file supports escape codes or windows colors and returns Mode accordingly. Or you can force color mode. Or force not force color mode.

2 Likes