Text colour and style, cursor movement, progress bars, reading keys and the mouse, and the terminal size.
import term
The term package has what a command line program needs to look good in a terminal: text colour and style, columns that line up, progress bars and spinners, and for full screen programs, cursor movement, the alternate screen and reading keys one at a time.
The colour functions, such as Red, return a new string and print nothing. In the default ColorAuto mode they add nothing when the output goes to a file or another program, when NO_COLOR is set or when TERM=dumb, so the text stays plain; SetColorMode changes that, for a --color option for instance. The functions whose names start with Seq only return an escape sequence, and the one with the same name without the prefix sends it right away. To read keys, put the terminal into raw mode with MakeRaw or MakeCbreak, and always put it back with Restore.
For one line questions such as a name or a yes or no, cli is simpler; for log lines, log; for padding plain text, fmt.
The things people get wrong:
•
Padding coloured text with len. A colour code adds bytes but no columns; use PadRight and the other functions here, which measure with Width.
•
Trusting Width with every script. It counts one column per character: Chinese and Japanese characters, which take two columns, count as one, and invisible ones such as the zero width non-joiner in Persian میشود count as one too. Tables of such text need padding of your own.
•
Leaving the terminal in raw mode. Call Restore with defer right after MakeRaw, and leave the alternate screen and show the cursor on every way out.
•
Expecting a progress bar in a log. BarDraw draws nothing when the output is not a terminal, and BarFinish prints the final bar once, so a CI log gets one clean line.
A coloured table that lines up
A colour code adds bytes to a string but no columns on the screen, so padding with len would push every coloured cell out of line. PadRight, PadLeft and Truncate measure with Width, which skips escape codes, so a table lines up whether its cells are coloured or not.
term-guide-table.salam
import term
structService:
pub name: str = ""pub status: str = ""pub memory: i64 = 0pub uptime_ms: i64 = 0endfunccolored_status(s: str): str:
if s == "running":
ret term.Green(s)
else s == "degraded":
ret term.Yellow(s)
endret term.Red(s)
endfuncmain:
services := [
Service {
name = "api",
status = "running",
memory = 157286400,
uptime_ms = 93784000
}, Service {
name = "search-indexer",
status = "degraded",
memory = 1073741824,
uptime_ms = 4500000
}, Service {
name = "mail",
status = "stopped",
memory = 0,
uptime_ms = 0
}
]
println term.Bold(
term.PadRight(
"SERVICE", 14
) + " " + term.PadRight("STATUS", 9) + " " + term.PadLeft("MEMORY", 9) + " UPTIME"
)
each s in services:
name := term.PadRight(term.Truncate(s.name, 14), 14)
status := term.PadRight(colored_status(s.status), 9)
mut up := "-"if s.uptime_ms > 0:
up = term.FormatDuration(s.uptime_ms)
endprintln name, status, term.PadLeft(term.FormatBytes(s.memory), 9), "", up
endend
Output
SERVICE STATUS MEMORY UPTIME
api running 150.0 MB 26h 03m
search-indexer degraded 1.0 GB 1h 15m
mail stopped 0 B -
The output above is plain because the program's output went to a file, not a terminal. Run it in a terminal and the status column turns green, yellow and red, with no change to the code. FormatBytes and FormatDuration turn raw numbers into the short forms people expect in a status table.
Colour on screen, plain text in the log
The same line often goes to two places: the terminal, where colour helps, and a log file, where escape codes are noise. Build the line once and pass it through Strip for the file. The colour functions already return plain text when colour is off, but Strip also cleans text that was coloured earlier or came from another program.
term-guide-log.salam
import term
funcstatus_line(tag: str, message: str): str:
mut label := "[" + tag + "]"if tag == "ok":
label = term.Green(label)
else tag == "warn":
label = term.Yellow(label)
else tag == "fail":
label = term.Bold(term.Red(label))
endret term.PadRight(label, 7) + message
endfuncmain:
term.SetColorMode(term.ColorAlways)
line := status_line("warn", "cache is 91% full")
println"bytes:", line.Len(), "| columns on screen:", term.Width(line)
mut log_file := Vector {} asVector<str>
defer log_file.Free()
log_file.Push(term.Strip(status_line("ok", "config loaded")))
log_file.Push(term.Strip(line))
log_file.Push(term.Strip(status_line("fail", "could not reach the mail server")))
println"--- the log file ---"each entry in log_file:
println entry
endend
Output
bytes: 33 | columns on screen: 24
--- the log file ---
[ok] config loaded
[warn] cache is 91% full
[fail] could not reach the mail server
The example forces colour on with SetColorMode(ColorAlways) so the difference between bytes and columns is visible. Leave the mode at ColorAuto in real programs: it turns colour off for pipes, files and NO_COLOR, which is what users expect.
A progress bar that also works in CI
NewBar takes the total and a label; BarAdd moves it on and redraws it in place, and BarFinish fills it and ends the line. The fields change the look: a fixed width instead of one worked out from the terminal, the fill and empty characters, and show_count or show_eta for the numbers after the bar. BarRender returns the same text without drawing it, which is useful for a status line of your own.
term-guide-progress.salam
import term
funcmain:
sizes := [120, 480, 64, 900, 236]
mut total := 0eachsizein sizes: total += sizeendmut bar := term.NewBar(total, "backup")
bar.width = 20
bar.fill = "#"
bar.empty = "."
bar.show_count = trueeach i, sizein sizes:
term.BarAdd(bar, size)
if i == 1: println"halfway:", term.BarRender(bar) endend
term.BarFinish(bar)
println"copied", term.FormatBytes((total asi64) * 1024), "in", term.FormatDuration(7400)
end
On this page the output is not a terminal, so the five BarAdd calls drew nothing and BarFinish printed the finished bar once. In a terminal the same program shows one bar that fills up on a single line. NewBar picks █ and ░ when the locale is UTF-8; the example sets plain characters so its output is the same everywhere. For work with no known total, NewSpinner with SpinnerTick in a loop and SpinnerStop at the end does the same job.
An arrow key menu
A full screen program follows a fixed pattern: check that standard input is a terminal, switch it to raw mode so keys arrive one at a time without being echoed, move to the alternate screen so the user's scrollback is left alone, and undo all of it in reverse order at the end. ReadKey turns the bytes of a key press into a Key, so arrows, Enter and Escape are simple comparisons.
term-guide-menu.salam
import term
funcdraw(items: Vector<str>, chosen: int):
term.Write(term.SeqClearScreen())
term.Write(term.Bold("Pick a language (arrows, Enter, q)") + "\r\n\r\n")
each i, item in items:
if i == chosen:
term.Write(term.Inverse(" > " + item + " ") + "\r\n")
else:
term.Write(" " + item + "\r\n")
endend
term.Flush()
endfuncmain:
ifnot term.IsTTY(term.StdinFd):
printerrln"run this program in a terminal"ret1endmut items := Vector {} asVector<str>
defer items.Free()
items.Push("Salam")
items.Push("C")
items.Push("Go")
items.Push("Rust")
mut state := term.MakeRaw(term.StdinFd)
term.EnterAltScreen()
term.HideCursor()
mut chosen := 0mut picked := -1until picked < 0:
draw(items, chosen)
k := term.ReadKey()
if k.code == term.KeyUp and chosen > 0:
chosen--
else k.code == term.KeyDown and chosen < items.Len() - 1:
chosen++
else k.code == term.KeyEnter:
picked = chosen
else k.code == term.KeyEOF or (k.code == term.KeyChar and k.ch == "q"):
breakendend
term.ShowCursor()
term.ExitAltScreen()
term.Restore(state)
if picked >= 0:
println"you picked", items.Get(picked)
endret0end
This program needs a real terminal, so its output is not shown here. Run it with salam run term-guide-menu.salam. In raw mode the terminal no longer turns \n into a new line at the left edge, which is why the program writes \r\n. Always reach Restore, even on an error path, or the user's shell is left in raw mode; reset fixes it if that happens.
The saved state of the terminal, to put back with Restore.
Name
Type
Description
fd
int = 0
The file descriptor of the terminal.
saved
void*
The previous terminal settings on Unix.
mode_in
int = 0
The previous input mode on Windows.
mode_out
int = 0
The previous output mode on Windows.
ok
bool = false
Whether the mode change succeeded.
term-ReadKey.salam
import term
funcmain:
ifnot term.IsTTY(term.StdinFd):
printerrln"this program has to run in a terminal"ret1endmut state := term.MakeRaw(term.StdinFd)
defer term.Restore(state)
term.Write("press a key (q to quit)\r\n")
untiltrue:
ifnot term.KeyReady(500):
continueend
k := term.ReadKey()
if k.code == term.KeyChar and k.ch == "q":
breakend
term.Write("code: " + k.code + "\r\n")
end
k2 := term.GetKey()
b := term.ReadByte()
password := term.ReadPassword("password: ")
println k2.code, b, password.Len()
s2 := term.MakeCbreak(term.StdinFd)
mut s3 := s2
term.Restore(s3)
ret0end
Redraws the bar on the same line and hides the cursor the first time; does nothing when the output is not a terminal.
term-Progress.salam
import term
import time
funcmain:
mut b := term.NewBar(50, "processing")
repeat50:
term.BarAdd(b, 1)
term.BarDraw(b)
time.Sleep(20)
end
term.BarFinish(b)
mut s := term.NewSpinner("connecting to the server")
repeat20:
term.SpinnerTick(s)
time.Sleep(50)
end
term.SpinnerStop(s, "connected")
term.SpinnerFree(s)
end
Whether colour will be written. In automatic mode it is false when NO_COLOR is set, when TERM=dumb, or when the output is not a terminal; CLICOLOR_FORCE turns colour on.
The example for this item is shown with the ones above: term-Size.salam
Colours the text with the given sequence and removes the colour at the end. When colour is not supported it returns the text untouched. Nested colours work correctly.
The example for this item is shown with the ones above: term-Color.salam
The number of characters in the text, skipping escape sequences. Every character counts as one cell, so East Asian wide characters count as one and invisible ones, such as a zero width non-joiner, count too.
The example for this item is shown with the ones above: term-Width.salam