peppa/packages/runner/src/tmux-status.ts
2026-11-25 12:58:02 +00:00

200 lines
7.0 KiB
TypeScript

// tmux status line for the web terminal (PEP-257): capture-pane has only the pane, the status
// line is drawn by tmux for an attached client. tmux expands its own `status-format` for us
// (`#{T:status-format[i]}`); what is left are `#[…]` style directives, turned here into SGR and
// laid out on the window width the way tmux does: left, centre and right parts.
interface Style {
fg: string | null;
bg: string | null;
attrs: Set<string>;
}
const COLOURS = ["black", "red", "green", "yellow", "blue", "magenta", "cyan", "white"];
const ATTRS: Record<string, string> = {
bright: "1",
bold: "1",
dim: "2",
italics: "3",
underscore: "4",
"double-underscore": "4",
"curly-underscore": "4",
"dotted-underscore": "4",
"dashed-underscore": "4",
blink: "5",
reverse: "7",
hidden: "8",
strikethrough: "9",
overline: "53",
};
const clone = (s: Style): Style => ({ fg: s.fg, bg: s.bg, attrs: new Set(s.attrs) });
const EMPTY: Style = { fg: null, bg: null, attrs: new Set() };
/** SGR parameters of a tmux colour for fg (`base` 30) or bg (40); null — the terminal default. */
export function colourSgr(c: string, bg: boolean): string | null {
const v = c.toLowerCase();
const base = bg ? 40 : 30;
if (v === "default" || v === "terminal" || v === "") return null;
const i = COLOURS.indexOf(v);
if (i >= 0) return String(base + i);
if (v.startsWith("bright")) {
const j = COLOURS.indexOf(v.slice(6));
if (j >= 0) return String(base + 60 + j);
}
const n = /^colou?r(\d{1,3})$/.exec(v);
if (n && Number(n[1]) < 256) return `${base + 8};5;${Number(n[1])}`;
const hex = /^#([0-9a-f]{6})$/.exec(v);
if (hex) {
const x = parseInt(hex[1]!, 16);
return `${base + 8};2;${(x >> 16) & 255};${(x >> 8) & 255};${x & 255}`;
}
return null;
}
/** Applies one tmux style list (`fg=red,bold` / `bg=green fg=black`) to `s`; returns layout tokens. */
function applyStyle(spec: string, s: Style, defaults: Style[]): Array<[string, string]> {
const layout: Array<[string, string]> = [];
for (const raw of spec.split(/[\s,]+/)) {
const tok = raw.trim();
if (!tok) continue;
const eq = tok.indexOf("=");
const key = (eq < 0 ? tok : tok.slice(0, eq)).toLowerCase();
const val = eq < 0 ? "" : tok.slice(eq + 1);
// In a status line `fg=default` is the status style's colour, not the terminal's.
if (key === "fg") s.fg = val === "default" ? (defaults.at(-1) ?? EMPTY).fg : val;
else if (key === "bg") s.bg = val === "default" ? (defaults.at(-1) ?? EMPTY).bg : val;
else if (key === "default") {
const d = defaults.at(-1) ?? EMPTY;
s.fg = d.fg;
s.bg = d.bg;
s.attrs = new Set(d.attrs);
} else if (key === "none" || key === "noattr") s.attrs.clear();
else if (key === "push-default") defaults.push(clone(s));
else if (key === "pop-default") {
if (defaults.length > 1) defaults.pop();
} else if (key in ATTRS) s.attrs.add(key);
else if (key.startsWith("no") && key.slice(2) in ATTRS) s.attrs.delete(key.slice(2));
else if (key === "align" || key === "list" || key === "nolist") layout.push([key, val]);
// range=, norange, fill=, us=, ignore, acs… do not change what is drawn.
}
return layout;
}
/** Parses a style list (status-style) into a style. */
export function parseStyle(spec: string): Style {
const s = clone(EMPTY);
applyStyle(spec, s, [clone(EMPTY)]);
return s;
}
const sgr = (s: Style) => {
const p = ["0"];
for (const a of s.attrs) p.push(ATTRS[a]!);
const fg = s.fg && colourSgr(s.fg, false);
const bg = s.bg && colourSgr(s.bg, true);
if (fg) p.push(fg);
if (bg) p.push(bg);
return `\x1b[${p.join(";")}m`;
};
/** Terminal cells a code point takes: wide CJK and emoji 2, combining marks 0. */
export function charWidth(cp: number): number {
if (cp === 0x200d || (cp >= 0x300 && cp <= 0x36f) || (cp >= 0xfe00 && cp <= 0xfe0f) || (cp >= 0x20d0 && cp <= 0x20ff)) return 0;
if (
(cp >= 0x1100 && cp <= 0x115f) ||
(cp >= 0x2e80 && cp <= 0xa4cf && cp !== 0x303f) ||
(cp >= 0xac00 && cp <= 0xd7a3) ||
(cp >= 0xf900 && cp <= 0xfaff) ||
(cp >= 0xfe30 && cp <= 0xfe4f) ||
(cp >= 0xff00 && cp <= 0xff60) ||
(cp >= 0xffe0 && cp <= 0xffe6) ||
(cp >= 0x1f300 && cp <= 0x1f64f) ||
(cp >= 0x1f900 && cp <= 0x1f9ff) ||
(cp >= 0x20000 && cp <= 0x3fffd)
)
return 2;
return 1;
}
interface Cell {
ch: string;
w: number;
style: Style;
}
type Align = "left" | "centre" | "right";
/**
* One status line of `width` cells as SGR text: `format` is tmux's own expansion of
* `status-format[i]`, `base` — `status-style` (what `default` means).
*/
export function renderStatusLine(format: string, width: number, base: string): string {
const baseStyle = parseStyle(base);
const defaults = [clone(baseStyle)];
const style = clone(baseStyle);
const parts: Record<Align, Cell[]> = { left: [], centre: [], right: [] };
let align: Align = "left";
let hidden = false; // list markers: drawn by tmux only when the window list is cut
let i = 0;
while (i < format.length) {
if (format.startsWith("#[", i)) {
const end = format.indexOf("]", i + 2);
if (end < 0) break;
for (const [k, v] of applyStyle(format.slice(i + 2, end), style, defaults)) {
if (k === "align") align = v === "right" ? "right" : v === "centre" || v === "absolute-centre" ? "centre" : "left";
else if (k === "list") hidden = v === "left-marker" || v === "right-marker";
else if (k === "nolist") hidden = false;
}
i = end + 1;
continue;
}
if (format.startsWith("##", i)) i++;
const cp = format.codePointAt(i)!;
const ch = String.fromCodePoint(cp);
i += ch.length;
if (hidden || cp < 0x20) continue;
parts[align].push({ ch, w: charWidth(cp), style: clone(style) });
}
const span = (cells: Cell[]) => cells.reduce((n, c) => n + c.w, 0);
const fit = (cells: Cell[], room: number, fromEnd = false) => {
const out: Cell[] = [];
let used = 0;
const list = fromEnd ? [...cells].reverse() : cells;
for (const c of list) {
if (used + c.w > room) break;
used += c.w;
out.push(c);
}
return fromEnd ? out.reverse() : out;
};
const row: Array<Cell | null> = Array(width).fill(null);
const place = (cells: Cell[], at: number) => {
let x = at;
for (const c of cells) {
if (x + c.w > width) break;
row[x] = c;
for (let k = 1; k < c.w; k++) row[x + k] = { ch: "", w: 0, style: c.style };
x += c.w;
}
};
const left = fit(parts.left, width);
const lw = span(left);
const right = fit(parts.right, width - lw, true);
const rw = span(right);
const centre = fit(parts.centre, width - lw - rw);
const cw = span(centre);
place(left, 0);
place(right, width - rw);
place(centre, Math.max(lw, Math.min(width - rw - cw, Math.floor((width - cw) / 2))));
let out = "";
let last = "";
for (const c of row) {
const code = sgr(c?.style ?? baseStyle);
if (code !== last) out += code;
last = code;
if (c === null) out += " ";
else out += c.ch;
}
return out + "\x1b[0m";
}