std::terminal
Terminal Module
Semantic terminal helpers for ANSI-capable command-line applications.
Purpose
Use this module when a program needs readable terminal intent instead of manually assembling ANSI fragments.
The public API answers questions like:
- “How do I render text in red and then reset the terminal?”
- “How do I clear the screen or move the cursor?”
- “How do I avoid styling output when stdout is not a terminal?”
The module intentionally does not expose raw ANSI assembly as the primary
contract. Callers work with Terminal::Style, Terminal::Screen, and
Terminal::Cursor, while private helpers translate those semantic requests
into escape sequences.
Quick path
- Build a style with
Terminal::Style::new(). - Apply colors and attributes.
- Call
apply(text)or usecolorText/styledText. - Check
isOutputTerminal()before styling if plain output is required for redirected streams.
Public surface
| Area | API | Use when |
|---|---|---|
| Text styling | Terminal::Style, colorText, styledText, reset |
You want semantic color/attribute output with automatic trailing reset |
| Screen control | Terminal::Screen::clear, clearLine |
You need simple full-screen or line clearing |
| Cursor control | Terminal::Cursor::{moveTo, save, restore, hide, show} |
You need TUI-style cursor positioning or visibility control |
| Capability checks | isInputTerminal, isOutputTerminal, isErrorTerminal |
You need to branch on whether a file descriptor is a terminal |
Design boundary
Caller intent
┌──────────────────────────────────────────────────────┐
│ Terminal::Style::new().foreground(...).apply(text) │
│ Terminal::Screen::clear() │
│ Terminal::Cursor::moveTo(row, column) │
└──────────────────────────┬───────────────────────────┘
│ semantic API
▼
Private implementation
┌──────────────────────────────────────────────────────┐
│ ansiSgr(code) │
│ ansiCsi(command) │
└──────────────────────────────────────────────────────┘
This split is deliberate:
- Public code stays easy to read and review.
- Escape-sequence details stay centralized.
- Tests can assert high-level behavior without calling low-level helpers.
Behavior notes
- Styled helpers append a trailing reset automatically.
- Cursor coordinates are one-based, matching common ANSI terminal usage.
- Capability checks currently rely on
isattythroughstd::libcand are therefore limited to the supported POSIX-style hosts enabled by the@configFlagannotations. - This module does not implement raw mode, alternate screen buffers, event input, or terminal layout/widgets.
Example
import Terminal from "std::terminal";
function main(): i32 {
if (Terminal::isOutputTerminal()) {
let mut style: Terminal::Style = Terminal::Style::new();
style.foreground(Terminal::TerminalColor::GREEN);
style.attribute(Terminal::TerminalAttribute::BOLD);
}
let heading: String = Terminal::colorText("ready", Terminal::TerminalColor::GREEN);
let clear: String = Terminal::Screen::clear();
let moveHome: String = Terminal::Cursor::moveTo(1, 1);
return 0;
}
namespace CursorCursor control helpers.
All cursor coordinates in this namespace are one-based.
Row 1, column 1 is the top-left corner.
namespace ScreenScreen control helpers.
Use these methods when a caller needs a complete command string for common clearing operations without depending on raw ANSI fragments.
namespace TerminalTerminal utilities for semantic terminal formatting and control.
What this namespace provides
- Nested color and attribute enums
- Composable text styles
- Screen and cursor helpers
- File-descriptor terminal capability checks
What it does not provide
- Raw mode
- Alternate screen buffers
- Keyboard or mouse event handling
- High-level TUI widgets or layout primitives
Records
record StyleComposable text styling state.
Style collects semantic foreground, background, and attribute choices
and converts them into a single rendered string when apply() is called.
Rendering model
foreground? -> background? -> attributes* -> text -> reset
Key behavior
- Missing foreground/background means “leave terminal default unchanged” until the final reset.
- Attributes are emitted in insertion order.
apply()always appendsTerminal::reset().
foregroundColor: Option<TerminalColor>Optional foreground color to emit before text.
backgroundColor: Option<TerminalColor>Optional background color to emit before text.
attributes: Vector<TerminalAttribute>Ordered text attributes to emit before text.
static new(): StyleCreates an empty style with no colors or attributes.
Returns
A style that leaves all formatting unset until additional builder-style methods are called.
Example
let style: Terminal::Style = Terminal::Style::new();
apply(&self, text: str): StringApplies the style to text and appends a trailing reset.
Arguments
text: text payload to wrap.
Returns
An owned String containing all configured prefix sequences, then the
original text, then Terminal::reset().
Invariants
- Always returns a trailing reset.
- Never mutates the input text.
- Attribute order matches insertion order.
Example
let mut style: Terminal::Style = Terminal::Style::new();
style.foreground(Terminal::TerminalColor::RED);
let styled: String = style.apply("alert");
attribute(&mut self, attribute: TerminalAttribute): voidAppends one text attribute to the style.
Arguments
attribute: attribute to emit before the text.
Notes
Repeated calls preserve insertion order. The module does not currently deduplicate attributes or validate conflicting combinations.
Example
let mut style: Terminal::Style = Terminal::Style::new();
style.attribute(Terminal::TerminalAttribute::BOLD);
style.attribute(Terminal::TerminalAttribute::UNDERLINE);
background(&mut self, color: TerminalColor): voidSets the style background color.
Arguments
color: semantic background color to use for laterapply()calls.
Example
let mut style: Terminal::Style = Terminal::Style::new();
style.background(Terminal::TerminalColor::BLUE);
foreground(&mut self, color: TerminalColor): voidSets the style foreground color.
Arguments
color: semantic color to use for laterapply()calls.
Example
let mut style: Terminal::Style = Terminal::Style::new();
style.foreground(Terminal::TerminalColor::GREEN);
Enums
enum TerminalAttributeText attributes represented by ANSI SGR codes.
Combine one or more of these through Terminal::Style::attribute().
BOLDDIMITALICUNDERLINEREVERSEDcode(&self): i32Returns the ANSI SGR code for this attribute.
Example
let code: i32 = Terminal::TerminalAttribute::UNDERLINE.code();
// code == 4
enum TerminalColorANSI 8-color palette used by semantic styling helpers.
These values describe intent rather than literal bytes. Convert them
to concrete escape codes through foregroundCode() or backgroundCode().
Most callers should use them through Terminal::Style, colorText, or
styledText instead of calling the code helpers themselves.
BLACKREDGREENYELLOWBLUEMAGENTACYANWHITEDEFAULTbackgroundCode(&self): i32Returns the ANSI background SGR code for this color.
Returns
One of the standard background codes in the 40–49 range.
Example
let code: i32 = Terminal::TerminalColor::BLUE.backgroundCode();
// code == 44
foregroundCode(&self): i32Returns the ANSI foreground SGR code for this color.
Returns
One of the standard foreground codes in the 30–39 range.
Example
let code: i32 = Terminal::TerminalColor::RED.foregroundCode();
// code == 31
Functions
function appendStyled(output: &mut String, text: str, useAnsi: boolean, color: TerminalColor, bold: boolean): voidAppends optionally styled text to output.
function colorText(text: str, color: TerminalColor): StringWraps text in one foreground color and a trailing reset.
Arguments
text: text payload to wrap.color: semantic foreground color.
Returns
Styled text equivalent to constructing a new Style, setting its
foreground color, and calling apply(text).
Example
let ok: String = Terminal::colorText("ok", Terminal::TerminalColor::GREEN);
function isAsciiWhitespace(value: char): booleanfunction isErrorTerminal(): booleanReturns true when stderr is attached to a terminal.
This is useful for tooling that styles diagnostics separately from normal stdout output.
Example
let canStyleErrors: boolean = Terminal::isErrorTerminal();
function isInputTerminal(): booleanReturns true when stdin is attached to a terminal.
Returns
Host isatty(STDIN_FILENO) != 0 on supported platforms.
Limitations
This check is only available on the hosts enabled by the surrounding
@configFlag annotation.
Example
let interactive: boolean = Terminal::isInputTerminal();
function isOutputTerminal(): booleanReturns true when stdout is attached to a terminal.
Use this before emitting styling when redirected output should remain plain.
Example
if (Terminal::isOutputTerminal()) {
let text: String = Terminal::colorText("ready", Terminal::TerminalColor::GREEN);
}
function reset(): StringResets color and style attributes.
Returns
The complete ANSI reset sequence ESC[0m.
Notes
Style::apply, colorText, and styledText all append this sequence
automatically, so callers rarely need to concatenate it manually.
Example
let reset: String = Terminal::reset();
function stripAnsiAndWhitespace(text: str): StringStrips ANSI escape sequences and ASCII whitespace from rendered text.
This is intended for tests and compatibility comparisons where diagnostic styling and layout whitespace should not affect semantic equality.
function styledIf(text: str, useAnsi: boolean, color: TerminalColor, bold: boolean): StringApplies optional ANSI styling to text.
When useAnsi is false, this returns text unchanged as an owned string.
When useAnsi is true, it applies the requested foreground color and
optional bold attribute with a trailing reset.
function styledText(text: str, attribute: TerminalAttribute): StringWraps text in one text attribute and a trailing reset.
Arguments
text: text payload to wrap.attribute: semantic attribute to apply.
Example
let heading: String = Terminal::styledText("Title", Terminal::TerminalAttribute::BOLD);
Functions
function ansiCsi(command: str): StringBuilds a Control Sequence Introducer (CSI) escape sequence.
Purpose
This is a private implementation helper used by the public semantic API.
Callers should prefer Terminal::Style, Terminal::Screen, and
Terminal::Cursor instead of assembling CSI commands directly.
Arguments
command: trailing CSI payload such as"2J","12;34H", or"0m".
Returns
An owned String beginning with ESC [ followed by command.
Invariants
- Always returns a complete CSI prefix.
- Does not append any trailing reset or newline on its own.
Example
let sequence: String = ansiCsi("2J");
// sequence is ESC[2J
function ansiSgr(code: i32): StringBuilds one Select Graphic Rendition (SGR) command.
Purpose
Converts one numeric SGR code into a full CSI escape string. This helper is private so the public API can remain semantic.
Arguments
code: ANSI SGR code such as0,31, or1.
Returns
A complete ANSI sequence like ESC[31m.
Example
let red: String = ansiSgr(31);
// red is ESC[31m
function clear(): StringReturns the full-screen clear command.
Returns
A complete CSI sequence equivalent to ANSI ESC[2J.
Example
let clear: String = Terminal::Screen::clear();
function clearLine(): StringReturns the current-line clear command.
Returns
A complete CSI sequence equivalent to ANSI ESC[2K.
Example
let clearLine: String = Terminal::Screen::clearLine();
function hide(): StringHides the cursor.
Example
let hide: String = Terminal::Cursor::hide();
function moveTo(row: u32, column: u32): StringMoves the cursor to one-based row and column coordinates.
Arguments
row: one-based terminal row.column: one-based terminal column.
Returns
A complete CSI sequence such as ESC[12;34H.
Invariants
The function preserves the provided numeric values exactly; it does not clamp zero or out-of-range coordinates.
Example
let moveCursor: String = Terminal::Cursor::moveTo(3, 10);
function restore(): StringRestores the most recently saved cursor position.
Example
let restore: String = Terminal::Cursor::restore();
function save(): StringSaves the current cursor position.
Example
let save: String = Terminal::Cursor::save();
function show(): StringShows the cursor.
Example
let show: String = Terminal::Cursor::show();