tty

TTY and ANSI color-support detection.

This module answers two questions a CLI program asks at startup:

  1. Is this stream connected to a terminal? (is_tty)
  2. What level of ANSI color does it support? (detect_color_level)

Types

Level of ANSI color support detected for a stream. This variant set is intentionally stable for 1.x.

case tty.detect_color_level(Stdout) {
  NoColor -> render_plain_text()
  Basic -> render_basic_ansi()
  Ansi256 -> render_256_color()
  TrueColor -> render_rgb_color()
}
pub type ColorLevel {
  NoColor
  Basic
  Ansi256
  TrueColor
}

Constructors

  • NoColor

    No ANSI escape codes should be emitted.

  • Basic

    16-color (basic ANSI) is supported.

  • Ansi256

    256-color (xterm-256) is supported.

  • TrueColor

    24-bit truecolor (RGB) is supported.

The standard I/O streams of the running process. This variant set is intentionally stable for 1.x.

pub type Stream {
  Stdin
  Stdout
  Stderr
}

Constructors

  • Stdin

    Standard input.

  • Stdout

    Standard output.

  • Stderr

    Standard error.

Values

pub fn color_level_at_least(
  actual actual: ColorLevel,
  at_least required: ColorLevel,
) -> Bool

Returns True if the actual color level is at least as capable as the required level. Use this to gate features without matching every variant:

let level = tty.detect_color_level(Stdout)
case tty.color_level_at_least(actual: level, at_least: Ansi256) {
  True -> render_256_color()
  False -> render_basic()
}
pub fn color_level_compare(
  a: ColorLevel,
  b: ColorLevel,
) -> order.Order

Orders two color levels by capability, where NoColor < Basic < Ansi256 < TrueColor. Returns a gleam/order Order, so it composes with list.sort, order.reverse, and friends.

tty.color_level_compare(Basic, Ansi256)
// -> order.Lt
pub fn detect_color_level(stream: Stream) -> ColorLevel

Detects color support for a stream, honoring NO_COLOR, FORCE_COLOR, CI, TERM, and COLORTERM environment variables.

On the JavaScript target this reads process.env, so it requires a Node-style runtime.

When a JavaScript runtime does not provide process or process.env, environment variables are treated as unset and this function falls back to NoColor unless other forced inputs are available.

case tty.detect_color_level(Stdout) {
  NoColor -> render_without_ansi()
  Basic -> render_with_basic_ansi()
  Ansi256 -> render_with_256_colors()
  TrueColor -> render_with_truecolor()
}
pub fn is_tty(stream: Stream) -> Bool

Returns True if the given stream is connected to a terminal.

On the Erlang target this uses io:getopts/1 (requires OTP 26+). If terminal options cannot be read, this returns False. On the JavaScript target this uses process.stdin.isTTY, process.stdout.isTTY, or process.stderr.isTTY, so it requires a Node-style runtime with those streams.

case tty.is_tty(Stdout) {
  True -> show_spinner()
  False -> print_plain_progress()
}
Search Document