std/terminal
Source Edit This module contains a few procedures to control the terminal (also called console). On UNIX, the implementation simply uses ANSI escape sequences and does not depend on any other module, on Windows it uses the Windows API. Changing the style is permanent even after program termination! Use the code exitprocs.addExitProc(resetAttributes) to restore the defaults. Similarly, if you hide the cursor, make sure to unhide it with showCursor before quitting.
Progress bar
Basic progress bar example:
Example: cmd: -r:off
import std/terminal
import std/[os, strutils]
for i in 0..100:
stdout.styledWriteLine(fgRed, "0% ", fgWhite, '#'.repeat i, if i > 50: fgGreen else: fgYellow, "\t", $i , "%")
sleep 42
cursorUp 1
eraseLine()
stdout.resetAttributes()
Playing with colorful and styled text
Procs like
styledWriteLine,
styledEcho etc. have a temporary effect on text parameters. Style parameters only affect the text parameter right after them. After being called, these procs will reset the default style of the terminal. While
setBackGroundColor,
setForeGroundColor etc. have a lasting influence on the terminal, you can use
resetAttributes to reset the default style of the terminal.
Example: cmd: -r:off
import std/terminal
stdout.styledWriteLine({styleBright, styleBlink, styleUnderscore}, "styled text ")
stdout.styledWriteLine(fgRed, "red text ")
stdout.styledWriteLine(fgWhite, bgRed, "white text in red background")
stdout.styledWriteLine(" ordinary text without style ")
stdout.setBackGroundColor(bgCyan, true)
stdout.setForeGroundColor(fgBlue)
stdout.write("blue text in cyan background")
stdout.resetAttributes()
# You can specify multiple text parameters. Style parameters
# only affect the text parameter right after them.
styledEcho styleBright, fgGreen, "[PASS]", resetStyle, fgGreen, " Yay!"
stdout.styledWriteLine(fgRed, "red text ", styleBright, "bold red", fgDefault, " bold text") Imports
macros, strformat, strutils, colors, winlean, winlean, os, os
Types
BackgroundColor = enum
bgBlack = 40, ## black
bgRed, ## red
bgGreen, ## green
bgYellow, ## yellow
bgBlue, ## blue
bgMagenta, ## magenta
bgCyan, ## cyan
bgWhite, ## white
bg8Bit, ## 256-color (not supported, see `enableTrueColors` instead.)
bgDefault ## default terminal background color
- Terminal's background colors. Source Edit
ForegroundColor = enum
fgBlack = 30, ## black
fgRed, ## red
fgGreen, ## green
fgYellow, ## yellow
fgBlue, ## blue
fgMagenta, ## magenta
fgCyan, ## cyan
fgWhite, ## white
fg8Bit, ## 256-color (not supported, see `enableTrueColors` instead.)
fgDefault ## default terminal foreground color
- Terminal's foreground colors. Source Edit
Style = enum
styleBright = 1, ## bright text
styleDim, ## dim text
styleItalic, ## italic (or reverse on terminals not supporting)
styleUnderscore, ## underscored text
styleBlink, ## blinking/bold text
styleBlinkRapid, ## rapid blinking/bold text (not widely supported)
styleReverse, ## reverse
styleHidden, ## hidden text
styleStrikethrough ## strikethrough
- Different styles for text output. Source Edit
TerminalCmd = enum
resetStyle, ## reset attributes
fgColor, ## set foreground's true color
bgColor ## set background's true color
- commands that can be expressed as arguments Source Edit
Consts
Procs
proc ansiBackgroundColorCode(color: Color): string {....raises: [], tags: [],
forbids: [].} - Source Edit
proc ansiForegroundColorCode(color: Color): string {....raises: [], tags: [],
forbids: [].} - Source Edit
proc ansiForegroundColorCode(fg: ForegroundColor; bright = false): string {.
...raises: [], tags: [], forbids: [].} - Source Edit
proc ansiStyleCode(style: int): string {....raises: [], tags: [], forbids: [].} - Source Edit
proc cursorBackward(f: File; count = 1) {....raises: [OSError], tags: [RootEffect],
forbids: [].} - Moves the cursor backward by
count columns. Example: cmd: -r:off
stdout.cursorBackward(2)
write(stdout, "Hello World!") # anything written at that location will be erased/replaced with this
Source Edit proc cursorDown(f: File; count = 1) {....raises: [OSError], tags: [RootEffect],
forbids: [].} - Moves the cursor down by
count rows. Example: cmd: -r:off
stdout.cursorDown(2)
write(stdout, "Hello World!") # anything written at that location will be erased/replaced with this
Source Edit proc cursorForward(f: File; count = 1) {....raises: [OSError], tags: [RootEffect],
forbids: [].} - Moves the cursor forward by
count columns. Example: cmd: -r:off
stdout.cursorForward(2)
write(stdout, "Hello World!") # anything written at that location will be erased/replaced with this
Source Edit proc cursorUp(f: File; count = 1) {....raises: [OSError], tags: [RootEffect],
forbids: [].} - Moves the cursor up by
count rows. Example: cmd: -r:off
stdout.cursorUp(2)
write(stdout, "Hello World!") # anything written at that location will be erased/replaced with this
Source Edit proc disableTrueColors() {....raises: [], tags: [RootEffect, ReadEnvEffect],
forbids: [].} - Disables true color. Source Edit
proc enableTrueColors() {....raises: [], tags: [RootEffect, ReadEnvEffect],
forbids: [].} - Enables true color. Source Edit
proc eraseLine(f: File) {....raises: [OSError], tags: [RootEffect], forbids: [].} - Erases the entire current line.
Example: cmd: -r:off
write(stdout, "never mind")
stdout.eraseLine() # nothing will be printed on the screen
Source Edit proc eraseScreen(f: File) {....raises: [OSError], tags: [RootEffect], forbids: [].} - Erases the screen with the background colour and moves the cursor to home. Source Edit
proc getch(): char {....raises: [], tags: [], forbids: [].} - Reads a single character from the terminal, blocking until it is entered. The character is not printed to the terminal. Source Edit
proc getCursorPos(): tuple[x, y: int] {....raises: [ValueError, IOError, OSError],
tags: [], forbids: [].} - Source Edit
proc hideCursor(f: File) {....raises: [OSError], tags: [RootEffect], forbids: [].} - Hides the cursor. Source Edit
proc isatty(f: File): bool {....raises: [], tags: [], forbids: [].} - Returns true if
f is associated with a terminal device. Source Edit proc isTrueColorSupported(): bool {....raises: [], tags: [RootEffect], forbids: [].} - Returns true if a terminal supports true color. Source Edit
proc readPasswordFromStdin(prompt = "password: "): string {....raises: [IOError],
tags: [ReadIOEffect, WriteIOEffect], forbids: [].} - Reads a password from stdin without printing it. Source Edit
proc readPasswordFromStdin(prompt: string; password: var string): bool {.
...tags: [ReadIOEffect, WriteIOEffect], raises: [IOError], forbids: [].} - Reads a
password from stdin without printing it. password must not be nil! Returns false if the end of the file has been reached, true otherwise. Source Edit proc resetAttributes() {.noconv, ...raises: [], tags: [RootEffect], forbids: [].} - Resets all attributes on stdout. It is advisable to register this as a quit proc with
exitprocs.addExitProc(resetAttributes). Source Edit proc resetAttributes(f: File) {....raises: [], tags: [RootEffect], forbids: [].} - Resets all attributes. Source Edit
proc setBackgroundColor(f: File; bg: BackgroundColor; bright = false) {.
...raises: [], tags: [RootEffect], forbids: [].} - Sets the terminal's background color. Source Edit
proc setBackgroundColor(f: File; color: Color) {....raises: [IOError],
tags: [RootEffect, WriteIOEffect], forbids: [].} - Sets the terminal's background true color. Source Edit
proc setCursorPos(f: File; x, y: int) {....raises: [OSError], tags: [RootEffect],
forbids: [].} - Sets the terminal's cursor to the (x,y) position. (0,0) is the upper left of the screen. Source Edit
proc setCursorXPos(f: File; x: int) {....raises: [OSError], tags: [RootEffect],
forbids: [].} - Sets the terminal's cursor to the x position. The y position is not changed. Source Edit
proc setCursorYPos(f: File; y: int) {....raises: [OSError], tags: [RootEffect],
forbids: [].} - Sets the terminal's cursor to the y position. The x position is not changed. .. warning:: This is not supported on UNIX! Source Edit
proc setForegroundColor(f: File; color: Color) {....raises: [IOError],
tags: [RootEffect, WriteIOEffect], forbids: [].} - Sets the terminal's foreground true color. Source Edit
proc setForegroundColor(f: File; fg: ForegroundColor; bright = false) {.
...raises: [], tags: [RootEffect], forbids: [].} - Sets the terminal's foreground color. Source Edit
proc setStyle(f: File; style: set[Style]) {....raises: [], tags: [RootEffect],
forbids: [].} - Sets the terminal style. Source Edit
proc showCursor(f: File) {....raises: [OSError], tags: [RootEffect], forbids: [].} - Shows the cursor. Source Edit
proc terminalHeight(): int {....raises: [], tags: [], forbids: [].} - Returns the terminal height in rows. Source Edit
proc terminalHeightIoctl(handles: openArray[Handle]): int {....raises: [],
tags: [], forbids: [].} - Source Edit
proc terminalSize(): tuple[w, h: int] {....raises: [], tags: [], forbids: [].} - Returns the terminal width and height as a tuple. Internally calls
terminalWidth and terminalHeight, so the same assumptions apply. Source Edit proc terminalWidth(): int {....raises: [], tags: [], forbids: [].} - Returns the terminal width in columns. Source Edit
proc terminalWidthIoctl(handles: openArray[Handle]): int {....raises: [], tags: [],
forbids: [].} - Source Edit
proc writeStyled(txt: string; style: set[Style] = {styleBright}) {.
...raises: [IOError], tags: [RootEffect, WriteIOEffect], forbids: [].} - Writes the text
txt in a given style to stdout. Source Edit
Macros
macro styledWrite(f: File; m: varargs[typed]): untyped
- Similar to
write, but treating terminal style arguments specially. When some argument is Style, set[Style], ForegroundColor, BackgroundColor or TerminalCmd then it is not sent directly to f, but instead corresponding terminal style proc is called. Example: cmd: -r:off
stdout.styledWrite(fgRed, "red text ")
stdout.styledWrite(fgGreen, "green text")
Source Edit
Templates
template ansiBackgroundColorCode(color: static[Color]): string
- Source Edit
template ansiForegroundColorCode(color: static[Color]): string
- Source Edit
template ansiForegroundColorCode(fg: static[ForegroundColor];
bright: static[bool] = false): string - Source Edit
template ansiStyleCode(style: static[Style]): string
- Source Edit
template ansiStyleCode(style: Style): string
- Source Edit
template setBackgroundColor(bg: BackgroundColor; bright = false)
- Source Edit
template setBackgroundColor(color: Color)
- Source Edit
template setForegroundColor(color: Color)
- Source Edit
template setForegroundColor(fg: ForegroundColor; bright = false)
- Source Edit
template styledEcho(args: varargs[untyped])
- Echoes styles arguments to stdout using
styledWriteLine. Source Edit template styledWriteLine(f: File; args: varargs[untyped])
- Calls
styledWrite and appends a newline at the end. Example:
proc error(msg: string) =
styledWriteLine(stderr, fgRed, "Error: ", resetStyle, msg)
Source Edit