@intellectual-frontiers/terminal 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +8 -2
- package/dist/args.d.ts +240 -0
- package/dist/args.js +328 -0
- package/dist/commands.d.ts +103 -0
- package/dist/commands.js +127 -0
- package/dist/mod.d.ts +19 -0
- package/dist/mod.js +20 -0
- package/dist/palette.d.ts +44 -0
- package/dist/palette.js +84 -0
- package/dist/vt.d.ts +78 -0
- package/dist/vt.js +486 -0
- package/dist/width.d.ts +63 -0
- package/dist/width.js +170 -0
- package/package.json +63 -4
- package/src/args.ts +547 -0
- package/src/commands.ts +182 -0
- package/src/mod.ts +20 -0
- package/src/palette.ts +104 -0
- package/src/vt.ts +497 -0
- package/src/width.ts +181 -0
package/src/vt.ts
ADDED
|
@@ -0,0 +1,497 @@
|
|
|
1
|
+
// Spec: 0001-terminal FR-005
|
|
2
|
+
/**
|
|
3
|
+
* A small terminal emulator for snapshot tests (commons 0006-signals FR-025): a screen a given number of columns wide, either growing as it
|
|
4
|
+
* is written to (no height) or a given number of rows high and scrolling, that is fed what a program writes and shows what a person would
|
|
5
|
+
* see after it: the text, each cell's style kept apart from it, and the cursor.
|
|
6
|
+
*
|
|
7
|
+
* What it understands, as xterm does:
|
|
8
|
+
* - printable text by grapheme and display width (`width.ts`): a wide character or emoji takes two cells (the second a continuation), a
|
|
9
|
+
* combining mark or another zero-width grapheme joins the cell before; a character that does not fit in the last column wraps to the next
|
|
10
|
+
* line (autowrap with the wrap deferred until the next character, so a line exactly as wide as the screen does not add an empty one), and a
|
|
11
|
+
* wide character that would cross the right edge wraps whole, leaving the last cell empty;
|
|
12
|
+
* - CR, LF (also VT and FF), BS and TAB (stops every eight columns); LF also returns the carriage by default (`newline: "crlf"`, as a
|
|
13
|
+
* terminal's line discipline turns a program's "\n" into CR LF), or only moves down (`newline: "lf"`);
|
|
14
|
+
* - CSI cursor up, down, forward and back (A, B, C, D), next and previous line (E, F), column (G), row (d), position (H, f), save and
|
|
15
|
+
* restore (s, u, and ESC 7, ESC 8), erase in line (K 0, 1, 2) and in display (J 0, 1, 2, 3), and SGR (m: bold, dim, italic, underline,
|
|
16
|
+
* blink, inverse, hidden, strike, their resets, the 8, 16, 256 and 24-bit colours of text and background);
|
|
17
|
+
* - cursor shown and hidden (CSI ? 25 h and l), kept in `cursor().visible`;
|
|
18
|
+
* - every other control sequence, other private mode, OSC, DCS, APC, PM and SOS string, other escape and other control character: read
|
|
19
|
+
* and ignored. A sequence may be split across writes; bytes are decoded as UTF-8 across writes too.
|
|
20
|
+
*
|
|
21
|
+
* Erased cells take no style. A grapheme split across two writes is seen as two (the second joins the first cell, without changing its
|
|
22
|
+
* width).
|
|
23
|
+
*
|
|
24
|
+
* @example
|
|
25
|
+
* ```ts
|
|
26
|
+
* import { createScreen } from "./vt.ts";
|
|
27
|
+
* const s = createScreen({ width: 20 });
|
|
28
|
+
* s.write("building\n\u001b[32m✅\u001b[0m done");
|
|
29
|
+
* s.write("\u001b[1A\r\u001b[2Kbuilt");
|
|
30
|
+
* s.text(); // "built\n✅ done"
|
|
31
|
+
* s.cell(1, 0)?.style.fg; // { kind: "indexed", index: 2 }
|
|
32
|
+
* ```
|
|
33
|
+
*
|
|
34
|
+
* @module
|
|
35
|
+
*/
|
|
36
|
+
import { absurd } from "@intellectual-frontiers/core";
|
|
37
|
+
import { graphemes, graphemeWidth } from "./width.ts";
|
|
38
|
+
|
|
39
|
+
/** A colour of text or background: the terminal's default, one of 256 indexed colours (0 to 15 the basic and bright ones), or 24-bit. */
|
|
40
|
+
export type Colour =
|
|
41
|
+
| { readonly kind: "default" }
|
|
42
|
+
| { readonly kind: "indexed"; readonly index: number }
|
|
43
|
+
| { readonly kind: "rgb"; readonly r: number; readonly g: number; readonly b: number };
|
|
44
|
+
|
|
45
|
+
/** How a cell's text is drawn, as SGR left it. */
|
|
46
|
+
export type Style = {
|
|
47
|
+
readonly bold: boolean;
|
|
48
|
+
readonly dim: boolean;
|
|
49
|
+
readonly italic: boolean;
|
|
50
|
+
readonly underline: boolean;
|
|
51
|
+
readonly blink: boolean;
|
|
52
|
+
readonly inverse: boolean;
|
|
53
|
+
readonly hidden: boolean;
|
|
54
|
+
readonly strike: boolean;
|
|
55
|
+
readonly fg: Colour;
|
|
56
|
+
readonly bg: Colour;
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
const DEFAULT: Colour = { kind: "default" };
|
|
60
|
+
|
|
61
|
+
/** The style of a cell nothing styled: every attribute off, default colours. */
|
|
62
|
+
export const PLAIN: Style = {
|
|
63
|
+
bold: false,
|
|
64
|
+
dim: false,
|
|
65
|
+
italic: false,
|
|
66
|
+
underline: false,
|
|
67
|
+
blink: false,
|
|
68
|
+
inverse: false,
|
|
69
|
+
hidden: false,
|
|
70
|
+
strike: false,
|
|
71
|
+
fg: DEFAULT,
|
|
72
|
+
bg: DEFAULT,
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
const colourName = (c: Colour): string => {
|
|
76
|
+
switch (c.kind) {
|
|
77
|
+
case "default":
|
|
78
|
+
return "default";
|
|
79
|
+
case "indexed":
|
|
80
|
+
return String(c.index);
|
|
81
|
+
case "rgb":
|
|
82
|
+
return `#${[c.r, c.g, c.b].map((n) => n.toString(16).padStart(2, "0")).join("")}`;
|
|
83
|
+
default:
|
|
84
|
+
return absurd(c);
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
/** A style in words, for a snapshot: the attributes on, then `fg=` and `bg=` where not the default; "" for `PLAIN`. */
|
|
89
|
+
export function describeStyle(style: Style): string {
|
|
90
|
+
const words: string[] = [];
|
|
91
|
+
for (const a of ["bold", "dim", "italic", "underline", "blink", "inverse", "hidden", "strike"] as const) if (style[a]) words.push(a);
|
|
92
|
+
if (style.fg.kind !== "default") words.push(`fg=${colourName(style.fg)}`);
|
|
93
|
+
if (style.bg.kind !== "default") words.push(`bg=${colourName(style.bg)}`);
|
|
94
|
+
return words.join(" ");
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Whether two styles draw the same. */
|
|
98
|
+
export function sameStyle(a: Style, b: Style): boolean {
|
|
99
|
+
return describeStyle(a) === describeStyle(b);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** One cell of the screen: a grapheme and its style; a wide grapheme's second cell is a continuation, of width 0 and empty text. */
|
|
103
|
+
export type Cell = { readonly text: string; readonly width: 0 | 1 | 2; readonly style: Style };
|
|
104
|
+
|
|
105
|
+
/** A run of cells of one style on a line, their text joined. */
|
|
106
|
+
export type Run = { readonly text: string; readonly style: Style };
|
|
107
|
+
|
|
108
|
+
/** Where the cursor is (row and column from 0) and whether it is shown. */
|
|
109
|
+
export type Cursor = { readonly row: number; readonly col: number; readonly visible: boolean };
|
|
110
|
+
|
|
111
|
+
/** The size of a screen and how it reads a line feed. */
|
|
112
|
+
export type ScreenOptions = {
|
|
113
|
+
/** Columns; at least 1. */
|
|
114
|
+
readonly width: number;
|
|
115
|
+
/** Rows: the screen scrolls when a line feed is written on the last; without it, the screen grows. */
|
|
116
|
+
readonly height?: number;
|
|
117
|
+
/** "crlf" (the default): a line feed also returns the carriage, as a terminal's line discipline does; "lf": it only moves down. */
|
|
118
|
+
readonly newline?: "crlf" | "lf";
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
/** A screen being written to. */
|
|
122
|
+
export type Screen = {
|
|
123
|
+
/** Its width in columns. */
|
|
124
|
+
readonly width: number;
|
|
125
|
+
/** Its height in rows, or undefined where it grows. */
|
|
126
|
+
readonly height: number | undefined;
|
|
127
|
+
/** Feeds it what a program writes: text, or bytes decoded as UTF-8 (a character may be split across writes). */
|
|
128
|
+
write(data: string | Uint8Array): void;
|
|
129
|
+
/** Its lines as text: trailing spaces of each line and trailing empty lines left out. */
|
|
130
|
+
lines(): readonly string[];
|
|
131
|
+
/** Its lines joined by "\n". */
|
|
132
|
+
text(): string;
|
|
133
|
+
/** Its lines as runs of one style, trailing unstyled spaces and trailing empty lines left out. */
|
|
134
|
+
styled(): readonly (readonly Run[])[];
|
|
135
|
+
/** The cell at a row and column; undefined outside the screen. */
|
|
136
|
+
cell(row: number, col: number): Cell | undefined;
|
|
137
|
+
/** The cursor. */
|
|
138
|
+
cursor(): Cursor;
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
const BLANK: Cell = { text: " ", width: 1, style: PLAIN };
|
|
142
|
+
const CONTINUATION = (style: Style): Cell => ({ text: "", width: 0, style });
|
|
143
|
+
|
|
144
|
+
type ParserState = "ground" | "escape" | "csi" | "string" | "string-escape";
|
|
145
|
+
|
|
146
|
+
/** A new, empty screen with the cursor at the top left, shown. */
|
|
147
|
+
export function createScreen(options: ScreenOptions): Screen {
|
|
148
|
+
const width = Math.max(1, Math.floor(options.width));
|
|
149
|
+
const height = options.height === undefined ? undefined : Math.max(1, Math.floor(options.height));
|
|
150
|
+
const crlf = (options.newline ?? "crlf") === "crlf";
|
|
151
|
+
const rows: Cell[][] = [];
|
|
152
|
+
const decoder = new TextDecoder();
|
|
153
|
+
|
|
154
|
+
let row = 0;
|
|
155
|
+
let col = 0;
|
|
156
|
+
let pending = false;
|
|
157
|
+
let visible = true;
|
|
158
|
+
let style = PLAIN;
|
|
159
|
+
let saved = { row: 0, col: 0, style: PLAIN };
|
|
160
|
+
let state: ParserState = "ground";
|
|
161
|
+
let seq = "";
|
|
162
|
+
let text = "";
|
|
163
|
+
|
|
164
|
+
const blankRow = (): Cell[] => Array.from({ length: width }, () => BLANK);
|
|
165
|
+
const line = (r: number): Cell[] => {
|
|
166
|
+
while (rows.length <= r) rows.push(blankRow());
|
|
167
|
+
return rows[r] ?? blankRow();
|
|
168
|
+
};
|
|
169
|
+
const maxRow = (): number => (height === undefined ? Number.MAX_SAFE_INTEGER : height - 1);
|
|
170
|
+
const clampCol = (c: number): number => Math.min(width - 1, Math.max(0, c));
|
|
171
|
+
const clampRow = (r: number): number => Math.min(maxRow(), Math.max(0, r));
|
|
172
|
+
|
|
173
|
+
const linefeed = (): void => {
|
|
174
|
+
if (height !== undefined && row === height - 1) {
|
|
175
|
+
line(height - 1);
|
|
176
|
+
rows.shift();
|
|
177
|
+
rows.push(blankRow());
|
|
178
|
+
} else {
|
|
179
|
+
row++;
|
|
180
|
+
}
|
|
181
|
+
};
|
|
182
|
+
|
|
183
|
+
/** Blanks columns `from` to `to` (inclusive) of a row, with the halves of wide characters cut by the edges. */
|
|
184
|
+
const blank = (r: number, from: number, to: number): void => {
|
|
185
|
+
const l = line(r);
|
|
186
|
+
let a = Math.max(0, from);
|
|
187
|
+
let b = Math.min(width - 1, to);
|
|
188
|
+
if (a > b) return;
|
|
189
|
+
if (l[a]?.width === 0 && a > 0) a--;
|
|
190
|
+
if (l[b]?.width === 2 && b < width - 1) b++;
|
|
191
|
+
for (let c = a; c <= b; c++) l[c] = BLANK;
|
|
192
|
+
};
|
|
193
|
+
|
|
194
|
+
const put = (g: string, w: 1 | 2): void => {
|
|
195
|
+
const l = line(row);
|
|
196
|
+
blank(row, col, col + w - 1);
|
|
197
|
+
l[col] = { text: g, width: w, style };
|
|
198
|
+
if (w === 2 && col + 1 < width) l[col + 1] = CONTINUATION(style);
|
|
199
|
+
};
|
|
200
|
+
|
|
201
|
+
const print = (chunk: string): void => {
|
|
202
|
+
for (const g of graphemes(chunk)) {
|
|
203
|
+
const w = graphemeWidth(g);
|
|
204
|
+
if (w === 0) {
|
|
205
|
+
const cp = g.codePointAt(0) ?? 0;
|
|
206
|
+
if (cp < 0x20 || (cp >= 0x7f && cp < 0xa0)) continue;
|
|
207
|
+
let c = pending ? col : col - 1;
|
|
208
|
+
const l = line(row);
|
|
209
|
+
if (l[c]?.width === 0) c--;
|
|
210
|
+
const cell = l[c];
|
|
211
|
+
if (c >= 0 && cell !== undefined) l[c] = { ...cell, text: cell.text + g };
|
|
212
|
+
continue;
|
|
213
|
+
}
|
|
214
|
+
if (pending) {
|
|
215
|
+
col = 0;
|
|
216
|
+
linefeed();
|
|
217
|
+
pending = false;
|
|
218
|
+
}
|
|
219
|
+
if (col + w > width && col > 0) {
|
|
220
|
+
col = 0;
|
|
221
|
+
linefeed();
|
|
222
|
+
}
|
|
223
|
+
put(g, w > width ? 1 : w);
|
|
224
|
+
col += Math.min(w, width);
|
|
225
|
+
if (col >= width) {
|
|
226
|
+
col = width - 1;
|
|
227
|
+
pending = true;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
};
|
|
231
|
+
|
|
232
|
+
const flush = (): void => {
|
|
233
|
+
if (text !== "") print(text);
|
|
234
|
+
text = "";
|
|
235
|
+
};
|
|
236
|
+
|
|
237
|
+
const sgr = (params: readonly number[]): void => {
|
|
238
|
+
const ps = params.length === 0 ? [0] : params;
|
|
239
|
+
const extended = (i: number): { readonly colour: Colour; readonly used: number } => {
|
|
240
|
+
if (ps[i + 1] === 5) return { colour: { kind: "indexed", index: (ps[i + 2] ?? 0) & 0xff }, used: 2 };
|
|
241
|
+
if (ps[i + 1] === 2) {
|
|
242
|
+
const at = (k: number): number => (ps[i + k] ?? 0) & 0xff;
|
|
243
|
+
return { colour: { kind: "rgb", r: at(2), g: at(3), b: at(4) }, used: 4 };
|
|
244
|
+
}
|
|
245
|
+
return { colour: DEFAULT, used: 0 };
|
|
246
|
+
};
|
|
247
|
+
for (let i = 0; i < ps.length; i++) {
|
|
248
|
+
const p = ps[i] ?? 0;
|
|
249
|
+
if (p === 0) style = PLAIN;
|
|
250
|
+
else if (p === 1) style = { ...style, bold: true };
|
|
251
|
+
else if (p === 2) style = { ...style, dim: true };
|
|
252
|
+
else if (p === 3) style = { ...style, italic: true };
|
|
253
|
+
else if (p === 4) style = { ...style, underline: true };
|
|
254
|
+
else if (p === 5 || p === 6) style = { ...style, blink: true };
|
|
255
|
+
else if (p === 7) style = { ...style, inverse: true };
|
|
256
|
+
else if (p === 8) style = { ...style, hidden: true };
|
|
257
|
+
else if (p === 9) style = { ...style, strike: true };
|
|
258
|
+
else if (p === 21 || p === 24) style = { ...style, underline: false };
|
|
259
|
+
else if (p === 22) style = { ...style, bold: false, dim: false };
|
|
260
|
+
else if (p === 23) style = { ...style, italic: false };
|
|
261
|
+
else if (p === 25) style = { ...style, blink: false };
|
|
262
|
+
else if (p === 27) style = { ...style, inverse: false };
|
|
263
|
+
else if (p === 28) style = { ...style, hidden: false };
|
|
264
|
+
else if (p === 29) style = { ...style, strike: false };
|
|
265
|
+
else if (p >= 30 && p <= 37) style = { ...style, fg: { kind: "indexed", index: p - 30 } };
|
|
266
|
+
else if (p === 39) style = { ...style, fg: DEFAULT };
|
|
267
|
+
else if (p >= 40 && p <= 47) style = { ...style, bg: { kind: "indexed", index: p - 40 } };
|
|
268
|
+
else if (p === 49) style = { ...style, bg: DEFAULT };
|
|
269
|
+
else if (p >= 90 && p <= 97) style = { ...style, fg: { kind: "indexed", index: p - 90 + 8 } };
|
|
270
|
+
else if (p >= 100 && p <= 107) style = { ...style, bg: { kind: "indexed", index: p - 100 + 8 } };
|
|
271
|
+
else if (p === 38 || p === 48) {
|
|
272
|
+
const { colour, used } = extended(i);
|
|
273
|
+
style = p === 38 ? { ...style, fg: colour } : { ...style, bg: colour };
|
|
274
|
+
i += used;
|
|
275
|
+
} else if (p === 58) i += extended(i).used;
|
|
276
|
+
}
|
|
277
|
+
};
|
|
278
|
+
|
|
279
|
+
const csi = (body: string, final: string): void => {
|
|
280
|
+
const priv = /^[<=>?]/.test(body);
|
|
281
|
+
const raw = (priv ? body.slice(1) : body).replace(/[ -/]+$/, "");
|
|
282
|
+
const params = raw === "" ? [] : raw.split(/[;:]/).map((p) => (p === "" ? 0 : Number.parseInt(p, 10) || 0));
|
|
283
|
+
if (priv) {
|
|
284
|
+
if (body.startsWith("?") && params.includes(25) && (final === "h" || final === "l")) visible = final === "h";
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
if (/[ -/]$/.test(body)) return; // a sequence with intermediates is none of these
|
|
288
|
+
const n = Math.max(1, params[0] ?? 1);
|
|
289
|
+
switch (final) {
|
|
290
|
+
case "A":
|
|
291
|
+
row = clampRow(row - n);
|
|
292
|
+
break;
|
|
293
|
+
case "B":
|
|
294
|
+
row = clampRow(row + n);
|
|
295
|
+
break;
|
|
296
|
+
case "C":
|
|
297
|
+
col = clampCol(col + n);
|
|
298
|
+
break;
|
|
299
|
+
case "D":
|
|
300
|
+
col = clampCol(col - n);
|
|
301
|
+
break;
|
|
302
|
+
case "E":
|
|
303
|
+
row = clampRow(row + n);
|
|
304
|
+
col = 0;
|
|
305
|
+
break;
|
|
306
|
+
case "F":
|
|
307
|
+
row = clampRow(row - n);
|
|
308
|
+
col = 0;
|
|
309
|
+
break;
|
|
310
|
+
case "G":
|
|
311
|
+
case "`":
|
|
312
|
+
col = clampCol(n - 1);
|
|
313
|
+
break;
|
|
314
|
+
case "d":
|
|
315
|
+
row = clampRow(n - 1);
|
|
316
|
+
break;
|
|
317
|
+
case "H":
|
|
318
|
+
case "f":
|
|
319
|
+
row = clampRow(n - 1);
|
|
320
|
+
col = clampCol(Math.max(1, params[1] ?? 1) - 1);
|
|
321
|
+
break;
|
|
322
|
+
case "K": {
|
|
323
|
+
const mode = params[0] ?? 0;
|
|
324
|
+
if (mode === 0) blank(row, col, width - 1);
|
|
325
|
+
else if (mode === 1) blank(row, 0, col);
|
|
326
|
+
else if (mode === 2) blank(row, 0, width - 1);
|
|
327
|
+
break;
|
|
328
|
+
}
|
|
329
|
+
case "J": {
|
|
330
|
+
const mode = params[0] ?? 0;
|
|
331
|
+
if (mode === 0) {
|
|
332
|
+
blank(row, col, width - 1);
|
|
333
|
+
if (height === undefined) rows.length = Math.min(rows.length, row + 1);
|
|
334
|
+
else for (let r = row + 1; r < height; r++) blank(r, 0, width - 1);
|
|
335
|
+
} else if (mode === 1) {
|
|
336
|
+
for (let r = 0; r < row; r++) blank(r, 0, width - 1);
|
|
337
|
+
blank(row, 0, col);
|
|
338
|
+
} else if (mode === 2 || mode === 3) {
|
|
339
|
+
if (height === undefined) rows.length = 0;
|
|
340
|
+
else for (let r = 0; r < height; r++) blank(r, 0, width - 1);
|
|
341
|
+
}
|
|
342
|
+
break;
|
|
343
|
+
}
|
|
344
|
+
case "m":
|
|
345
|
+
sgr(params);
|
|
346
|
+
return; // SGR leaves a deferred wrap as it is
|
|
347
|
+
case "s":
|
|
348
|
+
saved = { row, col, style };
|
|
349
|
+
break;
|
|
350
|
+
case "u":
|
|
351
|
+
({ row, col, style } = saved);
|
|
352
|
+
break;
|
|
353
|
+
default:
|
|
354
|
+
return; // unknown: ignored, and the cursor untouched
|
|
355
|
+
}
|
|
356
|
+
pending = false;
|
|
357
|
+
};
|
|
358
|
+
|
|
359
|
+
const control = (code: number): void => {
|
|
360
|
+
switch (code) {
|
|
361
|
+
case 0x0d:
|
|
362
|
+
col = 0;
|
|
363
|
+
pending = false;
|
|
364
|
+
return;
|
|
365
|
+
case 0x0a:
|
|
366
|
+
case 0x0b:
|
|
367
|
+
case 0x0c:
|
|
368
|
+
linefeed();
|
|
369
|
+
if (crlf) col = 0;
|
|
370
|
+
pending = false;
|
|
371
|
+
return;
|
|
372
|
+
case 0x08:
|
|
373
|
+
col = Math.max(0, col - 1);
|
|
374
|
+
pending = false;
|
|
375
|
+
return;
|
|
376
|
+
case 0x09:
|
|
377
|
+
col = Math.min(width - 1, (Math.floor(col / 8) + 1) * 8);
|
|
378
|
+
pending = false;
|
|
379
|
+
return;
|
|
380
|
+
default:
|
|
381
|
+
return; // BEL and the other controls show nothing
|
|
382
|
+
}
|
|
383
|
+
};
|
|
384
|
+
|
|
385
|
+
const feed = (data: string): void => {
|
|
386
|
+
for (let i = 0; i < data.length; i++) {
|
|
387
|
+
const ch = data.charAt(i);
|
|
388
|
+
const code = data.charCodeAt(i);
|
|
389
|
+
switch (state) {
|
|
390
|
+
case "ground":
|
|
391
|
+
if (code === 0x1b) {
|
|
392
|
+
flush();
|
|
393
|
+
state = "escape";
|
|
394
|
+
} else if (code < 0x20 || code === 0x7f) {
|
|
395
|
+
flush();
|
|
396
|
+
control(code);
|
|
397
|
+
} else text += ch;
|
|
398
|
+
break;
|
|
399
|
+
case "escape":
|
|
400
|
+
if (code === 0x5b) {
|
|
401
|
+
state = "csi";
|
|
402
|
+
seq = "";
|
|
403
|
+
} else if (ch === "]" || ch === "P" || ch === "X" || ch === "^" || ch === "_") state = "string";
|
|
404
|
+
else if (code >= 0x20 && code <= 0x2f) seq += ch;
|
|
405
|
+
else if (code >= 0x30 && code <= 0x7e) {
|
|
406
|
+
if (seq === "" && ch === "7") saved = { row, col, style };
|
|
407
|
+
else if (seq === "" && ch === "8") ({ row, col, style } = saved);
|
|
408
|
+
seq = "";
|
|
409
|
+
state = "ground";
|
|
410
|
+
} else if (code !== 0x1b) {
|
|
411
|
+
seq = "";
|
|
412
|
+
state = "ground";
|
|
413
|
+
i--;
|
|
414
|
+
}
|
|
415
|
+
break;
|
|
416
|
+
case "csi":
|
|
417
|
+
if (code >= 0x20 && code <= 0x3f) seq += ch;
|
|
418
|
+
else if (code >= 0x40 && code <= 0x7e) {
|
|
419
|
+
csi(seq, ch);
|
|
420
|
+
seq = "";
|
|
421
|
+
state = "ground";
|
|
422
|
+
} else if (code === 0x1b) {
|
|
423
|
+
seq = "";
|
|
424
|
+
state = "escape";
|
|
425
|
+
} else {
|
|
426
|
+
seq = "";
|
|
427
|
+
state = "ground";
|
|
428
|
+
if (code !== 0x18 && code !== 0x1a) i--;
|
|
429
|
+
}
|
|
430
|
+
break;
|
|
431
|
+
case "string":
|
|
432
|
+
if (code === 0x07) state = "ground";
|
|
433
|
+
else if (code === 0x1b) state = "string-escape";
|
|
434
|
+
break;
|
|
435
|
+
case "string-escape":
|
|
436
|
+
seq = "";
|
|
437
|
+
state = code === 0x5c ? "ground" : "escape";
|
|
438
|
+
if (code !== 0x5c) i--;
|
|
439
|
+
break;
|
|
440
|
+
default:
|
|
441
|
+
absurd(state);
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
flush();
|
|
445
|
+
};
|
|
446
|
+
|
|
447
|
+
const visibleCells = (l: readonly Cell[]): readonly Cell[] => l.filter((c) => c.width !== 0);
|
|
448
|
+
const dropTrailingEmpty = <T>(ls: readonly T[], empty: (l: T) => boolean): readonly T[] => {
|
|
449
|
+
let end = ls.length;
|
|
450
|
+
for (let last = ls[end - 1]; last !== undefined && empty(last); last = ls[end - 1]) end--;
|
|
451
|
+
return ls.slice(0, end);
|
|
452
|
+
};
|
|
453
|
+
const lines = (): readonly string[] =>
|
|
454
|
+
dropTrailingEmpty(
|
|
455
|
+
rows.map((l) =>
|
|
456
|
+
visibleCells(l)
|
|
457
|
+
.map((c) => c.text)
|
|
458
|
+
.join("")
|
|
459
|
+
.replace(/ +$/, ""),
|
|
460
|
+
),
|
|
461
|
+
(l) => l === "",
|
|
462
|
+
);
|
|
463
|
+
|
|
464
|
+
return {
|
|
465
|
+
width,
|
|
466
|
+
height,
|
|
467
|
+
write(data: string | Uint8Array): void {
|
|
468
|
+
feed(typeof data === "string" ? data : decoder.decode(data, { stream: true }));
|
|
469
|
+
},
|
|
470
|
+
lines,
|
|
471
|
+
text(): string {
|
|
472
|
+
return lines().join("\n");
|
|
473
|
+
},
|
|
474
|
+
styled(): readonly (readonly Run[])[] {
|
|
475
|
+
const out = rows.map((l) => {
|
|
476
|
+
const cells = visibleCells(l);
|
|
477
|
+
let end = cells.length;
|
|
478
|
+
while (end > 0 && cells[end - 1]?.text === " " && sameStyle(cells[end - 1]?.style ?? PLAIN, PLAIN)) end--;
|
|
479
|
+
const runs: Run[] = [];
|
|
480
|
+
for (const c of cells.slice(0, end)) {
|
|
481
|
+
const last = runs[runs.length - 1];
|
|
482
|
+
if (last !== undefined && sameStyle(last.style, c.style)) runs[runs.length - 1] = { text: last.text + c.text, style: last.style };
|
|
483
|
+
else runs.push({ text: c.text, style: c.style });
|
|
484
|
+
}
|
|
485
|
+
return runs;
|
|
486
|
+
});
|
|
487
|
+
return dropTrailingEmpty(out, (l) => l.length === 0);
|
|
488
|
+
},
|
|
489
|
+
cell(r: number, c: number): Cell | undefined {
|
|
490
|
+
if (r < 0 || c < 0 || c >= width || (height !== undefined && r >= height)) return undefined;
|
|
491
|
+
return rows[r]?.[c] ?? BLANK;
|
|
492
|
+
},
|
|
493
|
+
cursor(): Cursor {
|
|
494
|
+
return { row, col, visible };
|
|
495
|
+
},
|
|
496
|
+
};
|
|
497
|
+
}
|
package/src/width.ts
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
// Spec: 0001-terminal FR-004
|
|
2
|
+
/**
|
|
3
|
+
* Display width: how many columns of a terminal a text takes, and a text cut to a number of columns (commons 0006-signals FR-023). An
|
|
4
|
+
* escape sequence takes none and is never split; a grapheme (what a person sees as one character, found with `Intl.Segmenter`) is never
|
|
5
|
+
* split either; a wide character or an emoji takes two columns.
|
|
6
|
+
*
|
|
7
|
+
* The width of a grapheme is an approximation of what terminals do (as `wcwidth` and the `string-width` package approximate it):
|
|
8
|
+
* - a control character, a combining mark, a format character (such as the zero-width joiner) or a variation selector alone: 0;
|
|
9
|
+
* - an emoji: 2 when it is shown as an emoji, which is when its first code point has the `Emoji_Presentation` property (✅ ❌ 👉), when
|
|
10
|
+
* it carries the emoji variation selector U+FE0F (⏭️ ⏹️ ⚠️, keycaps such as 1️⃣), or when it is a zero-width-joiner sequence (one glyph
|
|
11
|
+
* of two columns, however many code points it joins); the text variation selector U+FE0E makes it 1;
|
|
12
|
+
* - an East Asian Wide or Fullwidth character (CJK ideographs, kana, Hangul syllables, fullwidth forms): 2, by the ranges in `WIDE`,
|
|
13
|
+
* which follow Unicode's `EastAsianWidth.txt` in blocks rather than code point by code point (JavaScript has no property escape for it);
|
|
14
|
+
* - anything else: 1. Ambiguous-width characters (Greek, box drawing) count 1, as a terminal in a Western locale shows them.
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* ```ts
|
|
18
|
+
* import { cutToWidth, displayWidth } from "./width.ts";
|
|
19
|
+
* displayWidth("✅ 测试"); // 7
|
|
20
|
+
* cutToWidth("✅ 测试", 6); // "✅ 测"
|
|
21
|
+
* cutToWidth("\u001b[31mfailed badly\u001b[0m", 7, "…"); // "\u001b[31mfailed…\u001b[0m"
|
|
22
|
+
* ```
|
|
23
|
+
*
|
|
24
|
+
* @module
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
const ESC = String.fromCharCode(0x1b);
|
|
28
|
+
const BEL = String.fromCharCode(0x07);
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* An escape sequence: a control sequence (CSI, even one cut off at the end of the text), a string sequence (OSC, DCS, SOS, PM, APC) up
|
|
32
|
+
* to its terminator (BEL or ESC \) or the end, another escape (`ESC 7`, `ESC ( B`), or a lone ESC.
|
|
33
|
+
*/
|
|
34
|
+
const ESCAPE = new RegExp(`${ESC}(?:\\[[0-?]*[ -/]*[@-~]?|[\\]PX^_][^${BEL}${ESC}]*(?:${BEL}|${ESC}\\\\)?|[ -/]*[0-~]|)`, "g");
|
|
35
|
+
|
|
36
|
+
/** A piece of a text: an escape sequence, or a run of text between them. */
|
|
37
|
+
export type Token = { readonly kind: "escape"; readonly text: string } | { readonly kind: "text"; readonly text: string };
|
|
38
|
+
|
|
39
|
+
/** A text split into its escape sequences and the runs of text between them, in order; joined, the pieces are the text again. */
|
|
40
|
+
export function tokens(text: string): readonly Token[] {
|
|
41
|
+
const out: Token[] = [];
|
|
42
|
+
let last = 0;
|
|
43
|
+
for (const m of text.matchAll(ESCAPE)) {
|
|
44
|
+
if (m.index > last) out.push({ kind: "text", text: text.slice(last, m.index) });
|
|
45
|
+
out.push({ kind: "escape", text: m[0] });
|
|
46
|
+
last = m.index + m[0].length;
|
|
47
|
+
}
|
|
48
|
+
if (last < text.length) out.push({ kind: "text", text: text.slice(last) });
|
|
49
|
+
return out;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
|
|
53
|
+
|
|
54
|
+
/** The graphemes of a text with no escape sequence, in order (extended grapheme clusters, by `Intl.Segmenter`). */
|
|
55
|
+
export function graphemes(text: string): readonly string[] {
|
|
56
|
+
return Array.from(segmenter.segment(text), (s) => s.segment);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** East Asian Wide and Fullwidth ranges (inclusive), by block; emoji are told apart by their own properties. */
|
|
60
|
+
const WIDE: readonly (readonly [number, number])[] = [
|
|
61
|
+
[0x1100, 0x115f], // Hangul Jamo, leading consonants
|
|
62
|
+
[0x2329, 0x232a], // angle brackets
|
|
63
|
+
[0x2e80, 0x303e], // CJK radicals, Kangxi radicals, ideographic description, CJK symbols and punctuation
|
|
64
|
+
[0x3041, 0x33ff], // Hiragana, Katakana, Bopomofo, Hangul compatibility Jamo, Kanbun, CJK strokes, enclosed CJK, CJK compatibility
|
|
65
|
+
[0x3400, 0x4dbf], // CJK extension A
|
|
66
|
+
[0x4e00, 0x9fff], // CJK unified ideographs
|
|
67
|
+
[0xa000, 0xa4cf], // Yi
|
|
68
|
+
[0xa960, 0xa97f], // Hangul Jamo extended A
|
|
69
|
+
[0xac00, 0xd7a3], // Hangul syllables
|
|
70
|
+
[0xf900, 0xfaff], // CJK compatibility ideographs
|
|
71
|
+
[0xfe10, 0xfe19], // vertical forms
|
|
72
|
+
[0xfe30, 0xfe6f], // CJK compatibility forms, small form variants
|
|
73
|
+
[0xff00, 0xff60], // fullwidth forms
|
|
74
|
+
[0xffe0, 0xffe6], // fullwidth signs
|
|
75
|
+
[0x16fe0, 0x16fe4], // ideographic symbols
|
|
76
|
+
[0x17000, 0x18cff], // Tangut, Khitan
|
|
77
|
+
[0x1b000, 0x1b2ff], // kana supplement and extensions, Nushu
|
|
78
|
+
[0x1f200, 0x1f2ff], // enclosed ideographic supplement
|
|
79
|
+
[0x20000, 0x2fffd], // CJK extensions B to F, compatibility supplement
|
|
80
|
+
[0x30000, 0x3fffd], // CJK extensions G and H
|
|
81
|
+
];
|
|
82
|
+
|
|
83
|
+
const isWide = (cp: number): boolean => WIDE.some(([lo, hi]) => cp >= lo && cp <= hi);
|
|
84
|
+
const isControl = (cp: number): boolean => cp < 0x20 || (cp >= 0x7f && cp < 0xa0);
|
|
85
|
+
const ZERO = /^[\p{Mn}\p{Me}\p{Cf}\u{fe00}-\u{fe0f}]+$/u;
|
|
86
|
+
const PRESENTATION = /^\p{Emoji_Presentation}/u;
|
|
87
|
+
const PICTOGRAPHIC = /\p{Extended_Pictographic}/u;
|
|
88
|
+
const EMOJI = /\p{Emoji}/u;
|
|
89
|
+
|
|
90
|
+
/** The columns one grapheme takes: 0, 1 or 2 (see the module's rules). */
|
|
91
|
+
export function graphemeWidth(grapheme: string): 0 | 1 | 2 {
|
|
92
|
+
const cp = grapheme.codePointAt(0);
|
|
93
|
+
if (cp === undefined || isControl(cp) || ZERO.test(grapheme)) return 0;
|
|
94
|
+
if (grapheme.includes("\u{fe0e}")) return 1;
|
|
95
|
+
if (PRESENTATION.test(grapheme)) return 2;
|
|
96
|
+
if (grapheme.includes("\u{fe0f}") && EMOJI.test(grapheme)) return 2;
|
|
97
|
+
if (grapheme.includes("\u{200d}") && PICTOGRAPHIC.test(grapheme)) return 2;
|
|
98
|
+
return isWide(cp) ? 2 : 1;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** The columns a text takes on a terminal: its graphemes' widths summed; escape sequences take none. */
|
|
102
|
+
export function displayWidth(text: string): number {
|
|
103
|
+
let w = 0;
|
|
104
|
+
for (const t of tokens(text)) if (t.kind === "text") for (const g of graphemes(t.text)) w += graphemeWidth(g);
|
|
105
|
+
return w;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** A text split in two at a number of columns. */
|
|
109
|
+
export type Split = {
|
|
110
|
+
/** The longest beginning that takes at most the columns asked for, with every escape sequence before the cut. */
|
|
111
|
+
readonly head: string;
|
|
112
|
+
/** The rest: `head + tail` is the text. */
|
|
113
|
+
readonly tail: string;
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* A text split where it reaches `width` columns, between two graphemes or escape sequences, never inside one: a wide character that would
|
|
118
|
+
* cross the edge goes to the tail. Escape sequences up to the first grapheme that does not fit stay in the head.
|
|
119
|
+
*/
|
|
120
|
+
export function splitAtWidth(text: string, width: number): Split {
|
|
121
|
+
let used = 0;
|
|
122
|
+
let at = 0;
|
|
123
|
+
for (const t of tokens(text)) {
|
|
124
|
+
if (t.kind === "escape") {
|
|
125
|
+
at += t.text.length;
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
for (const g of graphemes(t.text)) {
|
|
129
|
+
const w = graphemeWidth(g);
|
|
130
|
+
if (used + w > width) return { head: text.slice(0, at), tail: text.slice(at) };
|
|
131
|
+
used += w;
|
|
132
|
+
at += g.length;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return { head: text, tail: "" };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const SGR = new RegExp(`^${ESC}\\[([0-9;:]*)m$`);
|
|
139
|
+
|
|
140
|
+
/** The parameters of an SGR sequence (`ESC [ ... m`), or undefined for another sequence. */
|
|
141
|
+
export function sgrParams(escape: string): readonly number[] | undefined {
|
|
142
|
+
const m = SGR.exec(escape);
|
|
143
|
+
if (m === null) return undefined;
|
|
144
|
+
return (m[1] ?? "").split(/[;:]/).map((p) => (p === "" ? 0 : Number(p)));
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Whether, after these escape sequences, a style set by SGR is still on: something other than a reset came after the last reset. */
|
|
148
|
+
function styleOpen(escapes: readonly string[]): boolean {
|
|
149
|
+
let open = false;
|
|
150
|
+
for (const e of escapes) {
|
|
151
|
+
const params = sgrParams(e) ?? [];
|
|
152
|
+
for (let i = 0; i < params.length; i++) {
|
|
153
|
+
const p = params[i];
|
|
154
|
+
if (p === 0) open = false;
|
|
155
|
+
else {
|
|
156
|
+
open = true;
|
|
157
|
+
// 38, 48 and 58 take a colour: 5;n or 2;r;g;b.
|
|
158
|
+
if (p === 38 || p === 48 || p === 58) i += params[i + 1] === 5 ? 2 : params[i + 1] === 2 ? 4 : 0;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
return open;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** The SGR sequence that turns every style off. */
|
|
166
|
+
export const RESET = `${ESC}[0m`;
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* A text cut to at most `width` columns. A text that fits is returned as it is. Otherwise it is cut between graphemes so that it and the
|
|
170
|
+
* `ellipsis` (none by default; "…" is the usual one) fit; the escape sequences before the cut are kept, those after are dropped, and where a
|
|
171
|
+
* colour or another style was still on at the cut, the result ends with a reset so that the style does not run on. An ellipsis wider than
|
|
172
|
+
* `width` is left out.
|
|
173
|
+
*/
|
|
174
|
+
export function cutToWidth(text: string, width: number, ellipsis = ""): string {
|
|
175
|
+
if (displayWidth(text) <= width) return text;
|
|
176
|
+
const room = width - displayWidth(ellipsis);
|
|
177
|
+
const mark = room >= 0 ? ellipsis : "";
|
|
178
|
+
const { head } = splitAtWidth(text, room >= 0 ? room : width);
|
|
179
|
+
const escapes = tokens(head).flatMap((t) => (t.kind === "escape" ? [t.text] : []));
|
|
180
|
+
return head + mark + (styleOpen(escapes) ? RESET : "");
|
|
181
|
+
}
|