term - terminal control
Enable with use term;. The terminal host capabilities an interactive TUI needs and pure .j cannot reach: raw mode (unbuffered, no-echo input), the terminal size, and raw single-byte reads from stdin. Screen control, key decoding, and rendering belong in a .j layer on top.
An output-only TUI (a dashboard, a progress bar) needs only ansi escape codes and os.isTerminal; use term to read keypresses as they happen.
term is built on golang.org/x/term (also used by the REPL's line editor). Build-tag split like net: the default jennifer binary has the real implementation; jennifer-tiny raises an error (a minimal / embedded target may have no controlling terminal). The tiny build could not support readByteTimeout in any case: its cooperative scheduler cannot wait for a timer while a read of stdin blocks.
Surface
| Call | Returns | Notes |
|---|---|---|
term.makeRaw(stream) | term.State | Put the terminal into raw mode; stream must be "stdin" (raw mode governs input). Returns a handle for restore. |
term.restore(state) | null | Undo makeRaw, restoring the terminal. The handle is single-use. |
term.size(stream) | term.Size | The terminal's {rows, cols} (query "stdout"). Catchable error when there is no size to report: not a terminal, or a terminal with no window size set (see Terminal size). |
term.readByte() | int | The next raw byte from stdin (0-255); throws "closed" at end of input. |
term.readByteTimeout(ms) | int | Like readByte, but throws "timeout" when no byte arrives within ms milliseconds; ms 0 polls. |
stream is "stdin" / "stdout" / "stderr" (the same names as os.isTerminal). A stream that is not a terminal - a pipe or a redirect - is a catchable error for makeRaw / size.
Raw mode
In the default (cooked) mode the OS buffers and echoes a whole line and hands it over on Enter. In raw mode every keypress is delivered immediately, unechoed, as an editor, pager, or game loop needs. term.makeRaw enters it and returns a term.State handle; pass that handle to term.restore to put the terminal back:
use io;
use os;
use term;
if (not os.isTerminal("stdin")) {
io.printf("needs an interactive terminal\n");
} else {
def state as term.State init term.makeRaw("stdin");
defer term.restore($state); # runs however this block exits
def running as bool init true;
while ($running) {
try {
def b as int init term.readByte(); # blocks until a key is pressed
if ($b == 113) { # 'q'
$running = false;
} else {
io.printf("byte %d\r\n", $b); # raw mode: newline is not cooked
}
} catch (e) {
if ($e.kind != "closed") {
throw $e;
}
$running = false; # end of input
}
}
}Always restore. Raw mode is a property of the terminal device, not the process, so a program that exits still in raw mode would leave the shell there. Put defer term.restore($state); right after the makeRaw (as above) so the restore runs on every exit path - including a throw unwinding through the block (control-flow > defer). In raw mode the newline is not cooked, so prints need an explicit \r\n. The term.State handle is single-use: a second term.restore of the same handle does nothing, so a stale handle never clobbers a live terminal and an explicit restore before the deferred one is harmless. At most 256 states are active at once; one more makeRaw throws kind "limit".
As a backstop, the jennifer CLI cooks the terminal back on the way out even when the program does not: a normal exit, an exit, an uncaught error, a panic, or an uncaught terminating signal (SIGINT / SIGTERM / SIGHUP, re-raised so the process still dies as usual). It only runs as the process ends, so a program that leaves raw mode mid-run must still call restore, and kill -9 (SIGKILL) bypasses it.
Reading keys
term.readByte returns one raw byte from stdin (0-255) and throws "closed" at end of input. In raw mode it returns the instant a key is pressed. It reads bytes, not decoded keys: a plain key is one byte, but an arrow key or a function key arrives as a multi-byte escape sequence (ESC [ A for Up, ...). Decoding those into key events is left to a TUI layer on top.
term.readByteTimeout(ms) is the bounded form: the byte, or "timeout" when ms milliseconds pass with no byte (0 polls without waiting); "closed" at end of input as readByte. It tells a lone Escape key from the start of an escape sequence (a terminal writes a sequence's bytes in one burst, so a short wait after ESC that times out - the screen module uses 50 ms - means a bare Escape), and polls input from a loop that must not block.
term and io read stdin through one shared buffer, so their reads mix freely: every byte goes to exactly one read, in input order. A read that times out loses nothing: the byte it was waiting for is the next one any read returns, whether that is term.readByte, term.readByteTimeout, or an io read such as io.readLine or io.readBytes. A byte io.eof() peeked is still there for term.readByte, and the end of input (or a read error, such as a closed stdin) reached by one library is what the other sees too: "closed" from term, io.eof() true. Stdin is not read until the first read asks for input, and only as much as that read needs (one chunk ahead at most), so a program that switches between raw keys and io.readLine lines gets each in the mode active when it is read; a read still pending from a timed-out term read takes the terminal mode set by the time the key arrives.
def b as int init term.readByte();
if ($b == 27) {
try {
def next as int init term.readByteTimeout(50);
# the second byte of an escape sequence
} catch (e) {
if ($e.kind != "timeout") {
throw $e;
}
# a lone Escape key
}
}term.readByte and term.readByteTimeout are refused inside the REPL, which owns the terminal for its own line editor.
Errors
| Kind | Thrown by | When |
|---|---|---|
"closed" | readByte, readByteTimeout | End of input. |
"timeout" | readByteTimeout | No byte within ms. The read stays in flight: its byte is the next one any read returns. |
"limit" | makeRaw | More than 256 raw-mode states active. |
"runtime" | every call | A wrong argument, ms negative or above 9,223,372,036,854 (the largest a duration holds), a stream that is not a terminal, a read error (a closed stdin), a call inside the REPL. |
0.28.0 replaced the -1 (end of input) and -2 (timeout) return values with the "closed" and "timeout" errors.
Terminal size
term.size(stream) returns a term.Size{rows, cols} - the character grid of the terminal behind stream (usually "stdout"):
def dim as term.Size init term.size("stdout");
io.printf("%d rows x %d cols\n", $dim.rows, $dim.cols);The size is a snapshot; a terminal can be resized after the call, so re-query it for the current value.
term.size errors (catchable) whenever there is no size to report: when stream is not a terminal - a pipe, a redirect, or jennifer test's stdout - and when it is a terminal with no window size set - a pty opened without one, as under script(1) or some CI runners, which the OS reports as 0 x 0. A successful call always returns positive dimensions, and one try covers both cases; fall back (for example to the LINES / COLUMNS environment, then 80x24) when it throws:
def rows as int init 24;
def cols as int init 80;
try {
def dim as term.Size init term.size("stdout");
$rows = $dim.rows;
$cols = $dim.cols;
} catch (e) {
# no terminal size - keep the 80x24 fallback
}See also
os-os.isTerminal(stream)to gate on an interactive terminal before entering raw mode.ansi- escape codes for colour and cursor control, which pair withtermfor a full-screen TUI.screen- the full-screen TUI module (cell buffer, diff rendering, key decoding) built on top ofterm.
Academy talks
| Talk | What it shows |
|---|---|
| A terminal game in Jennifer | raw keys and reads with a timeout |