//! ANSI escape sequence builders.
//!
//! Mirrors the `github.com/charmbracelet/x/ansi` (v0.11.8) builders used by
//! ultraviolet byte-for-byte where cost comparisons matter: parameters of 1
//! (or 0/negative) are omitted exactly as Go's `strconv.Itoa` gating does, and
//! `CursorPosition(1,1)` collapses to `\x1b[H`.
//!
//! All builders write into a `std.Io.Writer` and return the number of bytes
//! written. To compare sequence costs, render callers build each candidate
//! into a fixed stack buffer and compare lengths — same semantics as Go's
//! `len(seq)`.
const std = @import("std");
const Writer = std.Io.Writer;
const t = std.testing;
/// Backspace
pub const BS: u8 = 0x08;
/// Horizontal Tab
pub const HT: u8 = 0x09;
/// Line Feed
pub const LF: u8 = 0x0A;
/// Carriage Return
pub const CR: u8 = 0x0D;
/// Unit Separator
pub const US: u8 = 0x1F;
/// Delete
pub const DEL: u8 = 0x7F;
/// NUL (^@).
pub const NUL: u8 = 0x00;
/// SOH (^A).
pub const SOH: u8 = 0x01;
/// STX (^B).
pub const STX: u8 = 0x02;
/// ETX (^C).
pub const ETX: u8 = 0x03;
/// EOT (^D).
pub const EOT: u8 = 0x04;
/// ENQ (^E).
pub const ENQ: u8 = 0x05;
/// ACK (^F).
pub const ACK: u8 = 0x06;
/// BEL (^G).
pub const BEL: u8 = 0x07;
/// VT (^K).
pub const VT: u8 = 0x0B;
/// FF (^L).
pub const FF: u8 = 0x0C;
/// SO (^N).
pub const SO: u8 = 0x0E;
/// SI (^O).
pub const SI: u8 = 0x0F;
/// DLE (^P).
pub const DLE: u8 = 0x10;
/// DC1 (^Q).
pub const DC1: u8 = 0x11;
/// DC2 (^R).
pub const DC2: u8 = 0x12;
/// DC3 (^S).
pub const DC3: u8 = 0x13;
/// DC4 (^T).
pub const DC4: u8 = 0x14;
/// NAK (^U).
pub const NAK: u8 = 0x15;
/// SYN (^V).
pub const SYN: u8 = 0x16;
/// ETB (^W).
pub const ETB: u8 = 0x17;
/// CAN (^X).
pub const CAN: u8 = 0x18;
/// EM (^Y).
pub const EM: u8 = 0x19;
/// SUB (^Z).
pub const SUB: u8 = 0x1A;
/// ESC (^[).
pub const ESC: u8 = 0x1B;
/// FS (^\).
pub const FS: u8 = 0x1C;
/// GS (^]).
pub const GS: u8 = 0x1D;
/// RS (^^).
pub const RS: u8 = 0x1E;
/// SP (space).
pub const SP: u8 = 0x20;
/// PAD.
pub const PAD: u8 = 0x80;
/// SOS.
pub const SOS: u8 = 0x98;
/// SS3.
pub const SS3: u8 = 0x8F;
/// DCS.
pub const DCS: u8 = 0x90;
/// CSI.
pub const CSI: u8 = 0x9B;
/// ST.
pub const ST: u8 = 0x9C;
/// OSC.
pub const OSC: u8 = 0x9D;
/// PM.
pub const PM: u8 = 0x9E;
/// APC.
pub const APC: u8 = 0x9F;
/// Returns the number of bytes `writeNumber` would emit for `n`.
pub fn decimalLength(n: usize) usize {
if (n < 10) return 1;
if (n < 100) return 2;
if (n < 1000) return 3;
if (n < 10000) return 4;
if (n < 100000) return 5;
if (n < 10000000) return 7;
return 9;
}
/// Writes the decimal ASCII representation of `n`.
pub fn writeNumber(writer: *Writer, n: usize) Writer.Error!usize {
if (n < 10) {
try writer.writeByte(@intCast('0' + n));
return 1;
}
var buf: [20]u8 = undefined;
const s = std.fmt.bufPrint(&buf, "{d}", .{n}) catch unreachable;
try writer.writeAll(s);
return s.len;
}
/// Writes a CSI sequence `ESC [ ` with the given parametrized
/// count. The parameter is omitted entirely when `n <= 1`, matching the Go
/// builders. Returns bytes written.
fn writeCsiParam(writer: *Writer, n: usize, final: u8) Writer.Error!usize {
var count: usize = 0;
try writer.writeByte(0x1b);
try writer.writeByte('[');
count += 2;
if (n > 1) {
const c = try writeNumber(writer, n);
count += c;
}
try writer.writeByte(final);
return count + 1;
}
/// Writes a CSI sequence `ESC [ ` where the parameter is
/// omitted when `n <= 0` (used by column/row absolute positioning). Returns
/// bytes written.
fn writeCsiPos(writer: *Writer, n: usize, final: u8) Writer.Error!usize {
var count: usize = 0;
try writer.writeByte(0x1b);
try writer.writeByte('[');
count += 2;
if (n > 0) {
const c = try writeNumber(writer, n);
count += c;
}
try writer.writeByte(final);
return count + 1;
}
/// CSI n A — move cursor up `n` cells. Parameter omitted for n <= 1.
pub fn cursorUp(writer: *Writer, n: usize) Writer.Error!usize {
return writeCsiParam(writer, n, 'A');
}
pub const cuu = cursorUp;
/// CSI n B — move cursor down `n` cells.
pub fn cursorDown(writer: *Writer, n: usize) Writer.Error!usize {
return writeCsiParam(writer, n, 'B');
}
pub const cud = cursorDown;
/// CSI n C — move cursor forward (right) `n` cells.
pub fn cursorForward(writer: *Writer, n: usize) Writer.Error!usize {
return writeCsiParam(writer, n, 'C');
}
pub const cuf = cursorForward;
/// CSI n D — move cursor backward (left) `n` cells.
pub fn cursorBackward(writer: *Writer, n: usize) Writer.Error!usize {
return writeCsiParam(writer, n, 'D');
}
pub const cub = cursorBackward;
/// CSI n G — move cursor to the given column (horizontal absolute).
/// Parameter omitted for col <= 0 (defaults to 1).
pub fn cursorHorizontalAbsolute(writer: *Writer, col: usize) Writer.Error!usize {
return writeCsiPos(writer, col, 'G');
}
pub const cha = cursorHorizontalAbsolute;
/// CSI n G — alias for horizontal position absolute.
pub fn horizontalPositionAbsolute(writer: *Writer, col: usize) Writer.Error!usize {
return writeCsiPos(writer, col, 'G');
}
pub const hpa = horizontalPositionAbsolute;
pub const HorizontalPositionAbsolute = horizontalPositionAbsolute;
/// CSI n d — move cursor to the given row (vertical absolute).
pub fn verticalPositionAbsolute(writer: *Writer, row: usize) Writer.Error!usize {
return writeCsiPos(writer, row, 'd');
}
pub const vpa = verticalPositionAbsolute;
/// CSI r ; c H — set cursor position. (1,1) collapses to `\x1b[H`.
pub fn cursorPosition(writer: *Writer, col: usize, row: usize) Writer.Error!usize {
if (row <= 1 and col <= 1) {
try writer.writeAll("\x1b[H");
return 3;
}
var count: usize = 2;
try writer.writeByte(0x1b);
try writer.writeByte('[');
if (row > 0) {
const c = try writeNumber(writer, row);
count += c;
}
try writer.writeByte(';');
if (col > 0) {
const c = try writeNumber(writer, col);
count += c;
}
try writer.writeByte('H');
return count + 2;
}
pub const cup = cursorPosition;
/// ESC [ H — move cursor to upper-left corner of the scrolling region.
pub const cursorHomePosition = "\x1b[H";
/// CSI n I — move cursor to the next tab stop `n` times.
pub fn cursorHorizontalForwardTab(writer: *Writer, n: usize) Writer.Error!usize {
return writeCsiParam(writer, n, 'I');
}
pub const cht = cursorHorizontalForwardTab;
/// CSI n Z — move cursor to the previous tab stop `n` times.
pub fn cursorBackwardTab(writer: *Writer, n: usize) Writer.Error!usize {
return writeCsiParam(writer, n, 'Z');
}
pub const cbt = cursorBackwardTab;
/// ESC M — reverse index (cursor up; scroll down at top margin).
pub const reverseIndex = "\x1bM";
/// CSI n X — erase `n` characters (ECH).
pub fn eraseCharacter(writer: *Writer, n: usize) Writer.Error!usize {
return writeCsiParam(writer, n, 'X');
}
pub const ech = eraseCharacter;
/// CSI n P — delete `n` characters (DCH).
pub fn deleteCharacter(writer: *Writer, n: usize) Writer.Error!usize {
return writeCsiParam(writer, n, 'P');
}
pub const dch = deleteCharacter;
/// CSI n @ — insert `n` blank characters (ICH).
pub fn insertCharacter(writer: *Writer, n: usize) Writer.Error!usize {
return writeCsiParam(writer, n, '@');
}
pub const ich = insertCharacter;
/// CSI n K — erase line (EL).
pub fn eraseLine(writer: *Writer, n: usize) Writer.Error!usize {
return writeCsiPos(writer, n, 'K');
}
pub const el = eraseLine;
/// ESC [ K — clear from cursor to end of line.
pub const eraseLineRight = "\x1b[K";
/// ESC [ 1K — clear from cursor to beginning of line.
pub const eraseLineLeft = "\x1b[1K";
/// ESC [ 2K — clear entire line.
pub const eraseEntireLine = "\x1b[2K";
/// CSI n J — erase display (ED).
pub fn eraseDisplay(writer: *Writer, n: usize) Writer.Error!usize {
return writeCsiPos(writer, n, 'J');
}
pub const ed = eraseDisplay;
/// ESC [ J — clear from cursor to end of screen.
pub const eraseScreenBelow = "\x1b[J";
/// ESC [ 1J — clear from cursor to beginning of screen.
pub const eraseScreenAbove = "\x1b[1J";
/// ESC [ 2J — clear entire screen.
pub const eraseEntireScreen = "\x1b[2J";
/// ESC [ 3J — clear entire display (including scrollback).
pub const eraseEntireDisplay = "\x1b[3J";
/// CSI n L — insert `n` blank lines (IL).
pub fn insertLine(writer: *Writer, n: usize) Writer.Error!usize {
return writeCsiParam(writer, n, 'L');
}
pub const il = insertLine;
/// CSI n M — delete `n` lines (DL).
pub fn deleteLine(writer: *Writer, n: usize) Writer.Error!usize {
return writeCsiParam(writer, n, 'M');
}
pub const dl = deleteLine;
/// CSI n S — scroll screen up `n` lines (SU).
pub fn scrollUp(writer: *Writer, n: usize) Writer.Error!usize {
return writeCsiParam(writer, n, 'S');
}
pub const su = scrollUp;
/// CSI n T — scroll screen down `n` lines (SD).
pub fn scrollDown(writer: *Writer, n: usize) Writer.Error!usize {
return writeCsiParam(writer, n, 'T');
}
pub const sd = scrollDown;
/// CSI top ; bot r — set top and bottom scrolling margins (DECSTBM).
pub fn setTopBottomMargins(writer: *Writer, top: usize, bot: usize) Writer.Error!usize {
var count: usize = 2;
try writer.writeByte(0x1b);
try writer.writeByte('[');
if (top > 0) {
const c = try writeNumber(writer, top);
count += c;
}
try writer.writeByte(';');
if (bot > 0) {
const c = try writeNumber(writer, bot);
count += c;
}
try writer.writeByte('r');
return count + 2;
}
pub const decstbm = setTopBottomMargins;
/// CSI n b — repeat previous character `n` times (REP).
pub fn repeatPreviousCharacter(writer: *Writer, n: usize) Writer.Error!usize {
return writeCsiParam(writer, n, 'b');
}
pub const rep = repeatPreviousCharacter;
/// ESC [ ? 1049 h — enter alt screen, save cursor.
pub const setModeAltScreenSaveCursor = "\x1b[?1049h";
/// ESC [ ? 1049 l — exit alt screen, restore cursor.
pub const resetModeAltScreenSaveCursor = "\x1b[?1049l";
/// ESC [ ? 7 h — enable autowrap.
pub const setModeAutoWrap = "\x1b[?7h";
/// ESC [ ? 7 l — disable autowrap.
pub const resetModeAutoWrap = "\x1b[?7l";
/// ESC [ 4 h — enable insert/replace mode.
pub const setModeInsertReplace = "\x1b[4h";
/// ESC [ 4 l — disable insert/replace mode.
pub const resetModeInsertReplace = "\x1b[4l";
/// ESC [ ? 5 W — set tab stops every 8 columns.
pub const setTabEvery8Columns = "\x1b[?5W";
/// ESC [ m — reset all styles.
pub const resetStyle = "\x1b[m";
/// OSC 8 ; ; BEL — start a hyperlink.
pub fn setHyperlink(writer: *Writer, uri: []const u8, params: []const u8) Writer.Error!usize {
try writer.writeAll("\x1b]8;");
try writer.writeAll(params);
try writer.writeByte(';');
try writer.writeAll(uri);
try writer.writeByte(0x07);
return 4 + params.len + 1 + uri.len + 1;
}
/// OSC 8 ; ; BEL — reset a hyperlink.
pub fn resetHyperlink(writer: *Writer, params: []const u8) Writer.Error!usize {
return setHyperlink(writer, "", params);
}
// --- window title / terminal colors / cursor style -------------------------
/// OSC 2 ; BEL — set the window title. Mirrors
/// `ansi.SetWindowTitle` (`\x1b]2;{title}\x07`).
pub fn setWindowTitle(writer: *Writer, title: []const u8) Writer.Error!usize {
try writer.writeAll("\x1b]2;");
try writer.writeAll(title);
try writer.writeByte(0x07);
return 4 + title.len + 1;
}
/// OSC 10 ; BEL — set the terminal default foreground color. Mirrors
/// `ansi.SetForegroundColor(hex)`.
pub fn setForegroundColor(writer: *Writer, hex: []const u8) Writer.Error!usize {
try writer.writeAll("\x1b]10;");
try writer.writeAll(hex);
try writer.writeByte(0x07);
return 5 + hex.len + 1;
}
/// OSC 110 BEL — reset the terminal default foreground color.
pub const resetForegroundColor = "\x1b]110\x07";
/// OSC 11 ; BEL — set the terminal default background color.
pub fn setBackgroundColor(writer: *Writer, hex: []const u8) Writer.Error!usize {
try writer.writeAll("\x1b]11;");
try writer.writeAll(hex);
try writer.writeByte(0x07);
return 5 + hex.len + 1;
}
/// OSC 111 BEL — reset the terminal default background color.
pub const resetBackgroundColor = "\x1b]111\x07";
/// OSC 12 ; BEL — set the terminal cursor color.
pub fn setCursorColor(writer: *Writer, hex: []const u8) Writer.Error!usize {
try writer.writeAll("\x1b]12;");
try writer.writeAll(hex);
try writer.writeByte(0x07);
return 5 + hex.len + 1;
}
/// OSC 112 BEL — reset the terminal cursor color.
pub const resetCursorColor = "\x1b]112\x07";
/// CSI