termenv

repository·master·Indexed 24 days ago

https://github.com/muesli/termenv

A Go library for safe and convenient terminal styling. It provides tools for ANSI escape sequences, color conversions with automatic degradation (TrueColor, ANSI256, ANSI, Ascii), and terminal capability detection. Features include cursor positioning, screen management, mouse mode, bracketed paste mode, and support for OSC 52 (clipboard), OSC 8 (hyperlinks), and OSC 777 (notifications). It also includes specific support for enabling Virtual Terminal Processing on Windows.

Tokens
8K
Snippets
19
Records
69
Agent score
84%

What's inside termenv

  1. Understand terminal color profiles

    master

    The output.Profile property returns the detected color capabilities of the terminal. termenv automatically degrades colors to the best matching available profile if the terminal has limited support:

    TrueColor (24-bit RGB) => ANSI256 => ANSI (16 colors) => Ascii (no ANSI support).

    Available profiles:

    • termenv.Ascii: No ANSI support detected.
    • termenv.ANSI: 16 color ANSI support.
    • termenv.ANSI256: Extended 256 color ANSI support.
    • termenv.TrueColor: RGB/TrueColor support.

    To respect environment variables like NO_COLOR and CLICOLOR_FORCE, use termenv.EnvColorProfile instead of the standard detection.

  2. Enable ANSI processing on Windows

    master

    While Unix systems support ANSI styling by default, Windows requires you to explicitly enable Virtual Terminal Processing. Use termenv.EnableVirtualTerminalProcessing to ensure your terminal application can process ANSI sequences. This method is safe to call on non-Windows systems or when the output is not a terminal (e.g., during testing).

        restoreConsole, err := termenv.EnableVirtualTerminalProcessing(termenv.DefaultOutput())
        if err != nil {
            panic(err)
        }
        defer restoreConsole()
  3. Change Background Color via ANSI escape sequences

    master

    You can change the terminal's background color by sending an ANSI escape sequence containing the desired hex color code. The format is \033]11;#RRGGBB\007.

    echo -ne "\033]11;#00ff00\007"
  4. Initialize a termenv Output

    master

    To start using termenv, create a new output instance targeting a writer (usually os.Stdout). This instance provides the API for styling, positioning, and terminal control.

    output := termenv.NewOutput(os.Stdout)
  5. Change Foreground Color via ANSI escape sequences

    master

    You can change the terminal's foreground color by sending an ANSI escape sequence containing the desired hex color code. The format is \033]10;#RRGGBB\007.

    echo -ne "\033]10;#0000ff\007"