//! Styled strings: decompose a string with ANSI escape codes into styled //! cells and lines. //! //! Port of ultraviolet's `styled.go` plus the `x/ansi` sequence decoder it //! depends on (`parser_decode.go`, `parser.go`, `style.go`). A `StyledString` //! can either produce a list of `Line`s (`lines`, unwrapped) or draw itself //! into a screen buffer at a given area (`draw`, with wrapping/truncation). //! //! `printString` implements uv's draw + build-lines loop. Notable departures //! from upstream, all recorded in `Brain.md`: //! //! - The `y >= bounds.Max.Y` early-exit added to uv `1acffa0` is applied only //! in the draw path. uv also breaks for the nil-screen `Lines` path (where //! bounds is the zero `Rectangle{}`), which would drop everything after the //! first token; we keep `lines` unbounded as the function comment intends. //! - Memory: cell `content` slices are borrowed from the input text; slices //! derived from escape sequences (folded combining marks, hyperlink url / //! params) are owned `Allocator` allocations stored in the cell/buffer and //! never freed by the buffer (matches Go's GC with substrings staying live). const std = @import("std"); const ir = @import("root.zig"); const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; const t = std.testing; const Line = ir.Line; const Link = ir.Link; const Method = ir.width.Method; const Rectangle = ir.Rectangle; const Color = ir.Color; const Buffer = ir.Buffer; const Cell = ir.Cell; const Lines = ir.Lines; const Screen = ir.Screen; const Style = ir.Style; // C0/C1 introducers the decoder recognizes. const ESC: u8 = 0x1b; const CSI: u8 = 0x9b; const DCS: u8 = 0x90; const OSC: u8 = 0x9d; const APC: u8 = 0x9f; const SOS: u8 = 0x98; const PM: u8 = 0x9e; const BEL: u8 = 0x07; const ST: u8 = 0x9c; const CAN: u8 = 0x18; const SUB: u8 = 0x1a; const LF: u8 = 0x0a; const CR: u8 = 0x0d; // Mirrors `x/ansi.DecodeSequence`/`DecodeSequenceWc` state machine, used by // printString to split a string into printable grapheme clusters (with cell // width) and escape sequences (with collected parameters/data/command). /// Decoder states (an enum rather than Go's byte constants). const State = enum { normal, prefix, params, intermed, escape, string, }; /// Packed parameter: low 31 bits hold the value (or `MissingParam`), the top /// bit is the `HasMoreFlag` (a ':' sub-parameter separator follows). /// Mirrors `parser.Param` in x/ansi. /// NOTE: This should be a packed struct const HasMoreFlag: u32 = 0x8000_0000; const ParamMask: u32 = 0x7fff_ffff; const MissingParam: u32 = 0x7fff_ffff; const MissingCommand: u32 = 0x7fff_ffff; const MaxParams: usize = 32; const MaxData: usize = 64 * 1024; /// Result of one `decode` call. pub const Decoded = struct { n: usize, width: usize, state: State, }; /// Stateless-ish sequence scanner. The decoder mutates `params`/`data`/`cmd` /// across calls and the caller threads `state`, exactly like Go's `Parser`. pub const Decoder = struct { param_buf: [MaxParams]u32 = @splat(0), params_len: usize = 0, data_buf: [MaxData]u8 = undefined, data_len: usize = 0, cmd: u32 = 0, pub fn init() Decoder { return .{}; } fn clearSeq(d: *Decoder) void { d.param_buf[0] = MissingParam; d.params_len = 0; d.cmd = 0; d.data_len = 0; } /// Increment the number of params to account for the last one (unless the /// final param was never collected). Called upon leaving the param state. fn incLastParam(d: *Decoder) void { if ((d.params_len > 0 and d.params_len < MaxParams - 1) or (d.params_len == 0 and d.param_buf[0] != MissingParam)) { d.params_len += 1; } } /// Decodes the next sequence from `b`, returning the number of bytes it /// consumes, its cell width (0 for control/escape sequences), and the /// next decoder state. `seq` is `b[0..n]`. pub fn decode(d: *Decoder, b: []const u8, state: State, m: Method) Decoded { var i: usize = 0; var st = state; while (i < b.len) : (i += 1) { const c = b[i]; switch (st) { .normal => { if (c == ESC) { d.clearSeq(); st = .escape; continue; } if (c == CSI or c == DCS) { d.clearSeq(); st = .prefix; continue; } if (c == OSC or c == APC or c == SOS or c == PM) { d.cmd = MissingCommand; d.data_len = 0; st = .string; continue; } d.data_len = 0; d.params_len = 0; d.cmd = 0; if (c > 0x1f and c < 0x7f) { // ASCII printable return .{ .n = 1, .width = 1, .state = .normal }; } if (c <= 0x1f or c == 0x7f or c < 0xc0) { // C0 & C1 controls, DEL, invalid UTF-8 tail bytes return .{ .n = 1, .width = 0, .state = .normal }; } // UTF-8 lead byte: whole grapheme cluster, cell width. const cluster = firstGraphemeCluster(b[i..]); const w = ir.width.stringWidth(m, cluster); return .{ .n = cluster.len, .width = w, .state = .normal }; }, .prefix => { if (c >= '<' and c <= '?') { d.cmd &= ~(@as(u32, 0xff) << 8); d.cmd |= @as(u32, c) << 8; continue; } // Not a prefix leg: process this byte in the param state. st = .params; if (c >= '0' and c <= '9') { if (d.params_len < MaxParams) { if (d.param_buf[d.params_len] == MissingParam) d.param_buf[d.params_len] = 0; d.param_buf[d.params_len] = d.param_buf[d.params_len] * 10 + (c - '0'); } continue; } if (c == ':') { if (d.params_len < MaxParams) d.param_buf[d.params_len] |= HasMoreFlag; } if (c == ';' or c == ':') { d.params_len += 1; if (d.params_len < MaxParams) d.param_buf[d.params_len] = MissingParam; continue; } // Not a param leg: process this byte in the intermediate state. st = .intermed; if (c >= ' ' and c <= '/') { d.cmd &= ~(@as(u32, 0xff) << 16); d.cmd |= @as(u32, c) << 16; continue; } d.incLastParam(); if (c >= '@' and c <= '~') { d.cmd = (d.cmd & ~@as(u32, 0xff)) | c; if (hasDcsPrefix(b)) { // Continue to collect DCS data. d.data_len = 0; st = .string; continue; } return .{ .n = i + 1, .width = 0, .state = .normal }; } // Invalid CSI/DCS sequence. return .{ .n = i, .width = 0, .state = .normal }; }, .params => { if (c >= '0' and c <= '9') { if (d.params_len < MaxParams) { if (d.param_buf[d.params_len] == MissingParam) d.param_buf[d.params_len] = 0; d.param_buf[d.params_len] = d.param_buf[d.params_len] * 10 + (c - '0'); } continue; } if (c == ':') { if (d.params_len < MaxParams) d.param_buf[d.params_len] |= HasMoreFlag; } if (c == ';' or c == ':') { d.params_len += 1; if (d.params_len < MaxParams) d.param_buf[d.params_len] = MissingParam; continue; } // Not a param leg: process this byte in the intermediate state. st = .intermed; if (c >= ' ' and c <= '/') { d.cmd &= ~(@as(u32, 0xff) << 16); d.cmd |= @as(u32, c) << 16; continue; } d.incLastParam(); if (c >= '@' and c <= '~') { d.cmd = (d.cmd & ~@as(u32, 0xff)) | c; if (hasDcsPrefix(b)) { // Continue to collect DCS data. d.data_len = 0; st = .string; continue; } return .{ .n = i + 1, .width = 0, .state = .normal }; } // Invalid CSI/DCS sequence. return .{ .n = i, .width = 0, .state = .normal }; }, .intermed => { if (c >= ' ' and c <= '/') { d.cmd &= ~(@as(u32, 0xff) << 16); d.cmd |= @as(u32, c) << 16; continue; } d.incLastParam(); if (c >= '@' and c <= '~') { d.cmd = (d.cmd & ~@as(u32, 0xff)) | c; if (hasDcsPrefix(b)) { // Continue to collect DCS data. d.data_len = 0; st = .string; continue; } return .{ .n = i + 1, .width = 0, .state = .normal }; } // Invalid CSI/DCS sequence. return .{ .n = i, .width = 0, .state = .normal }; }, .escape => { if (c == '[' or c == 'P') { d.param_buf[0] = MissingParam; d.params_len = 0; d.cmd = 0; st = .prefix; continue; } if (c == ']' or c == 'X' or c == '^' or c == '_') { d.cmd = MissingCommand; d.data_len = 0; st = .string; continue; } if (c >= ' ' and c <= '/') { d.cmd &= ~(@as(u32, 0xff) << 16); d.cmd |= @as(u32, c) << 16; continue; } if (c >= '0' and c <= '~') { d.cmd = (d.cmd & ~@as(u32, 0xff)) | c; return .{ .n = i + 1, .width = 0, .state = .normal }; } // Invalid escape sequence. return .{ .n = i, .width = 0, .state = .normal }; }, .string => { if (c == BEL) { if (hasOscPrefix(b)) { parseOscCmd(d); return .{ .n = i + 1, .width = 0, .state = .normal }; } } else if (c == CAN or c == SUB) { if (hasOscPrefix(b)) parseOscCmd(d); // Cancel the sequence. return .{ .n = i, .width = 0, .state = .normal }; } else if (c == ST) { if (hasOscPrefix(b)) parseOscCmd(d); return .{ .n = i + 1, .width = 0, .state = .normal }; } else if (c == ESC) { if (hasStPrefix(b[i..])) { if (hasOscPrefix(b)) parseOscCmd(d); // End of string, 7-bit ST. return .{ .n = i + 2, .width = 0, .state = .normal }; } return .{ .n = i, .width = 0, .state = .normal }; } if (d.data_len < MaxData) { d.data_buf[d.data_len] = c; d.data_len += 1; if (c == ';' and hasOscPrefix(b)) parseOscCmd(d); } }, } } return .{ .n = b.len, .width = 0, .state = st }; } /// The collected parameters as a slice. pub fn params(d: Decoder) []const u32 { const n = @min(d.params_len, MaxParams); return d.param_buf[0..n]; } /// The collected OSC/DCS data. pub fn data(d: Decoder) []const u8 { return d.data_buf[0..d.data_len]; } }; fn parseOscCmd(d: *Decoder) void { if (d.cmd != MissingCommand) return; var j: usize = 0; while (j < d.data_len) : (j += 1) { const ch = d.data_buf[j]; if (ch < '0' or ch > '9') break; if (d.cmd == MissingCommand) d.cmd = 0; d.cmd = d.cmd * 10 + (ch - '0'); } } /// Parser/Params.Param(i, def): bounds-checked variant, returns `ok=false` /// when the index is out of range. pub fn paramAt(params: []const u32, i: usize, def: u32) struct { value: u32, ok: bool } { if (i >= params.len) return .{ .value = def, .ok = false }; return .{ .value = paramValue(params[i], def), .ok = true }; } fn hasOscPrefix(b: []const u8) bool { return (b.len > 0 and b[0] == OSC) or (b.len > 1 and b[0] == ESC and b[1] == ']'); } fn hasCsiPrefix(b: []const u8) bool { return (b.len > 0 and b[0] == CSI) or (b.len > 1 and b[0] == ESC and b[1] == '['); } fn hasDcsPrefix(b: []const u8) bool { return (b.len > 0 and b[0] == DCS) or (b.len > 1 and b[0] == ESC and b[1] == 'P'); } fn hasStPrefix(b: []const u8) bool { return (b.len > 0 and b[0] == ST) or (b.len > 1 and b[0] == ESC and b[1] == '\\'); } /// Returns the first grapheme cluster of `s` starting at a UTF-8 lead byte. /// Best effort on top of wcwidth: the first code point plus any immediately /// following zero-width code points (combining marks, variation selectors, /// ZWJ, enclosing keycaps) — see `Brain.md` decision #5. /// /// Tolerant of invalid UTF-8: a malformed or truncated sequence is consumed /// one byte at a time so callers always make progress. pub fn firstGraphemeCluster(s: []const u8) []const u8 { if (s.len == 0) return s; var i: usize = 0; var taken: usize = 1; while (i < s.len) { const cp_len = std.unicode.utf8ByteSequenceLength(s[i]) catch { return s[0..taken]; }; if (i + cp_len > s.len) return s[0..taken]; const cp = std.unicode.utf8Decode(s[i .. i + cp_len]) catch { return s[0..taken]; }; if (i == 0) { taken = cp_len; } else { // Only zero-width graphic marks (combining marks, ZWJ, variation // selectors, ...) fold onto the cluster. Control bytes like ESC // stop the cluster even though wcwidth reports them width 0. const is_ctrl = cp < 0x20 or cp == 0x7f; if (codepointWidth(cp) == 0 and !is_ctrl) { taken += cp_len; } else { break; } } i += cp_len; } return s[0..taken]; } const codepointWidth = ir.width.codepointWidth; /// `p.Param(def)`: unpacks the value, substituting `def` for a missing param. pub fn paramValue(p: u32, def: u32) u32 { const v = p & ParamMask; if (v == MissingParam) return def; return v; } pub fn hasMore(p: u32) bool { return p & HasMoreFlag != 0; } fn colorParams(params: []const u32, n: *usize) struct { p1: i32, p2: i32, p3: i32, p4: i32 } { const s = params[0]; const p = params[1]; const s_h = hasMore(s); const p_h = hasMore(p); if (s_h and p_h and params.len > 8 and hasMore(params[2]) and hasMore(params[3]) and hasMore(params[4]) and hasMore(params[5]) and hasMore(params[6]) and hasMore(params[7])) { n.* += 7; return .{ .p1 = @intCast(paramValue(params[3], 0)), .p2 = @intCast(paramValue(params[4], 0)), .p3 = @intCast(paramValue(params[5], 0)), .p4 = @intCast(paramValue(params[6], 0)) }; } if (s_h and p_h and params.len > 7 and hasMore(params[2]) and hasMore(params[3]) and hasMore(params[4]) and hasMore(params[5]) and hasMore(params[6])) { n.* += 6; return .{ .p1 = @intCast(paramValue(params[3], 0)), .p2 = @intCast(paramValue(params[4], 0)), .p3 = @intCast(paramValue(params[5], 0)), .p4 = @intCast(paramValue(params[6], 0)) }; } if (s_h and p_h and params.len > 6 and hasMore(params[2]) and hasMore(params[3]) and hasMore(params[4]) and hasMore(params[5])) { n.* += 5; return .{ .p1 = @intCast(paramValue(params[3], 0)), .p2 = @intCast(paramValue(params[4], 0)), .p3 = @intCast(paramValue(params[5], 0)), .p4 = @intCast(paramValue(params[6], 0)) }; } if (s_h and p_h and params.len > 5 and hasMore(params[2]) and hasMore(params[3]) and hasMore(params[4]) and !hasMore(params[5])) { n.* += 4; return .{ .p1 = @intCast(paramValue(params[3], 0)), .p2 = @intCast(paramValue(params[4], 0)), .p3 = @intCast(paramValue(params[5], 0)), .p4 = -1 }; } if (s_h and p_h and pv0(p) == 2 and hasMore(params[2]) and hasMore(params[3]) and !hasMore(params[4])) { n.* += 3; return .{ .p1 = @intCast(paramValue(params[2], 0)), .p2 = @intCast(paramValue(params[3], 0)), .p3 = @intCast(paramValue(params[4], 0)), .p4 = -1 }; } if (!s_h and !p_h and pv0(p) == 2 and !hasMore(params[2]) and !hasMore(params[3]) and !hasMore(params[4])) { n.* += 3; return .{ .p1 = @intCast(paramValue(params[2], 0)), .p2 = @intCast(paramValue(params[3], 0)), .p3 = @intCast(paramValue(params[4], 0)), .p4 = -1 }; } return .{ .p1 = -1, .p2 = -1, .p3 = -1, .p4 = -1 }; } fn pv0(p: u32) u32 { return paramValue(p, 0); } /// Mirrors `x/ansi.ReadStyleColor`. `params` must start at the SGR type /// parameter (38/48/58). Returns the number of parameters consumed, 0 when the /// color could not be read. Color space / CMY / CMYK / RGBA variants map to /// `.none` because `Color` has no such representation (see Brain.md). pub fn readStyleColor(params: []const u32, pen_color: *?Color) usize { if (params.len < 2) return 0; const color_type = paramValue(params[1], 0); var n: usize = 2; switch (color_type) { 0 => return 2, // implementation defined 1 => { // transparent pen_color.* = .none; return 2; }, 2 => { // RGB if (params.len < 5) return 0; const c = colorParams(params, &n); if (c.p1 == -1 or c.p2 == -1 or c.p3 == -1) return 0; pen_color.* = .{ .rgb = .{ .r = @intCast(c.p1), .g = @intCast(c.p2), .b = @intCast(c.p3), } }; return n; }, 3 => { // CMY if (params.len < 5) return 0; const c = colorParams(params, &n); if (c.p1 == -1 or c.p2 == -1 or c.p3 == -1) return 0; pen_color.* = .none; return n; }, 4 => { // CMYK if (params.len < 6) return 0; const c = colorParams(params, &n); if (c.p1 == -1 or c.p2 == -1 or c.p3 == -1 or c.p4 == -1) return 0; pen_color.* = .none; return n; }, 5 => { // indexed if (params.len < 3) return 0; const s_h = hasMore(params[0]); const p_h = hasMore(params[1]); const p2_h = hasMore(params[2]); if (!((s_h and p_h and !p2_h) or (!s_h and !p_h and !p2_h))) return 0; pen_color.* = .{ .ansi256 = @intCast(paramValue(params[2], 0)) }; return 3; }, 6 => { // RGBA if (params.len < 6) return 0; const c = colorParams(params, &n); if (c.p1 == -1 or c.p2 == -1 or c.p3 == -1 or c.p4 == -1) return 0; pen_color.* = .none; return n; }, else => return 0, } } /// Renders `text` starting at `(x0, y0)` within `bounds`. /// /// When `screen` is null it builds and returns a slice of `Line`s instead /// (unwrapped, ignoring bounds) — the uv nil-screen mode. The caller owns the /// returned lines and their cells. When `screen` is set, the lines result is /// empty and everything goes through `screen`; `truncate` (draw only) caps a /// line at the bounds width and repeats `tail`. fn printString( comptime S: type, screen: ?*S, allocator: Allocator, m: Method, x0: usize, y0: usize, bounds: Rectangle, text: []const u8, truncate: bool, tail: []const u8, ) Allocator.Error![]Line { var dec: Decoder = .init(); var tailc: ?Cell = null; if (truncate and tail.len > 0) tailc = newCell(m, tail); var cell: Cell = .empty; var style: Style = .{}; var link: Link = .{}; var state: State = .normal; // Last cell written, for folding in combining marks. var last_x: i64 = -1; var last_y: i64 = -1; var x = x0; var y = y0; var str = text; const in_lines = S == void; var build: ?ArrayList(ArrayList(Cell)) = null; if (in_lines) build = .empty; defer { if (build) |*b| b.deinit(allocator); } while (str.len > 0) { const dec_res = dec.decode(str, state, m); state = dec_res.state; var n = dec_res.n; var width = dec_res.width; var seq = str[0..n]; // The decoder's ASCII fast path doesn't check for trailing combining // sequences, so re-decode as a full cluster when one starts here. // The str[1] >= 0xc0 check skips the segmenter for plain ASCII. if (n == 1 and seq[0] > 0x1f and seq[0] < 0x7f and str.len > 1 and str[1] >= 0xc0) { const cluster = firstGraphemeCluster(str); if (cluster.len > 1) { seq = str[0..cluster.len]; width = ir.width.stringWidth(m, seq); n = cluster.len; } } if (width > 0) { cell.content = seq; cell.width = @intCast(@min(width, 255)); cell.style = style; cell.link = link; if (in_lines) { try ensureLine(&build.?, allocator, y); const list = build.?.items; try list[y].append(allocator, cell); last_x = @intCast(list[y].items.len - 1); last_y = @intCast(y); x += width; } else { const s = screen.?; if (!truncate and x + width > bounds.max_x and y + 1 < bounds.max_y) { // Wrap the string to the width of the screen. x = bounds.min_x; y += 1; } if (inBounds(x, y, bounds)) { if (tailc) |tc| { if (tc.width > 0 and x + width > bounds.max_x - tc.width) { // Truncate the string and append the tail if any. var tcell = tc; tcell.style = style; tcell.link = link; s.setCell(@intCast(x), @intCast(y), tcell); last_x = @intCast(x); last_y = @intCast(y); x += tc.width; } else { s.setCell(@intCast(x), @intCast(y), cell); last_x = @intCast(x); last_y = @intCast(y); x += width; } } else { s.setCell(@intCast(x), @intCast(y), cell); last_x = @intCast(x); last_y = @intCast(y); x += width; } } } // Reset cell for next iteration. cell = .empty; } else { // Control and escape sequences. if (hasCsiPrefix(seq) and dec.cmd & 0xff == 'm') { // SGR Select Graphic Rendition. style.read(dec.params()); } else if (hasOscPrefix(seq) and dec.cmd == 8) { // Hyperlinks. try link.read(allocator, dec.data()); } else if (seq.len == 1 and seq[0] == LF) { // Ensure the row that holds the pre-LF text exists, then start // a fresh (possibly empty) row after it. This keeps a trailing // newline as a final empty line. if (in_lines) { try ensureLine(&build.?, allocator, y); y += 1; try ensureLine(&build.?, allocator, y); } else { y += 1; } // Always treat a NL as CR-LF similar to Termios ONLCR. if (in_lines) { x = 0; } else { x = bounds.min_x; } } else if (seq.len == 1 and seq[0] == CR) { if (in_lines) { x = 0; } else { x = bounds.min_x; } } else if (seq.len > 0 and seq[0] >= 0xc0) { // A zero-width grapheme, i.e. a combining mark the re-decode // above couldn't fold because an escape sequence sits between // it and its base, as in "a\x1b[31m\u0301". Every escape // introducer is a C0 or C1 byte, so a UTF-8 lead byte here is // always text. The mark belongs to the cell we last wrote. if (in_lines) { const list = build.?.items; if (last_y >= 0 and last_y < list.len and last_x >= 0 and last_x < list[@intCast(last_y)].items.len) { const idx: usize = @intCast(last_y); const idx2: usize = @intCast(last_x); const new_content = try concatOwned(allocator, list[idx].items[idx2].content, seq); list[idx].items[idx2].content = new_content; } } else if (last_x >= 0 and last_y >= 0) { const s = screen.?; if (s.cellAt(@intCast(last_x), @intCast(last_y))) |prev| { var folded = prev.*; folded.content = try concatOwned(allocator, folded.content, seq); s.setCell(@intCast(last_x), @intCast(last_y), folded); } } } else { cell.content = try concatOwned(allocator, cell.content, seq); } } // Advance the state and data. str = str[n..]; // We've reached the bottom of the bounds: stop processing further // lines. Only enforced for the draw path (uv `1acffa0`); the line // builder is unbounded (see file header). if (!in_lines and y >= bounds.max_y) break; } // Make sure to set the last cell if it's not empty. if (!cell.equal(.empty) and !in_lines) { screen.?.setCell(@intCast(x), @intCast(y), cell); } if (build) |*b| { const list = b.items; var out = try allocator.alloc(Line, list.len); for (list, 0..) |*line, i| { out[i] = .{ .cells = try line.toOwnedSlice(allocator) }; } return out; } // Draw path: no lines produced. return &[_]Line{}; } fn ensureLine(build: *std.ArrayList(std.ArrayList(Cell)), allocator: Allocator, y: usize) Allocator.Error!void { while (build.items.len <= y) { try build.append(allocator, .empty); } } fn inBounds(x: usize, y: usize, bounds: Rectangle) bool { return x >= bounds.min_x and x < bounds.max_x and y >= bounds.min_y and y < bounds.max_y; } /// Concatenates `a` and `b` into a new owned allocation. Returns `b` alone /// when `a` is empty (usually zero-cost for the accumulating-cell path). fn concatOwned(allocator: Allocator, a: []const u8, b: []const u8) Allocator.Error![]const u8 { if (a.len == 0) return allocator.dupe(u8, b); if (b.len == 0) return a; const out = try allocator.alloc(u8, a.len + b.len); @memcpy(out[0..a.len], a); @memcpy(out[a.len..], b); return out; } fn newCell(m: Method, cluster: []const u8) Cell { if (cluster.len == 0) return .empty; if (cluster.len == 1 and cluster[0] == ' ') return .space; const w = ir.width.stringWidth(m, cluster); return .{ .content = cluster, .width = @intCast(@min(w, 255)) }; } /// A string that can be decomposed into styled lines and cells, mirroring /// uv `StyledString`. pub const String = struct { text: []const u8 = "", wrap: bool = false, tail: []const u8 = "", pub fn new(text: []const u8) String { return .{ .text = text, .wrap = true }; } /// The raw text. pub fn string(self: *const String) []const u8 { return self.text; } /// Decomposes the styled string into a slice of lines (unwrapped). The /// caller owns the lines and their cells. pub fn lines(self: *const String, allocator: Allocator, m: Method) ![]Line { return printString(void, null, allocator, m, 0, 0, .{}, self.text, false, ""); } /// Draws the styled string into `screen` at `area`, clearing the area /// first. Mirrors uv `Draw`. The screen must provide `setCell`, `cellAt`, /// `bounds`, and optionally `widthMethod` (fallback: wcwidth) and respect /// the resulting grapheme widths. pub fn draw(self: *const String, allocator: Allocator, screen: anytype, area: Rectangle) !void { const S = @TypeOf(screen.*); var y = area.min_y; while (y < area.max_y) : (y += 1) { var x = area.min_x; while (x < area.max_x) : (x += 1) { screen.setCell(x, y, null); } } // CR+LF are handled in the print loop: '\r' performs a carriage // return and '\n' a newline, so "\r\n" renders as a bare newline. const m: Method = if (@hasDecl(S, "widthMethod")) screen.widthMethod() else .wcwidth; _ = try printString( S, screen, allocator, m, area.min_x, area.min_y, area, self.text, !self.wrap, self.tail, ); } /// Number of lines the string occupies when rendered. pub fn height(self: *const String) usize { var count: usize = 0; for (self.text) |c| { if (c == '\n') count += 1; } return count + 1; } /// Cells width of the widest line using the grapheme method. pub fn unicodeWidth(self: *const String) usize { return self.widthHeight(.grapheme).width; } /// Cells width of the widest line using the wcwidth method. pub fn wcWidth(self: *const String) usize { return self.widthHeight(.wcwidth).width; } const Size = struct { width: usize, height: usize }; /// Width of the widest line and the line count. pub fn widthHeight(self: *const String, m: Method) Size { var h: usize = 0; var w: usize = 0; var it = std.mem.splitScalar(u8, self.text, '\n'); while (it.next()) |line| { h += 1; const lw = styledWidth(m, line); if (lw > w) w = lw; } return .{ .width = w, .height = h }; } /// The minimum area that can contain the whole styled string. pub fn bounds(self: *const String) Rectangle { const wh = self.widthHeight(.grapheme); return .new(0, 0, @intCast(wh.width), @intCast(wh.height)); } }; /// Display width of a possibly-styled line: the decoder walks the string and /// only printable clusters contribute width. Escape sequences are skipped, so /// this mirrors `ansi.Method.StringWidth` (a tab counts by its code point /// width here; see Brain.md). fn styledWidth(method: Method, text: []const u8) usize { var dec: Decoder = .init(); var state: State = .normal; var total: usize = 0; var str = text; while (str.len > 0) { const r = dec.decode(str, state, method); state = r.state; if (r.width > 0) { total += r.width; str = str[r.n..]; continue; } // A zero-width cluster that is not a fold (lone combining mark) still // counts zero here, matching per-code-point width sums. str = str[r.n..]; } return total; } test "decode ascii run" { var decoder: Decoder = .init(); const r = decoder.decode("abc", .normal, .wcwidth); try t.expectEqual(1, r.n); try t.expectEqual(1, r.width); try t.expectEqual(State.normal, r.state); } test "decode multiline string" { var decoder: Decoder = .init(); const r = decoder.decode("Hello, World!\n", .normal, .wcwidth); try t.expectEqual(1, r.n); } test "decode csi sgr params" { var decoder: Decoder = .init(); const r = decoder.decode("\x1b[31;1m X", .normal, .wcwidth); try t.expectEqual(7, r.n); try t.expectEqual(0, r.width); try t.expectEqual(State.normal, r.state); try t.expectEqual('m', decoder.cmd & 0xff); const ps = decoder.params(); try t.expectEqual(2, ps.len); try t.expectEqual(31, paramValue(ps[0], 0)); try t.expectEqual(1, paramValue(ps[1], 0)); // A printable after the SGR resets the collected params/data. const r2 = decoder.decode(" X", .normal, .wcwidth); try t.expectEqual(1, r2.n); try t.expectEqual(0, decoder.params().len); try t.expectEqual(0, decoder.data_len); } test "decode csi 256 color gives three params" { var decoder: Decoder = .init(); const r = decoder.decode("\x1b[38;5;196m", .normal, .wcwidth); try t.expectEqual(11, r.n); const ps = decoder.params(); try t.expectEqual(3, ps.len); try t.expectEqual(38, paramValue(ps[0], 0)); try t.expectEqual(5, paramValue(ps[1], 0)); try t.expectEqual(196, paramValue(ps[2], 0)); } test "decode colon subparameters" { var decoder: Decoder = .init(); const r = decoder.decode("\x1b[4:2m", .normal, .wcwidth); try t.expectEqual(6, r.n); const ps = decoder.params(); try t.expectEqual(2, ps.len); try t.expect(hasMore(ps[0])); try t.expectEqual(2, paramValue(ps[1], 0)); } test "decode osc8 hyperlink" { var decoder: Decoder = .init(); var r = decoder.decode("\x1b]8;id=1;https://example.com\x07x", .normal, .wcwidth); try t.expectEqual(29, r.n); try t.expectEqual(8, decoder.cmd); try t.expectEqualStrings("8;id=1;https://example.com", decoder.data()); r = decoder.decode("\x07x", .normal, .wcwidth); try t.expectEqual(1, r.n); } test "decode escapes and controls" { var decoder: Decoder = .init(); var r = decoder.decode("a\x1b[b", .normal, .wcwidth); try t.expectEqual(1, r.n); r = decoder.decode("\x1b[b", .normal, .wcwidth); try t.expectEqual(3, r.n); try t.expectEqual('b', decoder.cmd & 0xff); } test "readStyle parses sgr" { var decoder: Decoder = .init(); _ = decoder.decode("\x1b[31;1;4m", .normal, .wcwidth); var style = Style{}; style.read(decoder.params()); try t.expectEqual(Color.red, style.fg.?); try t.expect(style.attrs.bold); try t.expect(style.underline == .single); } test "readStyle colors" { var decoder: Decoder = .init(); _ = decoder.decode("\x1b[38;5;196;48;2;1;2;3m", .normal, .wcwidth); var style: Style = .{}; style.read(decoder.params()); try t.expectEqual(Color{ .ansi256 = 196 }, style.fg.?); try t.expectEqual(Color.fromRgb(1, 2, 3), style.bg.?); } test "readStyle reset clears" { var decoder: Decoder = .init(); var style: Style = .{ .fg = .red, .attrs = .{ .bold = true } }; _ = decoder.decode("\x1b[m", .normal, .wcwidth); style.read(decoder.params()); try t.expect(style.isZero()); } test "readLink hyperlink" { var link: Link = .{}; try link.read(t.allocator, "8;id=1;https://example.com"); defer link.deinit(t.allocator); try t.expectEqualStrings("https://example.com", link.url); try t.expectEqualStrings("id=1", link.params); } test "lines are built unwrapped and unbounded" { const string: String = .new("Hello,\nWorld!\nThird"); const lines_ = try string.lines(t.allocator, .wcwidth); defer { for (lines_) |line| t.allocator.free(line.cells); t.allocator.free(lines_); } try t.expectEqual(3, lines_.len); const s0 = try concatCells(t.allocator, lines_[0]); defer t.allocator.free(s0); try t.expectEqualStrings("Hello,", s0); const s1 = try concatCells(t.allocator, lines_[1]); defer t.allocator.free(s1); try t.expectEqualStrings("World!", s1); const s2 = try concatCells(t.allocator, lines_[2]); defer t.allocator.free(s2); try t.expectEqualStrings("Third", s2); } test "lines keeps empty lines" { const string: String = .new("\n\n"); const lines_ = try string.lines(t.allocator, .wcwidth); defer { for (lines_) |l| t.allocator.free(l.cells); t.allocator.free(lines_); } try t.expectEqual(3, lines_.len); try t.expectEqual(0, lines_[0].cells.len); try t.expectEqual(0, lines_[1].cells.len); try t.expectEqual(0, lines_[2].cells.len); } test "lines folds combining marks and keeps styles" { const string: String = .new("a\u{0301}\x1b[31mR"); const lines_ = try string.lines(t.allocator, .wcwidth); defer { for (lines_) |l| t.allocator.free(l.cells); t.allocator.free(lines_); } try t.expectEqual(2, lines_[0].cells.len); try t.expectEqualStrings("a\u{0301}", lines_[0].cells[0].content); try t.expectEqualStrings("R", lines_[0].cells[1].content); try t.expectEqual(Color.red, lines_[0].cells[1].style.fg.?); } test "draw renders styled text" { var buf: Screen = try .init(t.allocator, 6, 2); defer buf.deinit(); try String.new("Hi\nYo").draw(t.allocator, &buf, .new(0, 0, 6, 2)); try t.expectEqualStrings("H", buf.render_buffer.buffer.cellAt(0, 0).?.content); try t.expectEqualStrings("i", buf.render_buffer.buffer.cellAt(1, 0).?.content); try t.expectEqualStrings("Y", buf.render_buffer.buffer.cellAt(0, 1).?.content); try t.expectEqualStrings("o", buf.render_buffer.buffer.cellAt(1, 1).?.content); } test "draw wraps long lines" { var buf: Screen = try .init(t.allocator, 2, 2); defer buf.deinit(); try String.new("Hello!").draw(t.allocator, &buf, .new(0, 0, 2, 2)); try t.expectEqualStrings("H", buf.render_buffer.buffer.cellAt(0, 0).?.content); try t.expectEqualStrings("e", buf.render_buffer.buffer.cellAt(1, 0).?.content); try t.expectEqualStrings("l", buf.render_buffer.buffer.cellAt(0, 1).?.content); try t.expectEqualStrings("l", buf.render_buffer.buffer.cellAt(1, 1).?.content); } test "draw truncates with tail" { var buf: Screen = try .init(t.allocator, 5, 1); defer buf.deinit(); var string: String = .new("Hello, world!"); string.wrap = false; string.tail = "…"; try string.draw(t.allocator, &buf, .new(0, 0, 5, 1)); try t.expectEqualStrings("H", buf.render_buffer.buffer.cellAt(0, 0).?.content); try t.expectEqualStrings("e", buf.render_buffer.buffer.cellAt(1, 0).?.content); try t.expectEqualStrings("l", buf.render_buffer.buffer.cellAt(2, 0).?.content); try t.expectEqualStrings("l", buf.render_buffer.buffer.cellAt(3, 0).?.content); try t.expectEqualStrings("…", buf.render_buffer.buffer.cellAt(4, 0).?.content); } test "draw clears the area first" { var buf: Screen = try .init(t.allocator, 4, 1); defer buf.deinit(); try String.new("ab").draw(t.allocator, &buf, .new(0, 0, 4, 1)); // Cols 2 and 3 were cleared to spaces. try t.expectEqualStrings(" ", buf.render_buffer.buffer.cellAt(2, 0).?.content); try t.expectEqualStrings(" ", buf.render_buffer.buffer.cellAt(3, 0).?.content); } test "draw normalizes crlf and clips at bounds height" { var buf: Screen = try .init(t.allocator, 4, 1); defer buf.deinit(); try String.new("abc\r\ndef").draw(t.allocator, &buf, .new(0, 0, 4, 1)); try t.expectEqualStrings("a", buf.render_buffer.buffer.cellAt(0, 0).?.content); try t.expectEqualStrings("b", buf.render_buffer.buffer.cellAt(1, 0).?.content); try t.expectEqualStrings("c", buf.render_buffer.buffer.cellAt(2, 0).?.content); // "def" is on line 2, outside the 1-row area, so the cursor may be past // the area but col 3 stays the cleared space. try t.expectEqualStrings(" ", buf.render_buffer.buffer.cellAt(3, 0).?.content); } test "height and widthHeight" { const string: String = .new("Hello,\nWorld!\n"); try t.expectEqual(3, string.height()); } test "bounds reflect widest line grapheme width" { const bounds = String.new("a\x1b[31m世界b\nab").bounds(); try t.expectEqual(6, bounds.max_x); try t.expectEqual(2, bounds.max_y); } test "styledWidth ignores escape sequences" { try t.expectEqual(4, styledWidth(.wcwidth, "a\x1b[31mbc\x1b[0md")); } fn concatCells(allocator: Allocator, line: Line) Allocator.Error![]u8 { var out = try allocator.alloc(u8, 64); defer allocator.free(out); var used: usize = 0; for (line.cells) |cell| { @memcpy(out[used .. used + cell.content.len], cell.content); used += cell.content.len; } return allocator.dupe(u8, out[0..used]); } test "fuzz styled" { try t.fuzz({}, fuzzStyled, .{ .corpus = &.{ "", "plain text", "a\u{301}bc", "世\u{200d}界", "\x1b[1;31mred\x1b[0m", "\x1b[38;2;12;34;56m", "\x1b]8;;http://example.com\x1b\\link\x1b]8;;\x1b\\", "\r\n\x00\x1b[\x1b]", }, }); } fn fuzzStyled(_: void, smith: *t.Smith) anyerror!void { var buf: [512]u8 = undefined; const len = smith.slice(&buf); const text = buf[0..len]; // Directly drive the escape-sequence state machine. var dec: Decoder = .init(); var state: State = .normal; var i: usize = 0; while (i < len) { const r = dec.decode(text[i..], state, ir.width.Method.wcwidth); state = r.state; i += @max(r.n, 1); } // The lines/draw paths own allocations for folded combining marks and // hyperlink payloads (see file header); reclaim them all via an arena. var arena: std.heap.ArenaAllocator = .init(t.allocator); defer arena.deinit(); const aa = arena.allocator(); const str = String.new(text); if (str.lines(aa, ir.width.Method.wcwidth)) |lines| { _ = lines; } else |_| {} var sc: ir.Buffer = try .init(aa, 16, 16); str.draw(aa, &sc, .new(0, 0, 16, 16)) catch {}; _ = str.widthHeight(ir.width.Method.grapheme); _ = str.bounds(); _ = str.string(); } test "fuzz styled helpers" { try t.fuzz({}, fuzzStyledHelpers, .{ .corpus = &.{ "", "38;2;1;2;3", "38;5;196", "48;2;255;255;255", "0:1:2:3:4:5", "38;2;1;2", "a\u{301}\u{302}b", }, }); } fn fuzzStyledHelpers(_: void, smith: *t.Smith) anyerror!void { var params: [MaxParams]u32 = @splat(0); const n = smith.index(params.len + 1); for (params[0..n]) |*p| { // Color channels are u8-sized and the high bit marks a colon // sub-parameter; keeping values below 256 avoids integer-cast traps // inside `readStyleColor`'s channel packing. p.* = smith.valueRangeLessThan(u32, 0, 256) | (if (smith.value(bool)) HasMoreFlag else @as(u32, 0)); } var color: ?Color = null; _ = readStyleColor(params[0..n], &color); for (params[0..n], 0..) |p, i| { _ = paramValue(p, 0); _ = hasMore(p); _ = paramAt(params[0..n], i, 7); _ = paramAt(params[0..n], i + 1, 7); } var buf: [128]u8 = undefined; const blen = smith.slice(&buf); const cluster = firstGraphemeCluster(buf[0..blen]); _ = cluster; }