Skip to content
Kavachकवच

The Terminal

● Intermediate4 minBefore this: Output, User InputSpec 14.13

std.term colors and styles text, draws progress bars, and asks questions. It turns its colors off by itself when output isn't a terminal.

use std.term

fn main() {
    print(term.red("error:") + " file not found")
    print(term.bold(term.green("done") + " in 2 s"))
    print(term.yellow("warning:") + " " + term.underline("disk") + " almost full")
}

The program ran and printed:

kavach run colors.kav

error: file not founddone in 2 swarning: disk almost full
colors.kav: Kavach code, then what running it prints

In a terminal, error: is red and done green and bold. The output above has no colors because this page captured it through a pipe, not a terminal, and std.term never writes color codes there: log files and pipes stay clean. Setting the environment variable NO_COLOR turns colors off too.

Progress bars

use std.term

fn main() {
    const files = ["a.txt", "b.txt", "c.txt", "d.txt"]
    let bar = term.progress(files.len())
    for _ in files {
        bar = bar.step(1)
    }
    bar.done()
    print("copied {files.len()} files")
}

The program ran and printed:

kavach run progress.kav

copied 4 files
progress.kav: Kavach code, then what running it prints

In a terminal, the bar is drawn on one line and updated as the job goes on: [############--------] 60% 6/10. Outside one, as here, it prints nothing, so a log or a pipe gets no half-drawn lines.

Function or methodDoes
term.progress(total) -> ProgressA bar for a job of total steps, drawn at 0%
bar.step(n) -> Progressn more steps are done: the bar is drawn again (only when its percentage changed)
bar.done()The job is over: the bar is drawn full, and its line ends

One page for each form