Standard library · System and tools

term

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

struct Service:
    pub name: str = ""
    pub status: str = ""
    pub memory: i64 = 0
    pub uptime ms: i64 = 0
end

func colored status(s: str): str:
    if s == "running":
        ret term.Green(s)
    else s == "degraded":
        ret term.Yellow(s)
    end
    ret term.Red(s)
end

func main:
    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)
        end
        println name, status, term.PadLeft(term.FormatBytes(s.memory), 9), "", up
    end
end
OutputSERVICE 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

func status 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))
    end
    ret term.PadRight(label, 7) + message
end

func main:
    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 {} as Vector<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
    end
end
Outputbytes: 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

func main:
    sizes := [120, 480, 64, 900, 236]
    mut total := 0
    each size in sizes: total += size end
    mut bar := term.NewBar(total, "backup")
    bar.width = 20
    bar.fill = "#"
    bar.empty = "."
    bar.show_count = true
    each i, size in sizes:
        term.BarAdd(bar, size)
        if i == 1: println "halfway:", term.BarRender(bar) end
    end
    term.BarFinish(bar)
    println "copied", term.FormatBytes((total as i64) * 1024), "in", term.FormatDuration(7400)
end
Outputhalfway: backup [######..............] 33% 600/1800 backup [####################] 100% 1800/1800 copied 1.7 MB in 7.4s

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

func draw(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")
        end
    end
    term.Flush()
end

func main:
    if not term.IsTTY(term.StdinFd):
        printerrln "run this program in a terminal"
        ret 1
    end
    mut items := Vector {} as Vector<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 := 0
    mut picked := -1
    until 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"):
            break
        end
    end
    term.ShowCursor()
    term.ExitAltScreen()
    term.Restore(state)
    if picked >= 0:
        println "you picked", items.Get(picked)
    end
    ret 0
end

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.

Which function for which job

JobUse
Highlight a word or a statusRed, Green, Bold and the other colour functions
Line up columnsPadRight, PadLeft, Center, Truncate
Measure what the user seesWidth, and Cols for the terminal width
Remove colour codesStrip
Show progressNewBar with BarAdd and BarDraw, or NewSpinner
Ask for a passwordReadPassword
Read single keysMakeRaw or MakeCbreak, ReadKey, Restore
Draw a full screen viewEnterAltScreen, MoveTo, ClearScreen, ExitAltScreen

Types

Bar

struct Bar
A progress bar. Make one with NewBar and set the fields to change how it looks.
NameTypeDescription
totalint = 100The full value; 100 by default.
currentint = 0The current value.
widthint = 0The width of the bar in cells; zero means automatic, from the terminal width, between 8 and 80.
labelstr = ""The text that comes before the bar.
fillstr = "#"The character of the filled part.
headstr = ""The head character; when it is not empty it takes the last filled cell.
emptystr = "-"The character of the empty part.
colorint = 0The colour code of the filled part, such as FgGreen; zero means no colour.
show_percentbool = trueShow the percentage; on by default.
show_countbool = falseShow the count as 150/200.
show_etabool = falseShow the estimated time remaining.
hide_cursorbool = trueHide the cursor while drawing; on by default.
start_msi64 = 0The start time, used to work out the time remaining.
drawnbool = falseWhether the bar has been drawn at least once.
donebool = falseWhether the bar has finished.
term-Bar.salam
import term

func main:
    term.SetColorMode(term.ColorNever)
    mut b := term.NewBar(200, "download")
    b.width = 20
    b.fill = "█"
    b.empty = "░"
    term.BarSet(b, 50)
    println term.BarRender(b)
    term.BarAdd(b, 100)
    b.show_count = true
    println term.BarRender(b)
    mut s := term.NewSpinner("working")
    defer term.SpinnerFree(s)
    println s.label, s.frames.Len() > 0
    mut frames := Vector {} as Vector<str>
    frames.Push("◐")
    frames.Push("◓")
    mut s2 := term.NewSpinnerFrames("loading", frames)
    defer term.SpinnerFree(s2)
    repeat 3:
        println term.SpinnerFrame(s2)
        s2.idx = (s2.idx + 1) % frames.Len()
    end
end
Outputdownload [█████░░░░░░░░░░░░░░░] 25% download [███████████████░░░░░] 75% 150/200 working true ◐ ◓ ◐

Spinner

struct Spinner
A spinner: a "working on it" sign for work whose progress is not known.
NameTypeDescription
framesVectorThe frames of the spinner, shown in turn.
idxint = 0The index of the current frame.
labelstr = ""The text beside the spinner.
colorint = 0The colour code of the frame; zero means no colour.
drawnbool = falseWhether anything has been drawn on the screen.

The example for this item is shown with the ones above: term-Bar.salam

Key

struct Key
One key that was read.
NameTypeDescription
codeint = 0The kind of key; one of the Key constants.
chstr = ""The character, when the key is one.
ctrlbool = falseControl was held as well.
altbool = falseAlt was held as well.
shiftbool = falseShift was held as well.
rawstr = ""The raw bytes that came from the terminal.
term-Decode.salam
import term

func describe(k: term.Key): str:
    if k.code == term.KeyChar:
        ret "char " + k.ch + (k.ctrl ? " with ctrl" : "") + (k.alt ? " with alt" : "")
    else k.code == term.KeyUp:
        ret "up"
    else k.code == term.KeyEnter:
        ret "enter"
    else k.code == term.KeyEscape:
        ret "escape"
    else k.code >= term.KeyF1 and k.code < term.KeyF1 + 12:
        ret "f" + (k.code - term.KeyF1 + 1)
    end
    ret "code " + k.code
end

func main:
    each s in ["a", "\u001b[A", "\r", "\u001b", "\u0001", "\u001bx", "\u001bOQ", "\u001b[3~"]:
        println describe(term.Decode(s))
    end
    m := term.DecodeMouse("\u001b[<0;12;5M")
    println m.ok, m.button, m.col, m.row, m.pressed, m.motion
    println term.KeyDelete, term.KeyTab, term.KeyBackspace, term.KeySpace, term.KeyEOF, term.KeyUnknown
    println term.KeyDown, term.KeyRight, term.KeyLeft, term.KeyHome, term.KeyEnd, term.KeyPageUp, term.KeyPageDown, term.KeyInsert, term.KeyMouse, term.EscDelayMs
end
Outputchar a up enter escape char a with ctrl char x with alt f2 code 19 true 0 12 5 true false 19 3 4 6 7 0 11 12 13 14 15 16 17 18 50 50

MouseEvent

struct MouseEvent
One mouse event.
NameTypeDescription
buttonint = 0The button number: zero left, 1 middle, 2 right.
colint = 0The column, from 1.
rowint = 0The row, from 1.
pressedbool = falseThe button was pressed, not released.
motionbool = falseThe event is a movement.
okbool = falseThe sequence was read correctly.

The example for this item is shown with the ones above: term-Decode.salam

TermState

struct TermState
The saved state of the terminal, to put back with Restore.
NameTypeDescription
fdint = 0The file descriptor of the terminal.
savedvoid*The previous terminal settings on Unix.
mode_inint = 0The previous input mode on Windows.
mode_outint = 0The previous output mode on Windows.
okbool = falseWhether the mode change succeeded.
term-ReadKey.salam
import term

func main:
    if not term.IsTTY(term.StdinFd):
        printerrln "this program has to run in a terminal"
        ret 1
    end
    mut state := term.MakeRaw(term.StdinFd)
    defer term.Restore(state)
    term.Write("press a key (q to quit)\r\n")
    until true:
        if not term.KeyReady(500):
            continue
        end
        k := term.ReadKey()
        if k.code == term.KeyChar and k.ch == "q":
            break
        end
        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)
    ret 0
end

WinSize

struct WinSize
The size of the terminal window.
NameTypeDescription
colsint = 80The number of columns.
rowsint = 24The number of rows.
term-Size.salam
import term

func main:
    w := term.Size()
    println w.cols > 0, w.rows > 0, term.Cols() > 0, term.Rows() > 0
    t := term.IsTerminal()
    println t == term.IsTTY(term.StdoutFd)
    println term.StdinFd, term.StdoutFd, term.StderrFd
    term.SetColorMode(term.ColorAlways)
    println term.SupportsColor()
    c256 := term.Supports256Color()
    ctrue := term.SupportsTrueColor()
    println c256 or not c256, ctrue or not ctrue
end
Outputtrue true true true true 0 1 2 true true true

Constants and variables

Key codes Key…

The value of the code field of a Key. For the function keys, KeyF1 is the code of F1 and F2 through F12 follow it in order.
NameValue
KeyUnknown0
KeyChar1
KeyEnter2
KeyTab3
KeyBackspace4
KeyEscape5
KeySpace6
KeyEOF7
KeyUp10
KeyDown11
KeyRight12
KeyLeft13
KeyHome14
KeyEnd15
KeyPageUp16
KeyPageDown17
KeyInsert18
KeyDelete19
KeyF130
KeyMouse50

The example for this item is shown with the ones above: term-Decode.salam

EscDelayMs

const EscDelayMs: i32 = 50
How many milliseconds to wait after the escape key, to tell a lone escape from the start of a sequence.

The example for this item is shown with the ones above: term-Decode.salam

Reset

const Reset: str = ""
The sequence that removes every colour and style.
term-Color.salam
import term
import str

func show(s: str): str:
    ret str.Replace(s, term.Esc, "\\e")
end

func main:
    term.SetColorMode(term.ColorAlways)
    println show(term.Red("error")), show(term.Green("ok")), show(term.Yellow("warning"))
    println show(term.Bold("important")), show(term.Underline("link")), show(term.Italic("quote"))
    println show(term.Dim("a")), show(term.Blink("b")), show(term.Inverse("c")), show(term.Hidden("d")), show(term.Strike("e"))
    println show(term.Black("a")), show(term.Blue("b")), show(term.Magenta("c")), show(term.Cyan("d")), show(term.White("e")), show(term.Gray("f"))
    println show(term.BrightRed("a")), show(term.BrightGreen("b")), show(term.BrightYellow("c")), show(term.BrightBlue("d")), show(term.BrightMagenta("e")), show(term.BrightCyan("f")), show(term.BrightWhite("g"))
    println show(term.OnRed("a")), show(term.OnGreen("b")), show(term.OnYellow("c")), show(term.OnBlue("d")), show(term.OnMagenta("e")), show(term.OnCyan("f")), show(term.OnWhite("g"))
    println show(term.Color256("orange", 208)), show(term.OnColor256("x", 236))
    println show(term.RGB("hello", 255, 92, 0)), show(term.OnRGB("x", 10, 10, 10))
    println show(term.Style("x", term.StyleBold)), show(term.Paint("x", term.Sgr(term.FgRed)))
    println show(term.SeqFg256(208)), show(term.SeqBg256(17)), show(term.SeqFgRGB(1, 2, 3)), show(term.SeqBgRGB(4, 5, 6))
    println show(term.Reset), show(term.Csi)
    term.SetColorMode(term.ColorNever)
    println term.Red("no colour"), term.ColorMode() == term.ColorNever, term.ColorAuto
end
Output\e[31merror\e[0m \e[32mok\e[0m \e[33mwarning\e[0m \e[1mimportant\e[0m \e[4mlink\e[0m \e[3mquote\e[0m \e[2ma\e[0m \e[5mb\e[0m \e[7mc\e[0m \e[8md\e[0m \e[9me\e[0m \e[30ma\e[0m \e[34mb\e[0m \e[35mc\e[0m \e[36md\e[0m \e[37me\e[0m \e[90mf\e[0m \e[91ma\e[0m \e[92mb\e[0m \e[93mc\e[0m \e[94md\e[0m \e[95me\e[0m \e[96mf\e[0m \e[97mg\e[0m \e[41ma\e[0m \e[42mb\e[0m \e[43mc\e[0m \e[44md\e[0m \e[45me\e[0m \e[46mf\e[0m \e[47mg\e[0m \e[38;5;208morange\e[0m \e[48;5;236mx\e[0m \e[38;2;255;92;0mhello\e[0m \e[48;2;10;10;10mx\e[0m \e[1mx\e[0m \e[31mx\e[0m \e[38;5;208m \e[48;5;17m \e[38;2;1;2;3m \e[48;2;4;5;6m \e[0m \e[ no colour true 0

Style codes Style…

The display codes for text style; used with Style or Sgr.
NameValue
StyleBold1
StyleDim2
StyleItalic3
StyleUnderline4
StyleReverse7
StyleHidden8
StyleStrike9

The example for this item is shown with the ones above: term-Color.salam

Text colours Fg…

The text colour codes. Adding Bright to one of them gives the bright variant of the same colour, so 31 + 60 is bright red.
NameValue
FgBlack30
FgRed31
FgGreen32
FgYellow33
FgBlue34
FgMagenta35
FgCyan36
FgWhite37
FgDefault39
FgBright60

The example for this item is shown with the ones above: term-Color.salam

Background colours Bg…

The background colour codes; each is 10 more than the matching text colour.
NameValue
BgBlack40
BgRed41
BgGreen42
BgYellow43
BgBlue44
BgMagenta45
BgCyan46
BgWhite47
BgDefault49

The example for this item is shown with the ones above: term-Color.salam

Standard file descriptors Std…

The descriptors of standard input, output and error, for IsTTY and MakeRaw.
NameValue
StdinFd0
StdoutFd1
StderrFd2

The example for this item is shown with the ones above: term-Size.salam

Esc

const Esc: str = ""
The escape character, code 27, which starts every terminal sequence.

The example for this item is shown with the ones above: term-Color.salam

Csi

const Csi: str = "["
The control sequence introducer: escape followed by [.

The example for this item is shown with the ones above: term-Color.salam

Colour modes Color…

The values for SetColorMode. In automatic mode, colour is only written when the output is a terminal.
NameValue
ColorAuto0
ColorAlways1
ColorNever2

The example for this item is shown with the ones above: term-Color.salam

Functions

FormatDuration

func FormatDuration(ms: i64): str
Makes a duration in milliseconds readable, such as 9.5s or 1h 02m.
term-Width.salam
import term

func main:
    term.SetColorMode(term.ColorAlways)
    colored := term.Green("hello")
    println colored.Len(), term.Width(colored), term.Strip(colored)
    println term.Width("hello"), term.Width("日本"), term.Width("ab")
    term.SetColorMode(term.ColorNever)
    println "[" + term.Truncate("the Salam programming language", 10) + "]"
    println "[" + term.PadRight("name", 8) + "]", "[" + term.PadLeft("42", 6) + "]", "[" + term.Center("ok", 6) + "]"
    println term.FormatDuration(9500), term.FormatDuration(3721000)
    println term.FormatBytes(512), term.FormatBytes(1536), term.FormatBytes(3221225472)
end
Output14 5 hello 5 2 2 [the Salam ] [name ] [ 42] [ ok ] 9.5s 1h 02m 512 B 1.5 KB 3.0 GB

FormatBytes

func FormatBytes(n: i64): str
Writes a size with a fitting unit and one decimal, such as 512 B, 1.5 KB or 1.7 MB; each unit is 1024 times the one before.

The example for this item is shown with the ones above: term-Width.salam

NewBar

func NewBar(total: int, label: str): Bar
A new bar with a total and a label. In a UTF-8 environment it uses █ and ░, otherwise # and -.

The example for this item is shown with the ones above: term-Bar.salam

BarRender

func BarRender(b &: Bar): str
Returns the text of the bar without printing anything.

The example for this item is shown with the ones above: term-Bar.salam

BarDraw

func BarDraw(b &: Bar)
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

func main:
    mut b := term.NewBar(50, "processing")
    repeat 50:
        term.BarAdd(b, 1)
        term.BarDraw(b)
        time.Sleep(20)
    end
    term.BarFinish(b)
    mut s := term.NewSpinner("connecting to the server")
    repeat 20:
        term.SpinnerTick(s)
        time.Sleep(50)
    end
    term.SpinnerStop(s, "connected")
    term.SpinnerFree(s)
end

BarSet

func BarSet(b &: Bar, n: int)
Sets the current value, between zero and the total, and draws the bar.

The example for this item is shown with the ones above: term-Bar.salam

BarAdd

func BarAdd(b &: Bar, delta: int)
Adds to the current value and draws the bar.

The example for this item is shown with the ones above: term-Bar.salam

BarFinish

func BarFinish(b &: Bar)
Fills the bar, draws it one last time and moves to the next line. When the output is not a terminal it prints the final bar once, without colour.

The example for this item is shown with the ones above: term-Progress.salam

NewSpinner

func NewSpinner(label: str): Spinner
A new spinner with a label; the frames are braille dots in a UTF-8 environment and | / - \ otherwise.

The example for this item is shown with the ones above: term-Bar.salam

NewSpinnerFrames

func NewSpinnerFrames(label: str, frames: Vector<str>): Spinner
A spinner with frames of your own.

The example for this item is shown with the ones above: term-Bar.salam

SpinnerFrame

func SpinnerFrame(s &: Spinner): str
Returns the current frame.

The example for this item is shown with the ones above: term-Bar.salam

SpinnerTick

func SpinnerTick(s &: Spinner)
Draws the next frame on the same line. Call it in a loop with a short pause.

The example for this item is shown with the ones above: term-Progress.salam

SpinnerStop

func SpinnerStop(s &: Spinner, final: str)
Clears the spinner and, when a closing text is given, prints it on one line.

The example for this item is shown with the ones above: term-Progress.salam

SpinnerFree

func SpinnerFree(s &: Spinner)
Frees the memory of the spinner.

The example for this item is shown with the ones above: term-Bar.salam

Decode

func Decode(seq: str): Key
Turns a byte sequence from the terminal into a key, so \e[A is the up key. It is also how you test a program without a real terminal.

The example for this item is shown with the ones above: term-Decode.salam

DecodeMouse

func DecodeMouse(seq: str): MouseEvent
Reads an SGR mouse sequence, such as \e[<0;12;5M.

The example for this item is shown with the ones above: term-Decode.salam

ReadByte

func ReadByte(): int
Reads one byte from the input; -1 at the end of the input.

The example for this item is shown with the ones above: term-ReadKey.salam

KeyReady

func KeyReady(timeout_ms: int): bool
Waits up to the given time and returns true when a key is ready to read.

The example for this item is shown with the ones above: term-ReadKey.salam

ReadKey

func ReadKey(): Key
Reads one key. The terminal must already be in raw or cbreak mode.

The example for this item is shown with the ones above: term-ReadKey.salam

GetKey

func GetKey(): Key
Puts the terminal into cbreak mode itself, reads one key and gives the terminal state back.

The example for this item is shown with the ones above: term-ReadKey.salam

ReadPassword

func ReadPassword(prompt: str): str
Shows the prompt and reads a password without echoing it; backspace works and Ctrl+C gives an empty string.

The example for this item is shown with the ones above: term-ReadKey.salam

Sgr

func Sgr(code: int): str
The display sequence for one code, so code 1 is bold and 31 is red.

The example for this item is shown with the ones above: term-Color.salam

SeqFg256

func SeqFg256(n: int): str
The sequence for a text colour out of 256.

The example for this item is shown with the ones above: term-Color.salam

SeqBg256

func SeqBg256(n: int): str
The sequence for a background colour out of 256.

The example for this item is shown with the ones above: term-Color.salam

SeqFgRGB

func SeqFgRGB(r: int, g: int, b: int): str
The sequence for a text colour from red, green and blue parts.

The example for this item is shown with the ones above: term-Color.salam

SeqBgRGB

func SeqBgRGB(r: int, g: int, b: int): str
The sequence for a background colour from red, green and blue parts.

The example for this item is shown with the ones above: term-Color.salam

Paint

func Paint(s: str, prefix: str): str
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

Style

func Style(s: str, code: int): str
Dresses the text with one display code.

The example for this item is shown with the ones above: term-Color.salam

Bold

func Bold(s: str): str
Makes the text bold.

The example for this item is shown with the ones above: term-Color.salam

Dim

func Dim(s: str): str
Makes the text dim.

The example for this item is shown with the ones above: term-Color.salam

Italic

func Italic(s: str): str
Makes the text italic.

The example for this item is shown with the ones above: term-Color.salam

Underline

func Underline(s: str): str
Underlines the text.

The example for this item is shown with the ones above: term-Color.salam

func Blink(s: str): str
Makes the text blink.

The example for this item is shown with the ones above: term-Color.salam

Inverse

func Inverse(s: str): str
Swaps the text and background colours.

The example for this item is shown with the ones above: term-Color.salam

Hidden

func Hidden(s: str): str
Hides the text.

The example for this item is shown with the ones above: term-Color.salam

Strike

func Strike(s: str): str
Strikes the text through.

The example for this item is shown with the ones above: term-Color.salam

Black

func Black(s: str): str
Makes the text black.

The example for this item is shown with the ones above: term-Color.salam

Red

func Red(s: str): str
Makes the text red.

The example for this item is shown with the ones above: term-Color.salam

Green

func Green(s: str): str
Makes the text green.

The example for this item is shown with the ones above: term-Color.salam

Yellow

func Yellow(s: str): str
Makes the text yellow.

The example for this item is shown with the ones above: term-Color.salam

Blue

func Blue(s: str): str
Makes the text blue.

The example for this item is shown with the ones above: term-Color.salam

Magenta

func Magenta(s: str): str
Makes the text magenta.

The example for this item is shown with the ones above: term-Color.salam

Cyan

func Cyan(s: str): str
Makes the text cyan.

The example for this item is shown with the ones above: term-Color.salam

White

func White(s: str): str
Makes the text white.

The example for this item is shown with the ones above: term-Color.salam

Gray

func Gray(s: str): str
Makes the text gray.

The example for this item is shown with the ones above: term-Color.salam

BrightRed

func BrightRed(s: str): str
Makes the text bright red.

The example for this item is shown with the ones above: term-Color.salam

BrightGreen

func BrightGreen(s: str): str
Makes the text bright green.

The example for this item is shown with the ones above: term-Color.salam

BrightYellow

func BrightYellow(s: str): str
Makes the text bright yellow.

The example for this item is shown with the ones above: term-Color.salam

BrightBlue

func BrightBlue(s: str): str
Makes the text bright blue.

The example for this item is shown with the ones above: term-Color.salam

BrightMagenta

func BrightMagenta(s: str): str
Makes the text bright magenta.

The example for this item is shown with the ones above: term-Color.salam

BrightCyan

func BrightCyan(s: str): str
Makes the text bright cyan.

The example for this item is shown with the ones above: term-Color.salam

BrightWhite

func BrightWhite(s: str): str
Makes the text bright white.

The example for this item is shown with the ones above: term-Color.salam

OnRed

func OnRed(s: str): str
Makes the background of the text red.

The example for this item is shown with the ones above: term-Color.salam

OnGreen

func OnGreen(s: str): str
Makes the background of the text green.

The example for this item is shown with the ones above: term-Color.salam

OnYellow

func OnYellow(s: str): str
Makes the background of the text yellow.

The example for this item is shown with the ones above: term-Color.salam

OnBlue

func OnBlue(s: str): str
Makes the background of the text blue.

The example for this item is shown with the ones above: term-Color.salam

OnMagenta

func OnMagenta(s: str): str
Makes the background of the text magenta.

The example for this item is shown with the ones above: term-Color.salam

OnCyan

func OnCyan(s: str): str
Makes the background of the text cyan.

The example for this item is shown with the ones above: term-Color.salam

OnWhite

func OnWhite(s: str): str
Makes the background of the text white.

The example for this item is shown with the ones above: term-Color.salam

Color256

func Color256(s: str, n: int): str
Writes the text in one of 256 colours.

The example for this item is shown with the ones above: term-Color.salam

OnColor256

func OnColor256(s: str, n: int): str
Makes the background one of 256 colours.

The example for this item is shown with the ones above: term-Color.salam

RGB

func RGB(s: str, r: int, g: int, b: int): str
Writes the text in any red, green and blue colour.

The example for this item is shown with the ones above: term-Color.salam

OnRGB

func OnRGB(s: str, r: int, g: int, b: int): str
Makes the background any red, green and blue colour.

The example for this item is shown with the ones above: term-Color.salam

Strip

func Strip(s: str): str
Removes every escape sequence from the text.

The example for this item is shown with the ones above: term-Width.salam

Width

func Width(s: str): int
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

Truncate

func Truncate(s: str, n: int): str
Shortens the text to at most n characters as Width counts them, keeping the colour codes intact.

The example for this item is shown with the ones above: term-Width.salam

PadRight

func PadRight(s: str, n: int): str
Pads with spaces on the right until the width is n; for laying out columns.

The example for this item is shown with the ones above: term-Width.salam

PadLeft

func PadLeft(s: str, n: int): str
Pads with spaces on the left until the width is n.

The example for this item is shown with the ones above: term-Width.salam

Center

func Center(s: str, n: int): str
Centres the text in a width of n.

The example for this item is shown with the ones above: term-Width.salam

Write

func Write(s: str)
Writes the text to the output with no newline.
term-Screen.salam
import term

func main:
    term.EnableAnsi()
    term.SetTitle("dashboard")
    term.EnterAltScreen()
    term.HideCursor()
    term.ClearScreen()
    term.Home()
    term.MoveTo(2, 4)
    term.Write(term.Bold("hello from the dashboard"))
    term.SaveCursor()
    term.Down(2)
    term.Right(4)
    term.Emit("status: good")
    term.RestoreCursor()
    term.Up(1)
    term.Left(1)
    term.NextLine(1)
    term.PrevLine(1)
    term.Column(1)
    term.ClearLine()
    term.ClearToLineEnd()
    term.ClearBelow()
    term.ResetLine()
    term.SetScrollRegion(3, term.Rows() - 1)
    term.ScrollUp(1)
    term.ScrollDown(1)
    term.InsertLines(1)
    term.DeleteLines(1)
    term.ResetScrollRegion()
    term.EnableMouse()
    term.DisableMouse()
    term.Bell()
    term.Flush()
    term.ClearScrollback()
    term.ShowCursor()
    term.ExitAltScreen()
    term.WriteErr("done\n")
    w := term.Size()
    println w.cols, w.rows, term.Cols()
end

WriteErr

func WriteErr(s: str)
Writes the text to the error output.

The example for this item is shown with the ones above: term-Screen.salam

Flush

func Flush()
Shows whatever is still sitting in the output, right now.

The example for this item is shown with the ones above: term-Screen.salam

Emit

func Emit(s: str)
Writes and flushes straight away.

The example for this item is shown with the ones above: term-Screen.salam

IsTTY

func IsTTY(fd: int): bool
True when this file descriptor is attached to a terminal; false when the output goes to a file or a pipe.

The example for this item is shown with the ones above: term-Size.salam

IsTerminal

func IsTerminal(): bool
True when the standard output is a terminal.

The example for this item is shown with the ones above: term-Size.salam

Size

func Size(): WinSize
The size of the terminal window; 80 columns and 24 rows when it is not known.

The example for this item is shown with the ones above: term-Size.salam

Cols

func Cols(): int
The number of terminal columns.

The example for this item is shown with the ones above: term-Size.salam

Rows

func Rows(): int
The number of terminal rows.

The example for this item is shown with the ones above: term-Size.salam

SetColorMode

func SetColorMode(mode: int)
Sets how colour behaves: automatic, always or never. Useful for an option such as --color.

The example for this item is shown with the ones above: term-Color.salam

ColorMode

func ColorMode(): int
The current colour mode.

The example for this item is shown with the ones above: term-Color.salam

SupportsColor

func SupportsColor(): bool
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

Supports256Color

func Supports256Color(): bool
True when TERM contains 256color or COLORTERM is set.

The example for this item is shown with the ones above: term-Size.salam

SupportsTrueColor

func SupportsTrueColor(): bool
True when COLORTERM is truecolor or 24bit.

The example for this item is shown with the ones above: term-Size.salam

EnableAnsi

func EnableAnsi(): bool
Turns on terminal sequence processing on Windows; does nothing and returns true elsewhere.

The example for this item is shown with the ones above: term-Screen.salam

MakeRaw

func MakeRaw(fd: int): TermState
Puts the terminal into raw mode: every key arrives at once and is not echoed, and Ctrl+C is just another key. Returns the previous state.

The example for this item is shown with the ones above: term-ReadKey.salam

MakeCbreak

func MakeCbreak(fd: int): TermState
Puts the terminal into cbreak mode: keys arrive at once and are not echoed, but Ctrl+C still ends the program.

The example for this item is shown with the ones above: term-ReadKey.salam

Restore

func Restore(st &: TermState): bool
Puts the saved state back. Best called with defer right after the mode change.

The example for this item is shown with the ones above: term-ReadKey.salam

Bell

func Bell()
Rings the terminal bell.

The example for this item is shown with the ones above: term-Screen.salam

SeqTitle

func SeqTitle(title: str): str
The sequence that changes the window title.
term-Seq.salam
import term
import str

func show(s: str): str:
    ret str.Replace(str.Replace(s, term.Esc, "\\e"), "\u0007", "\\a")
end

func main:
    println show(term.SeqUp(2)), show(term.SeqDown(1)), show(term.SeqRight(3)), show(term.SeqLeft(3))
    println show(term.SeqNextLine(1)), show(term.SeqPrevLine(1)), show(term.SeqColumn(10)), show(term.SeqMoveTo(5, 20)), show(term.SeqHome())
    println show(term.SeqSaveCursor()), show(term.SeqRestoreCursor()), show(term.SeqHideCursor()), show(term.SeqShowCursor())
    println show(term.SeqClearScreen()), show(term.SeqClearScrollback()), show(term.SeqClearLine())
    println show(term.SeqClearToLineEnd()), show(term.SeqClearToLineStart()), show(term.SeqClearBelow()), show(term.SeqClearAbove()), show(term.SeqResetLine())
    println show(term.SeqScrollUp(2)), show(term.SeqScrollDown(2)), show(term.SeqInsertLines(1)), show(term.SeqDeleteLines(1))
    println show(term.SeqScrollRegion(2, 20)), show(term.SeqResetScrollRegion())
    println show(term.SeqEnterAltScreen()), show(term.SeqExitAltScreen())
    println show(term.SeqEnableMouse()), show(term.SeqEnableMouseMotion()), show(term.SeqDisableMouse())
    println show(term.SeqTitle("my program"))
end
Output\e[2A \e[1B \e[3C \e[3D \e[1E \e[1F \e[10G \e[5;20H \e[H \e7 \e8 \e[?25l \e[?25h \e[2J\e[H \e[3J \e[2K \e[K \e[1K \e[J \e[1J \e[2K \e[2S \e[2T \e[1L \e[1M \e[2;20r \e[r \e[?1049h \e[?1049l \e[?1000h\e[?1006h \e[?1003h\e[?1006h \e[?1006l\e[?1003l\e[?1002l\e[?1000l \e]0;my program\a

SetTitle

func SetTitle(title: str)
Changes the title of the terminal window.

The example for this item is shown with the ones above: term-Screen.salam

SeqUp

func SeqUp(n: int): str
The sequence that moves the cursor n rows up.

The example for this item is shown with the ones above: term-Seq.salam

SeqDown

func SeqDown(n: int): str
The sequence that moves the cursor n rows down.

The example for this item is shown with the ones above: term-Seq.salam

SeqRight

func SeqRight(n: int): str
The sequence that moves the cursor n columns right.

The example for this item is shown with the ones above: term-Seq.salam

SeqLeft

func SeqLeft(n: int): str
The sequence that moves the cursor n columns left.

The example for this item is shown with the ones above: term-Seq.salam

SeqNextLine

func SeqNextLine(n: int): str
The sequence that moves the cursor to the start of the nth next row.

The example for this item is shown with the ones above: term-Seq.salam

SeqPrevLine

func SeqPrevLine(n: int): str
The sequence that moves the cursor to the start of the nth previous row.

The example for this item is shown with the ones above: term-Seq.salam

SeqColumn

func SeqColumn(col: int): str
The sequence that moves the cursor to the given column.

The example for this item is shown with the ones above: term-Seq.salam

SeqMoveTo

func SeqMoveTo(row: int, col: int): str
The sequence that moves the cursor to the given row and column, both from 1.

The example for this item is shown with the ones above: term-Seq.salam

SeqHome

func SeqHome(): str
The sequence that moves the cursor to the top corner.

The example for this item is shown with the ones above: term-Seq.salam

SeqSaveCursor

func SeqSaveCursor(): str
The sequence that saves the cursor position.

The example for this item is shown with the ones above: term-Seq.salam

SeqRestoreCursor

func SeqRestoreCursor(): str
The sequence that goes back to the saved position.

The example for this item is shown with the ones above: term-Seq.salam

SeqHideCursor

func SeqHideCursor(): str
The sequence that hides the cursor.

The example for this item is shown with the ones above: term-Seq.salam

SeqShowCursor

func SeqShowCursor(): str
The sequence that shows the cursor again.

The example for this item is shown with the ones above: term-Seq.salam

SeqClearScreen

func SeqClearScreen(): str
The sequence that clears the whole screen.

The example for this item is shown with the ones above: term-Seq.salam

SeqClearScrollback

func SeqClearScrollback(): str
The sequence that clears the text which has scrolled off the screen.

The example for this item is shown with the ones above: term-Seq.salam

SeqClearLine

func SeqClearLine(): str
The sequence that clears the whole current line.

The example for this item is shown with the ones above: term-Seq.salam

SeqClearToLineEnd

func SeqClearToLineEnd(): str
The sequence that clears from the cursor to the end of the line.

The example for this item is shown with the ones above: term-Seq.salam

SeqClearToLineStart

func SeqClearToLineStart(): str
The sequence that clears from the start of the line to the cursor.

The example for this item is shown with the ones above: term-Seq.salam

SeqClearBelow

func SeqClearBelow(): str
The sequence that clears from the cursor to the bottom of the screen.

The example for this item is shown with the ones above: term-Seq.salam

SeqClearAbove

func SeqClearAbove(): str
The sequence that clears from the top of the screen to the cursor.

The example for this item is shown with the ones above: term-Seq.salam

SeqResetLine

func SeqResetLine(): str
The sequence that goes to the start of the line and clears it.

The example for this item is shown with the ones above: term-Seq.salam

SeqScrollUp

func SeqScrollUp(n: int): str
The sequence that scrolls the screen contents up by n rows.

The example for this item is shown with the ones above: term-Seq.salam

SeqScrollDown

func SeqScrollDown(n: int): str
The sequence that scrolls the screen contents down by n rows.

The example for this item is shown with the ones above: term-Seq.salam

SeqInsertLines

func SeqInsertLines(n: int): str
The sequence that inserts n empty lines at the cursor.

The example for this item is shown with the ones above: term-Seq.salam

SeqDeleteLines

func SeqDeleteLines(n: int): str
The sequence that deletes n lines from the cursor.

The example for this item is shown with the ones above: term-Seq.salam

SeqScrollRegion

func SeqScrollRegion(top: int, bottom: int): str
The sequence that limits scrolling to the rows top through bottom.

The example for this item is shown with the ones above: term-Seq.salam

SeqResetScrollRegion

func SeqResetScrollRegion(): str
The sequence that puts the scroll region back to the whole screen.

The example for this item is shown with the ones above: term-Seq.salam

SeqEnterAltScreen

func SeqEnterAltScreen(): str
The sequence that switches to the alternate screen.

The example for this item is shown with the ones above: term-Seq.salam

SeqExitAltScreen

func SeqExitAltScreen(): str
The sequence that comes back from the alternate screen.

The example for this item is shown with the ones above: term-Seq.salam

SeqEnableMouse

func SeqEnableMouse(): str
The sequence that turns on mouse click reporting.

The example for this item is shown with the ones above: term-Seq.salam

SeqEnableMouseMotion

func SeqEnableMouseMotion(): str
The sequence that turns on mouse click and movement reporting.

The example for this item is shown with the ones above: term-Seq.salam

SeqDisableMouse

func SeqDisableMouse(): str
The sequence that turns mouse reporting off.

The example for this item is shown with the ones above: term-Seq.salam

Up

func Up(n: int)
Moves the cursor n rows up.

The example for this item is shown with the ones above: term-Screen.salam

Down

func Down(n: int)
Moves the cursor n rows down.

The example for this item is shown with the ones above: term-Screen.salam

func Right(n: int)
Moves the cursor n columns right.

The example for this item is shown with the ones above: term-Screen.salam

Left

func Left(n: int)
Moves the cursor n columns left.

The example for this item is shown with the ones above: term-Screen.salam

NextLine

func NextLine(n: int)
Moves the cursor to the start of the nth next row.

The example for this item is shown with the ones above: term-Screen.salam

PrevLine

func PrevLine(n: int)
Moves the cursor to the start of the nth previous row.

The example for this item is shown with the ones above: term-Screen.salam

Column

func Column(col: int)
Moves the cursor to the given column.

The example for this item is shown with the ones above: term-Screen.salam

MoveTo

func MoveTo(row: int, col: int)
Moves the cursor to the given row and column, both from 1.

The example for this item is shown with the ones above: term-Screen.salam

Home

func Home()
Moves the cursor to the top corner.

The example for this item is shown with the ones above: term-Screen.salam

SaveCursor

func SaveCursor()
Saves the current cursor position.

The example for this item is shown with the ones above: term-Screen.salam

RestoreCursor

func RestoreCursor()
Moves the cursor back to the saved position.

The example for this item is shown with the ones above: term-Screen.salam

HideCursor

func HideCursor()
Hides the cursor.

The example for this item is shown with the ones above: term-Screen.salam

ShowCursor

func ShowCursor()
Shows the cursor again.

The example for this item is shown with the ones above: term-Screen.salam

ClearScreen

func ClearScreen()
Clears the whole screen.

The example for this item is shown with the ones above: term-Screen.salam

ClearScrollback

func ClearScrollback()
Clears the text which has scrolled off the screen.

The example for this item is shown with the ones above: term-Screen.salam

ClearLine

func ClearLine()
Clears the whole current line.

The example for this item is shown with the ones above: term-Screen.salam

ClearToLineEnd

func ClearToLineEnd()
Clears from the cursor to the end of the line.

The example for this item is shown with the ones above: term-Screen.salam

ClearBelow

func ClearBelow()
Clears from the cursor to the bottom of the screen.

The example for this item is shown with the ones above: term-Screen.salam

ResetLine

func ResetLine()
Goes to the start of the line and clears it, so the same line can be written again.

The example for this item is shown with the ones above: term-Screen.salam

ScrollUp

func ScrollUp(n: int)
Scrolls the screen contents up by n rows.

The example for this item is shown with the ones above: term-Screen.salam

ScrollDown

func ScrollDown(n: int)
Scrolls the screen contents down by n rows.

The example for this item is shown with the ones above: term-Screen.salam

InsertLines

func InsertLines(n: int)
Inserts n empty lines at the cursor.

The example for this item is shown with the ones above: term-Screen.salam

DeleteLines

func DeleteLines(n: int)
Deletes n lines from the cursor.

The example for this item is shown with the ones above: term-Screen.salam

SetScrollRegion

func SetScrollRegion(top: int, bottom: int)
Limits scrolling to the rows top through bottom, to keep a header still, for instance.

The example for this item is shown with the ones above: term-Screen.salam

ResetScrollRegion

func ResetScrollRegion()
Puts the scroll region back to the whole screen.

The example for this item is shown with the ones above: term-Screen.salam

EnterAltScreen

func EnterAltScreen()
Switches to the alternate screen, the way editors do, so the previous screen comes back intact on exit.

The example for this item is shown with the ones above: term-Screen.salam

ExitAltScreen

func ExitAltScreen()
Comes back from the alternate screen.

The example for this item is shown with the ones above: term-Screen.salam

EnableMouse

func EnableMouse()
Turns on mouse click reporting; the events are read like keys.

The example for this item is shown with the ones above: term-Screen.salam

DisableMouse

func DisableMouse()
Turns mouse reporting off.

The example for this item is shown with the ones above: term-Screen.salam