Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

terminalOutput.ts

1,377 lines48.4 KB

1import { eastAsianWidth } from "get-east-asian-width";
2​
3/** Server/client folds must agree: only the last LIVE_LINES are cursor-addressable, with no wrapping.
4 * SGR resets at line boundaries for safe tail cuts; unfinished escapes carry through pending. */
5export interface TerminalOutputState {
6 /** Fixed lines followed by the live window; contains only SGR escapes. */
7 readonly text: string;
8 readonly truncated: boolean;
9 /** An unfinished escape sequence or high surrogate awaiting the next chunk. */
10 readonly pending: string;
11 readonly screen: TerminalScreen;
13​
14/** Canonical SGR parameters; empty means default style. */
15interface Run {
16 readonly pen: string;
17 readonly text: string;
19type Line = ReadonlyArray<Run>;
20​
21interface TerminalScreen {
22 /** Scrolled-out lines, each ending in newline, as head + tail. Only the tail grows, so a cut
23 * usually slices the head instead of copying all scrollback on every chunk. */
24 readonly settled: readonly [head: string, tail: string];
25 /** Never empty. */
26 readonly lines: ReadonlyArray<Line>;
27 readonly row: number;
28 readonly col: number;
29 readonly pen: string;
30 readonly saved: { readonly row: number; readonly col: number; readonly pen?: string } | null;
32​
33export const EMPTY_TERMINAL_OUTPUT: TerminalOutputState = {
34 text: "",
35 truncated: false,
36 pending: "",
37 screen: { settled: ["", ""], lines: [[]], row: 0, col: 0, pen: "", saved: null },
38};
39​
40/** Default command tail, in UTF-16 code units. */
41export const TERMINAL_OUTPUT_TAIL_CHARS = 64 * 1024;
42​
43const LIVE_LINES = 64;
44​
45const MAX_PENDING_ESCAPE = 64;
46​
47const ESC = "\u001b";
48​
49function sgr(pen: string): string {
50 return pen === "" ? `${ESC}[0m` : `${ESC}[0;${pen}m`;
52​
53// Lines stay immutable after a feed, so their measured lengths can be cached.
54const lineLengths = new WeakMap<Line, number>();
55​
56function lineLength(line: Line): number {
57 const cached = lineLengths.get(line);
58 if (cached !== undefined) return cached;
59 let length = 0;
60 for (const run of line) length += run.text.length;
61 lineLengths.set(line, length);
62 return length;
64​
65const lineWidths = new WeakMap<Line, number>();
66const ZERO_WIDTH = /[\p{Mark}\p{Default_Ignorable_Code_Point}]/u;
67const ASCII = /^[\x00-\x7f]*$/u;
68const LEADING_MARKS = /^[\p{Mark}\p{Default_Ignorable_Code_Point}]*/u;
69​
70const DETACHED_MARK = /[\p{Mark}\p{Default_Ignorable_Code_Point}\uDC00-\uDFFF]/u;
71const EMOJI_MODIFIER = /\p{Emoji_Modifier}/u;
72const EMOJI_MODIFIER_BASE = /\p{Emoji_Modifier_Base}/u;
73const VARIATION_SELECTOR = /\p{Variation_Selector}/u;
74const REGIONAL_INDICATOR = /\p{Regional_Indicator}/u;
75​
76/** The emoji base a modifier after `preceding` would attach to, past any variation selectors. */
77function emojiBaseBefore(preceding: Iterable<string>): string | undefined {
78 for (const character of preceding) {
79 if (!VARIATION_SELECTOR.test(character)) {
80 return EMOJI_MODIFIER_BASE.test(character) ? character : undefined;
81 }
82 }
83 return undefined;
85​
86function isDetachedTailStart(
87 character: string,
88 precedingCharacters: () => Iterable<string>,
89): boolean {
90 if (DETACHED_MARK.test(character)) return true;
91 if (EMOJI_MODIFIER.test(character)) return emojiBaseBefore(precedingCharacters()) !== undefined;
92 if (REGIONAL_INDICATOR.test(character)) {
93 let odd = false;
94 for (const preceding of precedingCharacters()) {
95 if (!REGIONAL_INDICATOR.test(preceding)) break;
96 odd = !odd;
97 }
98 return odd;
99 }
100 return false;
102​
103function* previousCharacters(text: string, end: number): Generator<string> {
104 while (end > 0) {
105 if (text[end - 1] === "m") {
106 let start = end - 1;
107 while (start > 0 && /[0-9;:]/u.test(text[start - 1]!)) start -= 1;
108 if (start >= 2 && text.startsWith(`${ESC}[`, start - 2)) {
109 end = start - 2;
110 continue;
111 }
112 }
113 const pair = end >= 2 ? text.codePointAt(end - 2)! : 0;
114 const start = end - (pair > 0xffff ? 2 : 1);
115 yield text.slice(start, end);
116 end = start;
117 }
119​
120function* previousRunCharacters(runs: Line, index: number, end: number): Generator<string> {
121 for (let previous = index; previous >= 0; previous -= 1) {
122 const { text } = runs[previous]!;
123 yield* previousCharacters(text, previous === index ? end : text.length);
124 }
126​
127function characterWidth(character: string): number {
128 return ZERO_WIDTH.test(character) ? 0 : eastAsianWidth(character.codePointAt(0)!);
130​
131function textWidth(text: string): number {
132 if (ASCII.test(text)) return text.length;
133 let width = 0;
134 for (const character of text) width += characterWidth(character);
135 return width;
137​
138function lineWidth(line: Line): number {
139 const cached = lineWidths.get(line);
140 if (cached !== undefined) return cached;
141 let width = 0;
142 for (const run of line) width += textWidth(run.text);
143 lineWidths.set(line, width);
144 return width;
146​
147// Strip oldest styles to bound work on color-per-character output.
148const MAX_LINE_RUNS = 2_048;
149​
150function sliceLine(
151 line: Line,
152 start: number,
153 end: number,
154 includeLeadingMarks = start === 0 && end > 0,
155): Array<Run> {
156 const out: Array<Run> = [];
157 let col = 0;
158 let base = 0;
159 let baseEnd = 0;
160 for (const run of line) {
161 if (ASCII.test(run.text)) {
162 const runEnd = col + run.text.length;
163 if (runEnd > start && col < end) {
164 pushRun(out, {
165 pen: run.pen,
166 text: run.text.slice(Math.max(0, start - col), Math.min(run.text.length, end - col)),
167 });
168 }
169 base = runEnd - 1;
170 baseEnd = runEnd;
171 col = runEnd;
172 continue;
173 }
174 let text = "";
175 for (const character of run.text) {
176 const width = characterWidth(character);
177 if (width > 0) {
178 base = col;
179 baseEnd = col + width;
180 }
181 if (width === 0) {
182 const keep =
183 baseEnd === 0 ? includeLeadingMarks : base >= start && base < end && baseEnd <= end;
184 if (keep) text += character;
185 } else if (col < end && col + width > start) {
186 // Overwriting either half of a wide glyph clears that glyph's other cell.
187 text +=
188 col >= start && col + width <= end
189 ? character
190 : " ".repeat(Math.min(end, col + width) - Math.max(start, col));
191 }
192 col += width;
193 }
194 pushRun(out, { pen: run.pen, text });
195 }
196 return out;
198​
199function pushRun(runs: Array<Run>, run: Run): void {
200 if (run.text.length === 0) return;
201 const last = runs.at(-1);
202 if (last !== undefined && last.pen === run.pen) {
203 runs[runs.length - 1] = { pen: last.pen, text: last.text + run.text };
204 } else {
205 runs.push(run);
206 }
208​
209/** Mutates only lines owned by this feed. */
210function trimLineStart(runs: Array<Run>, count: number): number {
211 const width = lineWidth(runs);
212 const length = lineLength(runs);
213 let removedWidth = 0;
214 let removedUnits = 0;
215 let dropped = 0;
216 let remaining = count;
217 while (dropped < runs.length) {
218 const run = runs[dropped]!;
219 let cut = Math.min(remaining, run.text.length);
220 // A retained tail must start at a complete character, with no detached marks.
221 while (cut < run.text.length) {
222 const character = String.fromCodePoint(run.text.codePointAt(cut)!);
223 if (!isDetachedTailStart(character, () => previousRunCharacters(runs, dropped, cut))) break;
224 cut += character.length;
225 }
226 removedWidth += textWidth(run.text.slice(0, cut));
227 removedUnits += cut;
228 remaining = Math.max(0, remaining - cut);
229 if (cut < run.text.length) {
230 runs[dropped] = { pen: run.pen, text: run.text.slice(cut) };
231 break;
232 }
233 dropped += 1;
234 }
235 if (dropped > 0) runs.splice(0, dropped);
236 lineLengths.set(runs, length - removedUnits);
237 lineWidths.set(runs, width - removedWidth);
238 return removedWidth;
240​
241function writeLine(line: Line, col: number, text: string, pen: string): Line {
242 const length = lineWidth(line);
243 if (col === length) {
244 const runs = line.slice();
245 pushRun(runs, { pen, text });
246 lineWidths.set(runs, length + textWidth(text));
247 lineLengths.set(runs, lineLength(line) + text.length);
248 return runs;
249 }
250 const runs: Array<Run> = [];
251 for (const run of sliceLine(line, 0, Math.min(col, length), true)) pushRun(runs, run);
252 if (col > length) pushRun(runs, { pen: "", text: " ".repeat(col - length) });
253 pushRun(runs, { pen, text });
254 for (const run of sliceLine(line, col + textWidth(text), length, false)) pushRun(runs, run);
255 return runs;
257​
258/** Erase in line: 0 cursor to end, 1 start to cursor, 2 whole line. */
259function eraseLine(line: Line, col: number, mode: number): Line {
260 const length = lineWidth(line);
261 if (mode === 0) return sliceLine(line, 0, col);
262 if (mode === 1) {
263 const runs: Array<Run> = [];
264 pushRun(runs, { pen: "", text: " ".repeat(Math.min(col + 1, length)) });
265 for (const run of sliceLine(line, col + 1, length)) pushRun(runs, run);
266 return runs;
267 }
268 return mode === 2 ? [] : line;
270​
271function serializeLine(line: Line): string {
272 let out = "";
273 let current = "";
274 for (const run of line) {
275 if (run.pen !== current) {
276 out += sgr(run.pen);
277 current = run.pen;
278 }
279 out += run.text;
280 }
281 return current === "" ? out : out + sgr("");
283​
284interface Attributes {
285 bold: boolean;
286 dim: boolean;
287 italic: boolean;
288 underline: boolean;
289 strike: boolean;
290 inverse: boolean;
291 fg: string;
292 bg: string;
294​
295function parsePen(pen: string): Attributes {
296 const attributes: Attributes = {
297 bold: false,
298 dim: false,
299 italic: false,
300 underline: false,
301 strike: false,
302 inverse: false,
303 fg: "",
304 bg: "",
305 };
306 if (pen !== "") applySgr(attributes, pen.split(";").map(Number));
307 return attributes;
309​
310function formatPen(attributes: Attributes): string {
311 const parts: Array<string> = [];
312 if (attributes.bold) parts.push("1");
313 if (attributes.dim) parts.push("2");
314 if (attributes.italic) parts.push("3");
315 if (attributes.underline) parts.push("4");
316 if (attributes.inverse) parts.push("7");
317 if (attributes.strike) parts.push("9");
318 if (attributes.fg !== "") parts.push(attributes.fg);
319 if (attributes.bg !== "") parts.push(attributes.bg);
320 return parts.join(";");
322​
323/** Reads 5;n or 2;r;g;b colors; returns the code and next index. */
324function extendedColor(
325 code: number,
326 params: ReadonlyArray<number>,
327 index: number,
328): [string | undefined, number] {
329 const mode = params[index + 1];
330 if (mode === 5) {
331 const value = params[index + 2];
332 return value === undefined || value > 255
333 ? [undefined, index + 3]
334 : [`${code};5;${value}`, index + 3];
335 }
336 if (mode === 2) {
337 const [r, g, b] = [params[index + 2], params[index + 3], params[index + 4]];
338 if (r === undefined || g === undefined || b === undefined) return [undefined, index + 5];
339 return [`${code};2;${r & 255};${g & 255};${b & 255}`, index + 5];
340 }
341 return [undefined, index + 2];
343​
344function applySgr(attributes: Attributes, params: ReadonlyArray<number>): void {
345 if (params.length === 0) params = [0];
346 for (let index = 0; index < params.length;) {
347 const code = params[index]!;
348 if (code === 0 || Number.isNaN(code)) {
349 Object.assign(attributes, parsePen(""));
350 } else if (code === 1) attributes.bold = true;
351 else if (code === 2) attributes.dim = true;
352 else if (code === 3) attributes.italic = true;
353 else if (code === 4) attributes.underline = true;
354 else if (code === 7) attributes.inverse = true;
355 else if (code === 9) attributes.strike = true;
356 else if (code === 22) attributes.bold = attributes.dim = false;
357 else if (code === 23) attributes.italic = false;
358 else if (code === 24) attributes.underline = false;
359 else if (code === 27) attributes.inverse = false;
360 else if (code === 29) attributes.strike = false;
361 else if ((code >= 30 && code <= 37) || (code >= 90 && code <= 97)) attributes.fg = String(code);
362 else if ((code >= 40 && code <= 47) || (code >= 100 && code <= 107))
363 attributes.bg = String(code);
364 else if (code === 39) attributes.fg = "";
365 else if (code === 49) attributes.bg = "";
366 else if (code === 38 || code === 48 || code === 58) {
367 // 58 (underline colour) is consumed but not kept: nothing renders it.
368 const [color, next] = extendedColor(code, params, index);
369 if (color !== undefined && code !== 58) attributes[code === 38 ? "fg" : "bg"] = color;
370 index = next;
371 continue;
372 }
373 index += 1;
374 }
376​
377const STRING_SEQUENCE_INTRODUCERS = new Set(["]", "P", "X", "_", "^"]);
378// C1 DCS, SOS, CSI, OSC, PM and APC, each equal to ESC followed by its code minus 0x40.
379const C1_INTRODUCERS = new Set([0x90, 0x98, 0x9b, 0x9d, 0x9e, 0x9f]);
380​
381/** Length of a complete escape sequence whose introducer follows `index`, or -1 if unfinished. */
382function escapeLength(input: string, index: number, next = input[index + 1]): number {
383 if (next === undefined) return -1;
384 // A second ESC restarts the sequence.
385 if (next === ESC) return 1;
386 if (next === "[") {
387 for (let cursor = index + 2; cursor < input.length; cursor += 1) {
388 const code = input.charCodeAt(cursor);
389 // Like xterm.js, a new ESC cancels an unfinished CSI so the next sequence parses intact.
390 if (code === 0x1b) return cursor - index;
391 // CAN and SUB cancel the CSI and are consumed.
392 if (code === 0x18 || code === 0x1a) return cursor - index + 1;
393 if (code >= 0x40 && code <= 0x7e) return cursor - index + 1;
394 // Like xterm.js, a non-ASCII code point aborts the CSI and is consumed, both halves of a surrogate pair.
395 if (code >= 0x80) {
396 if (code >= 0xd800 && code <= 0xdbff) {
397 if (cursor + 1 >= input.length) return -1;
398 const low = input.charCodeAt(cursor + 1);
399 if (low >= 0xdc00 && low <= 0xdfff) return cursor - index + 2;
400 }
401 return cursor - index + 1;
402 }
403 }
404 return -1;
405 }
406 if (STRING_SEQUENCE_INTRODUCERS.has(next)) {
407 // ST (and BEL for OSC) ends string sequences; also stop at newlines so stray binary introducers cannot hide later output.
408 for (let cursor = index + 2; cursor < input.length; cursor += 1) {
409 if (next === "]" && input[cursor] === "\u0007") return cursor - index + 1;
410 if ("\u0018\u001a\u009c".includes(input[cursor]!)) return cursor - index + 1;
411 if (input[cursor] === "\n") return cursor - index;
412 // Like xterm.js, an ESC that does not start ST ends the string and begins the next sequence.
413 if (input[cursor] === ESC) {
414 if (cursor + 1 >= input.length) return -1;
415 return input[cursor + 1] === "\\" ? cursor - index + 2 : cursor - index;
416 }
417 }
418 return -1;
419 }
420 // ECMA-35: any intermediate bytes (0x20-0x2F, e.g. charset designations, DECALN) precede one final byte.
421 // NUL padding between them is skipped, as xterm.js does.
422 let cursor = index + 1;
423 while (cursor < input.length) {
424 const code = input.charCodeAt(cursor);
425 if (code !== 0x00 && (code < 0x20 || code > 0x2f)) break;
426 cursor += 1;
427 }
428 if (cursor >= input.length) return -1;
429 // After intermediates, a control or ESC is not a final byte; end before it so it is still processed.
430 const final = input.charCodeAt(cursor);
431 if (cursor > index + 1 && (final < 0x30 || final > 0x7e)) return cursor - index;
432 if (final >= 0xd800 && final <= 0xdbff) {
433 if (cursor + 1 >= input.length) return -1;
434 const low = input.charCodeAt(cursor + 1);
435 if (low >= 0xdc00 && low <= 0xdfff) return cursor - index + 2;
436 }
437 return cursor - index + 1;
439​
440const penTransitions = new Map<string, string>();
441​
442// Colon color sub-parameters carry an optional color-space id absent from the semicolon form.
443function csiParams(params: string): Array<number> {
444 const numbers: Array<number> = [];
445 // After a semicolon-form 38/48/58 the next part is its mode, then that many
446 // colour values; tracking them keeps a value from being read as a code.
447 let pending: "code" | "mode" | number = "code";
448 for (const part of params.split(";")) {
449 const sub = part.split(":").map(Number);
450 const head = sub[0]!;
451 if (typeof pending === "number") {
452 numbers.push(head);
453 pending = pending > 1 ? pending - 1 : "code";
454 continue;
455 }
456 if (pending === "mode") {
457 pending = "code";
458 if (sub.length === 1) {
459 numbers.push(head);
460 if (head === 5 || head === 2) pending = head === 5 ? 1 : 3;
461 continue;
462 }
463 // xterm also takes the mode's fields after colons (`38;2:255:0:0`).
464 if (head === 2 && sub.length >= 5) sub.splice(1, 1);
465 numbers.push(...sub.slice(0, head === 5 ? 2 : head === 2 ? 4 : 1));
466 continue;
467 }
468 if (sub.length === 1) {
469 numbers.push(head);
470 if (head === 38 || head === 48 || head === 58) pending = "mode";
471 continue;
472 }
473 if (head !== 38 && head !== 48 && head !== 58) {
474 // Other sub-parameters pick a style variant (`4:3` curly underline); keep
475 // only the head, except that `4:0` turns underline off.
476 numbers.push(head === 4 && sub[1] === 0 ? 24 : head);
477 continue;
478 }
479 if (sub[1] === 2 && sub.length >= 6) sub.splice(2, 1);
480 // The group is one parameter, so fields past its mode's length must not
481 // leak out as SGR codes of their own. Indexed colour has no colour-space id.
482 numbers.push(...sub.slice(0, sub[1] === 5 ? 3 : sub[1] === 2 ? 5 : 2));
483 }
484 return numbers;
486​
487class Terminal {
488 settledHead: string;
489 settledTail: string;
490 lines: Array<Line>;
491 row: number;
492 col: number;
493 pen: string;
494 saved: { row: number; col: number; pen?: string } | null;
495 /** Output was discarded on purpose (scrollback cleared or window over budget). */
496 dropped = false;
497 readonly maxChars: number;
498 /** Lines created during this feed, which it may extend in place. */
499 private readonly owned = new WeakSet<Line>();
500​
501 constructor(screen: TerminalScreen, maxChars: number) {
502 this.maxChars = maxChars;
503 [this.settledHead, this.settledTail] = screen.settled;
504 this.lines = screen.lines.slice();
505 this.row = screen.row;
506 this.col = screen.col;
507 this.pen = screen.pen;
508 this.saved = screen.saved;
509 }
510​
511 write(text: string): void {
512 let line = this.lines[this.row]!;
513 const length = lineWidth(line);
514 const width = textWidth(text);
515 if (this.col === length && this.owned.has(line)) {
516 const units = lineLength(line);
517 pushRun(line as Array<Run>, { pen: this.pen, text });
518 lineWidths.set(line, length + width);
519 lineLengths.set(line, units + text.length);
520 } else {
521 line = writeLine(line, this.col, text, this.pen);
522 this.owned.add(line);
523 }
524 this.col += width;
525 if (line.length > MAX_LINE_RUNS) {
526 // Flatten old runs so later trimming stays cheap.
527 const keep = line.length - MAX_LINE_RUNS / 8;
528 const plain = line
529 .slice(0, keep)
530 .map((run) => run.text)
531 .join("");
532 const columns = lineWidth(line);
533 const units = lineLength(line);
534 line = [{ pen: "", text: plain }, ...line.slice(keep)];
535 lineWidths.set(line, columns);
536 lineLengths.set(line, units);
537 this.owned.add(line);
538 }
539 // The output budget is UTF-16 units; cursor positions are terminal columns.
540 const current = lineLength(line);
541 if (current > this.maxChars) {
542 const removed = trimLineStart(line as Array<Run>, current - this.maxChars);
543 this.dropped = true;
544 this.col = Math.max(0, this.col - removed);
545 if (this.saved !== null && this.saved.row === this.row) {
546 this.saved = { ...this.saved, col: Math.max(0, this.saved.col - removed) };
547 }
548 }
549 this.lines[this.row] = line;
550 }
551​
552 newline(): void {
553 this.row += 1;
554 this.col = 0;
555 if (this.row === this.lines.length) this.lines.push([]);
556 while (this.lines.length > LIVE_LINES) this.scrollOut();
557 }
558​
559 scrollOut(): number {
560 const line = this.lines.shift()!;
561 this.settle(line);
562 this.row -= 1;
563 if (this.saved !== null) this.saved = { ...this.saved, row: Math.max(0, this.saved.row - 1) };
564 return lineLength(line);
565 }
566​
567 settle(line: Line): void {
568 this.settledTail += `${serializeLine(line)}\n`;
569 if (this.settledHead.length + this.settledTail.length > 2 * this.maxChars) {
570 [this.settledHead, this.settledTail = ""] = terminalOutputTailParts(
571 [this.settledHead, this.settledTail],
572 this.maxChars,
573 ).parts;
574 this.dropped = true;
575 }
576 }
577​
578 moveTo(row: number, col: number): void {
579 this.row = Math.max(0, Math.min(this.lines.length - 1, row));
580 // A huge column (ESC[999999999C) would otherwise pad a line past any string limit.
581 this.col = Math.max(0, Math.min(2 * TERMINAL_OUTPUT_TAIL_CHARS, col));
582 }
583​
584 csi(params: string, final: string): void {
585 if (!/^[\d;:]*$/u.test(params) || (final !== "m" && params.includes(":"))) return;
586 if (final === "m") {
587 const key = `${this.pen}|${params}`;
588 let pen = penTransitions.get(key);
589 if (pen === undefined) {
590 const attributes = parsePen(this.pen);
591 applySgr(attributes, params === "" ? [] : csiParams(params));
592 pen = formatPen(attributes);
593 if (penTransitions.size >= 512) penTransitions.clear();
594 penTransitions.set(key, pen);
595 }
596 this.pen = pen;
597 return;
598 }
599 const numbers = params === "" ? [] : csiParams(params);
600 const count = Math.max(1, numbers[0] || 1);
601 switch (final) {
602 case "A":
603 return this.moveTo(this.row - count, this.col);
604 case "B":
605 return this.moveTo(this.row + count, this.col);
606 case "C":
607 return this.moveTo(this.row, this.col + count);
608 case "D":
609 return this.moveTo(this.row, this.col - count);
610 case "E":
611 return this.moveTo(this.row + count, 0);
612 case "F":
613 return this.moveTo(this.row - count, 0);
614 case "G":
615 return this.moveTo(this.row, count - 1);
616 case "H":
617 case "f":
618 // Rows count from the top of the window: there is no fixed screen height.
619 return this.moveTo(count - 1, Math.max(1, numbers[1] || 1) - 1);
620 case "K":
621 this.lines[this.row] = eraseLine(this.lines[this.row]!, this.col, numbers[0] ?? 0);
622 return;
623 case "J": {
624 const mode = numbers[0] ?? 0;
625 if (mode === 0) {
626 this.lines[this.row] = eraseLine(this.lines[this.row]!, this.col, 0);
627 this.lines.length = this.row + 1;
628 } else if (mode === 1) {
629 for (let row = 0; row < this.row; row += 1) this.lines[row] = [];
630 this.lines[this.row] = eraseLine(this.lines[this.row]!, this.col, 1);
631 } else if (mode === 3) {
632 if (this.settledHead !== "" || this.settledTail !== "") this.dropped = true;
633 this.settledHead = "";
634 this.settledTail = "";
635 } else if (mode === 2) {
636 this.lines = [[]];
637 this.row = 0;
638 this.col = 0;
639 }
640 return;
641 }
642 case "s":
643 this.saved = { row: this.row, col: this.col };
644 return;
645 case "u":
646 if (this.saved !== null) this.moveTo(this.saved.row, this.saved.col);
647 return;
648 default:
649 }
650 }
651​
652 escape(sequence: string): void {
653 if (sequence[1] === "[") {
654 this.csi(sequence.slice(2, -1), sequence.at(-1)!);
655 } else if (sequence === `${ESC}7`) {
656 this.saved = { row: this.row, col: this.col, pen: this.pen };
657 } else if (sequence === `${ESC}8`) {
658 if (this.saved !== null) {
659 this.moveTo(this.saved.row, this.saved.col);
660 if (this.saved.pen !== undefined) this.pen = this.saved.pen;
661 }
662 } else if (sequence === `${ESC}M`) {
663 this.moveTo(this.row - 1, this.col);
664 }
665 }
666​
667 private control(code: number): boolean {
668 if (code === 0x0a) this.newline();
669 else if (code === 0x0d) this.col = 0;
670 else if (code === 0x08) this.col = Math.max(0, this.col - 1);
671 else return code === 0x07 || code === 0x00; // BEL and NUL padding have no screen effect.
672 return true;
673 }
674​
675 /** Applies `input`; returns the unfinished escape left at its end. */
676 feed(input: string): string {
677 let printable = 0;
678 const flush = (end: number) => {
679 if (end > printable) this.write(input.slice(printable, end));
680 };
681 for (let index = 0; index < input.length; index += 1) {
682 const code = input.charCodeAt(index);
683 if (code === 0x09 || (code >= 0x20 && code !== 0x7f && (code < 0x80 || code > 0x9f))) {
684 continue;
685 }
686 flush(index);
687 printable = index + 1;
688 const c1 = C1_INTRODUCERS.has(code) ? String.fromCharCode(code - 0x40) : undefined;
689 if (code === 0x1b || c1 !== undefined) {
690 // A C1 introducer stands in for ESC plus its 7-bit introducer, so parse it as that pair.
691 let start = c1 === undefined ? index + 1 : index;
692 while (c1 === undefined && this.control(input.charCodeAt(start))) start += 1;
693 const length = escapeLength(input, start - 1, c1);
694 const end = length === -1 ? -1 : start - 1 + length;
695 const rest = input.slice(
696 c1 === undefined ? start : start + 1,
697 end === -1 ? input.length : end,
698 );
699 let sequence = ESC + (c1 ?? "") + rest;
700 if (sequence[1] === "[") {
701 // Apply controls now and leave them out of the CSI, including any pending fragment.
702 sequence = sequence.replace(/[\0\u0007\b\n\r]/gu, (control) => {
703 this.control(control.charCodeAt(0));
704 return "";
705 });
706 } else if (!STRING_SEQUENCE_INTRODUCERS.has(sequence[1] ?? "")) {
707 // Drop NUL padding before the pending limit so split padding cannot expose the final byte.
708 sequence = sequence.replaceAll("\0", "");
709 }
710 if (end === -1) {
711 if (sequence.length <= MAX_PENDING_ESCAPE) return sequence;
712 // Retain the introducer and possible ST prefix so long string payloads stay hidden until termination.
713 if (STRING_SEQUENCE_INTRODUCERS.has(sequence[1]!)) {
714 return sequence.slice(0, 2) + (sequence.endsWith(ESC) ? ESC : "");
715 }
716 return "";
717 }
718 this.escape(sequence);
719 index = end - 1;
720 printable = end;
721 } else {
722 this.control(code);
723 }
724 }
725 const last = input.charCodeAt(input.length - 1);
726 if (last >= 0xd800 && last <= 0xdbff) {
727 flush(input.length - 1);
728 return input.slice(-1);
729 }
730 flush(input.length);
731 return "";
732 }
734​
735/** The active style at `index` of `text` and where a cut there may safely start. */
736function styleAt(text: string, index: number): { readonly start: number; readonly prefix: string } {
737 const lineStart = text.lastIndexOf("\n", index - 1) + 1;
738 let prefix = "";
739 let cursor = lineStart;
740 while (cursor < index) {
741 const found = text.indexOf(`${ESC}[`, cursor);
742 if (found === -1 || found >= index) break;
743 const end = text.indexOf("m", found);
744 if (end === -1) break;
745 if (end >= index) return { start: end + 1, prefix: text.slice(found, end + 1) };
746 prefix = text.slice(found, end + 1);
747 cursor = end + 1;
748 }
749 return { start: index, prefix: prefix === sgr("") ? "" : prefix };
751​
752/** Keeps the last `maxChars`, preferring to start on a fresh line. */
753export function terminalOutputTail(
754 text: string,
755 maxChars: number,
756): { readonly text: string; readonly truncated: boolean } {
757 if (text.length <= maxChars) return { text, truncated: false };
758 let start = text.length - maxChars;
759 if (text[start - 1] === "\n") return { text: text.slice(start), truncated: true };
760 const newline = text.indexOf("\n", start);
761 // Drop the partial first line unless that would discard most of the tail.
762 if (newline !== -1 && newline - start < maxChars / 4) {
763 return { text: text.slice(newline + 1), truncated: true };
764 }
765 // Cutting inside a line: never split an escape, keep the colour in force, and skip
766 // detached marks and modifiers, and lone low surrogates.
767 const style = styleAt(text, start);
768 let prefix = style.prefix;
769 start = style.start;
770 while (start < text.length) {
771 if (text.startsWith(`${ESC}[`, start)) {
772 const end = text.indexOf("m", start + 2);
773 if (end === -1) break;
774 const seq = text.slice(start, end + 1);
775 prefix = seq === sgr("") ? "" : seq;
776 start = end + 1;
777 continue;
778 }
779 const character = String.fromCodePoint(text.codePointAt(start)!);
780 if (!isDetachedTailStart(character, () => previousCharacters(text, start))) break;
781 start += character.length;
782 }
783 return { text: start < text.length ? prefix + text.slice(start) : "", truncated: true };
785​
786/**
787 * terminalOutputTail of the parts' concatenation, kept as parts. V8 copies a concatenated string
788 * the first time it is searched or sliced, so a newline cut slices only the part it lands in.
789 */
790function terminalOutputTailParts(
791 parts: readonly [string, ...Array<string>],
792 maxChars: number,
793): { readonly parts: readonly [string, ...Array<string>]; readonly truncated: boolean } {
794 let total = 0;
795 for (const part of parts) total += part.length;
796 if (total <= maxChars) return { parts, truncated: false };
797 const start = total - maxChars;
798 let previousEndedWithNewline = false;
799 let offset = 0;
800 for (let index = 0; index < parts.length; index += 1) {
801 const part = parts[index]!;
802 if (offset + part.length > start) {
803 const localStart = start - offset;
804 if (
805 localStart >= 0 &&
806 (localStart === 0 ? previousEndedWithNewline : part[localStart - 1] === "\n")
807 ) {
808 return { parts: [part.slice(localStart), ...parts.slice(index + 1)], truncated: true };
809 }
810 const newline = part.indexOf("\n", Math.max(0, localStart));
811 if (newline !== -1) {
812 if (offset + newline - start >= maxChars / 4) break;
813 return { parts: [part.slice(newline + 1), ...parts.slice(index + 1)], truncated: true };
814 }
815 }
816 if (part.length > 0) previousEndedWithNewline = part.endsWith("\n");
817 offset += part.length;
818 }
819 return { parts: [terminalOutputTail(parts.join(""), maxChars).text], truncated: true };
821​
822export function appendTerminalOutput(
823 state: TerminalOutputState,
824 chunk: string,
825 maxChars: number = TERMINAL_OUTPUT_TAIL_CHARS,
826): TerminalOutputState {
827 const input = state.pending + chunk;
828 if (input.length === 0) return state;
829 const terminal = new Terminal(state.screen, maxChars);
830 const pending = terminal.feed(input);
831 let truncated = state.truncated;
832 let windowChars = terminal.lines.reduce((total, line) => total + lineLength(line), 0);
833 while (windowChars > maxChars && terminal.row > 0) windowChars -= terminal.scrollOut();
834 // Lines below a cursor that moved up can't scroll out; they keep only their ends.
835 if (windowChars > maxChars) {
836 let budget = maxChars;
837 for (let row = 0; row <= terminal.row; row += 1) budget -= lineLength(terminal.lines[row]!);
838 for (let row = terminal.row + 1; row < terminal.lines.length; row += 1) {
839 const line = terminal.lines[row]!;
840 const length = lineLength(line);
841 const keep = Math.max(0, Math.min(length, budget));
842 if (keep < length) {
843 truncated = true;
844 const runs = line.slice();
845 const removed = trimLineStart(runs, length - keep);
846 terminal.lines[row] = runs;
847 if (terminal.saved !== null && terminal.saved.row === row) {
848 terminal.saved = {
849 ...terminal.saved,
850 col: Math.max(0, terminal.saved.col - removed),
851 };
852 }
853 }
854 budget -= lineLength(terminal.lines[row]!);
855 }
856 }
857 if (terminal.dropped) truncated = true;
858 const settled = terminalOutputTailParts([terminal.settledHead, terminal.settledTail], maxChars);
859 const window = terminal.lines.map(serializeLine).join("\n");
860 const tail = terminalOutputTailParts([...settled.parts, window], maxChars);
861 return {
862 text: tail.parts.reduce((text, part) => text + part, ""),
863 truncated: truncated || settled.truncated || tail.truncated,
864 pending,
865 screen: {
866 settled: [settled.parts[0], settled.parts[1] ?? ""],
867 lines: terminal.lines,
868 row: terminal.row,
869 col: terminal.col,
870 pen: terminal.pen,
871 saved: terminal.saved,
872 },
873 };
875​
876/** Rebuilds state from empty, including cursor/style/pending escapes, so later raw chunks fold identically. */
877export function terminalOutputResumeText(state: TerminalOutputState): string {
878 const { screen } = state;
879 const lastRow = screen.lines.length - 1;
880 // A full live window can hide retained scrollback from the display tail until the next redraw.
881 let replay = screen.settled.join("");
882 if (replay !== "" && lastRow < LIVE_LINES - 1) {
883 // Scroll the history out with blank rows, then clear them before replaying the live window.
884 replay += "\n".repeat(LIVE_LINES - 1) + `${ESC}[2J`;
885 }
886 replay += screen.lines.map(serializeLine).join("\n");
887 const up = (row: number) => lastRow - row;
888 const goTo = (row: number, col: number) =>
889 (up(row) > 0 ? `${ESC}[${up(row)}A` : "") + `${ESC}[${col + 1}G`;
890 let suffix = "";
891 let pen = "";
892 if (screen.saved !== null) {
893 const save = screen.saved.pen === undefined ? `${ESC}[s` : `${ESC}7`;
894 if (screen.saved.pen !== undefined && screen.saved.pen !== "") {
895 suffix += sgr(screen.saved.pen);
896 pen = screen.saved.pen;
897 }
898 if (screen.saved.row > lastRow) {
899 const extra = screen.saved.row - lastRow;
900 suffix +=
901 "\n".repeat(extra) +
902 `${ESC}[${screen.saved.col + 1}G${save}` +
903 `${ESC}[${extra}A${ESC}[${lineWidth(screen.lines[lastRow]!) + 2}G${ESC}[J`;
904 } else {
905 suffix += `${goTo(screen.saved.row, screen.saved.col)}${save}`;
906 if (up(screen.saved.row) > 0) suffix += `${ESC}[${up(screen.saved.row)}B`;
907 }
908 }
909 if (
910 screen.saved !== null ||
911 screen.row < lastRow ||
912 screen.col !== lineWidth(screen.lines[screen.row]!)
913 ) {
914 suffix += goTo(screen.row, screen.col);
915 }
916 if (screen.pen !== pen) suffix += sgr(screen.pen);
917 return replay + suffix + state.pending;
919​
920export function normalizeTerminalOutput(
921 text: string,
922 maxChars: number = TERMINAL_OUTPUT_TAIL_CHARS,
923): { readonly text: string; readonly truncated: boolean } {
924 const state = appendTerminalOutput(EMPTY_TERMINAL_OUTPUT, text, maxChars);
925 return { text: state.text, truncated: state.truncated };
927​
928export interface TerminalSpan {
929 readonly text: string;
930 readonly style: TerminalSpanStyle | null;
932​
933export interface TerminalSpanStyle {
934 /** CSS colours, already resolved against the palette. */
935 readonly color?: string;
936 readonly backgroundColor?: string;
937 readonly fontWeight?: "600";
938 readonly opacity?: number;
939 readonly fontStyle?: "italic";
940 readonly textDecorationLine?: "underline" | "line-through" | "underline line-through";
942​
943export const TERMINAL_PALETTES = {
944 dark: [
945 "#3b4048",
946 "#f47067",
947 "#57ab5a",
948 "#c69026",
949 "#539bf5",
950 "#b083f0",
951 "#39c5cf",
952 "#adbac7",
953 "#768390",
954 "#ff938a",
955 "#6bc46d",
956 "#daaa3f",
957 "#6cb6ff",
958 "#dcbdfb",
959 "#56d4dd",
960 "#cdd9e5",
961 ],
962 light: [
963 "#24292f",
964 "#cf222e",
965 "#116329",
966 "#7d4e00",
967 "#0550ae",
968 "#8250df",
969 "#1b7c83",
970 "#6e7781",
971 "#57606a",
972 "#a40e26",
973 "#1a7f37",
974 "#633c01",
975 "#0969da",
976 "#6639ba",
977 "#3192aa",
978 "#8c959f",
979 ],
980} as const;
981​
982function xtermColor(index: number, palette: ReadonlyArray<string>): string {
983 if (index < 16) return palette[index]!;
984 if (index >= 232) {
985 const level = 8 + (index - 232) * 10;
986 return `rgb(${level},${level},${level})`;
987 }
988 const cube = index - 16;
989 const channel = (value: number) => (value === 0 ? 0 : 55 + value * 40);
990 return `rgb(${channel(Math.floor(cube / 36))},${channel(Math.floor(cube / 6) % 6)},${channel(cube % 6)})`;
992​
993function resolveColor(
994 code: string,
995 base: number,
996 palette: ReadonlyArray<string>,
997): string | undefined {
998 const parts = code.split(";").map(Number);
999 const head = parts[0]!;
1000 if (head === base + 8) {
1001 if (parts[1] === 5) return xtermColor(parts[2]!, palette);
1002 return `rgb(${parts[2]},${parts[3]},${parts[4]})`;
1004 if (head >= base && head <= base + 7) return palette[head - base];
1005 if (head >= base + 60 && head <= base + 67) return palette[head - base - 52];
1006 return undefined;
1008​
1009type Rgb = readonly [number, number, number];
1010​
1011function parseCssColor(color: string): Rgb | undefined {
1012 if (color.startsWith("#") && color.length === 7) {
1013 return [1, 3, 5].map((offset) =>
1014 Number.parseInt(color.slice(offset, offset + 2), 16),
1015 ) as unknown as Rgb;
1017 const match = /^rgb\((\d+),(\d+),(\d+)\)$/u.exec(color);
1018 return match === null ? undefined : [Number(match[1]), Number(match[2]), Number(match[3])];
1020​
1021function luminance([r, g, b]: Rgb): number {
1022 const channel = (value: number) => {
1023 const scaled = value / 255;
1024 return scaled <= 0.03928 ? scaled / 12.92 : ((scaled + 0.055) / 1.055) ** 2.4;
1025 };
1026 return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b);
1028​
1029function contrastRatio(a: Rgb, b: Rgb): number {
1030 const [first, second] = [luminance(a), luminance(b)];
1031 return (Math.max(first, second) + 0.05) / (Math.min(first, second) + 0.05);
1033​
1034function spanStyle(pen: string, palette: ReadonlyArray<string>): TerminalSpanStyle | null {
1035 if (pen === "") return null;
1036 const attributes = parsePen(pen);
1037 let color = attributes.fg === "" ? undefined : resolveColor(attributes.fg, 30, palette);
1038 let backgroundColor = attributes.bg === "" ? undefined : resolveColor(attributes.bg, 40, palette);
1039 if (attributes.inverse) {
1040 [color, backgroundColor] = [backgroundColor, color ?? palette[7]];
1042 // Badges like "PASS" on green assume a terminal's own palette; keep their text readable.
1043 if (backgroundColor !== undefined) {
1044 const background = parseCssColor(backgroundColor);
1045 const foreground = color === undefined ? undefined : parseCssColor(color);
1046 if (
1047 background !== undefined &&
1048 (foreground === undefined || contrastRatio(foreground, background) < 3)
1049 ) {
1050 color = luminance(background) > 0.3 ? "#1f2328" : "#ffffff";
1053 const textDecorationLine = attributes.underline
1054 ? attributes.strike
1055 ? "underline line-through"
1056 : "underline"
1057 : attributes.strike
1058 ? "line-through"
1059 : undefined;
1060 return {
1061 ...(color === undefined ? {} : { color }),
1062 ...(backgroundColor === undefined ? {} : { backgroundColor }),
1063 ...(attributes.bold ? { fontWeight: "600" } : {}),
1064 ...(attributes.dim ? { opacity: 0.65 } : {}),
1065 ...(attributes.italic ? { fontStyle: "italic" } : {}),
1066 ...(textDecorationLine === undefined ? {} : { textDecorationLine }),
1067 };
1069​
1070/** Caps styled spans at maxSpans, then emits one plain remainder to bound DOM/native nodes. */
1071export function terminalOutputSpans(
1072 text: string,
1073 palette: ReadonlyArray<string>,
1074 maxSpans = 2_000,
1075): ReadonlyArray<TerminalSpan> {
1076 const spans: Array<TerminalSpan> = [];
1077 const styles = new Map<string, TerminalSpanStyle | null>();
1078 let pen = "";
1079 let cursor = 0;
1080 const push = (end: number) => {
1081 if (end <= cursor) return;
1082 let style = styles.get(pen);
1083 if (style === undefined) {
1084 style = spanStyle(pen, palette);
1085 styles.set(pen, style);
1087 spans.push({ text: text.slice(cursor, end), style });
1088 };
1089 while (cursor < text.length) {
1090 const escape = text.indexOf(`${ESC}[`, cursor);
1091 if (escape === -1 || spans.length >= maxSpans) break;
1092 push(escape);
1093 const end = text.indexOf("m", escape);
1094 if (end === -1) break;
1095 const params = text.slice(escape + 2, end);
1096 pen = params === "0" ? "" : params.replace(/^0;/u, "");
1097 cursor = end + 1;
1099 if (cursor < text.length) {
1100 if (spans.length >= maxSpans) {
1101 spans.push({ text: terminalOutputPlainText(text.slice(cursor)), style: null });
1102 } else {
1103 push(text.length);
1106 return spans;
1108​
1109// Colours and the cursor, erase and mode controls a saved transcript cannot replay.
1110const CSI_PATTERN = new RegExp(`${ESC}\\[[0-?]*[ -/]*[@-~]`, "gu");
1111​
1112export function terminalOutputPlainText(text: string): string {
1113 return text.replace(CSI_PATTERN, "");
1115​
1116// tqdm redraws a progress bar after a carriage return; JupyterLab shows only what the last
1117// redraws leave on the line. Walking the frames from the last keeps this linear.
1118function lastFrame(line: string): string {
1119 const frames = line.split("\r");
1120 let row = frames.pop()!;
1121 if (frames.length === 0) return row;
1122 // A tab can skip over cells left by an earlier frame.
1123 if (line.includes("\t")) return replaySavedLine(line, "redraw") ?? row;
1124 let width = textWidth(row);
1125 // Marks before a line's first glyph survive every later repaint, as in appendTerminalOutput.
1126 let leadingMarks = "";
1127 for (const frame of frames.reverse()) {
1128 leadingMarks = LEADING_MARKS.exec(frame)![0] + leadingMarks;
1129 const frameWidth = textWidth(frame);
1130 if (frameWidth <= width) continue;
1131 row += sliceLine([{ pen: "", text: frame }], width, frameWidth, false)[0]?.text ?? "";
1132 width = frameWidth;
1134 return leadingMarks + row;
1136​
1137export function terminalOutputCollapseRedraws(text: string): string {
1138 return /\r(?!\n)/.test(text)
1139 ? text.replaceAll("\r\n", "\n").split("\n").map(lastFrame).join("\n")
1140 : text;
1142​
1143const SAVED_CSI = /(?:\u001b\0*\[|\u009b)([0-?\0]*)([ -/][ -/\0]*)?([@-~])/uy;
1144const SAVED_STRING_END = /\u001b(?:\0*\\)?|\u009c|[\u0018\u001a]/gu;
1145const SAVED_OSC_END = /\u001b(?:\0*\\)?|\u009c|[\u0007\u0018\u001a]/gu;
1146const SAVED_TAB_WIDTH = 8;
1147​
1148/** Replays saved horizontal edits in original columns, without a terminal scrollback limit.
1149 * Undefined when erases would revisit too many columns, so hostile input stays linear. */
1150export function terminalOutputReplayLineEdits(line: string): string | undefined {
1151 return replaySavedLine(line, "edits");
1153​
1154function replaySavedLine(line: string, mode: "edits" | "redraw"): string | undefined {
1155 const replayEdits = mode === "edits";
1156 const columnLimit = line.length + (line.split("\t").length - 1) * (SAVED_TAB_WIDTH - 1);
1157 // Zero is blank, one continues a wide glyph, and other values encode code points.
1158 let columns = new Uint32Array(0);
1159 const prefixes = new Map<number, string>();
1160 const suffixes = new Map<number, string>();
1161 let base: number | undefined;
1162 let wrotePrefix = false;
1163 let length = 0;
1164 let col = 0;
1165 let savedCol: number | undefined;
1166 // Columns in the cleared prefix are blank except for the span written since the erase.
1167 let clearedPrefix = 0;
1168 let dirtyStart = Infinity;
1169 let dirtyEnd = 0;
1170 let plainParts: string[] | undefined = replayEdits ? [] : undefined;
1171 let plainStart = 0;
1172 let eraseBudget = 4 * columnLimit;
1173​
1174 const skipControl = (start: number, end: number) => {
1175 if (start > plainStart) plainParts?.push(line.slice(plainStart, start));
1176 plainStart = end;
1177 };
1178​
1179 const moveTo = (next: number) => {
1180 base = undefined;
1181 wrotePrefix = false;
1182 col = next;
1183 };
1184​
1185 const clearBoundary = (at: number) => {
1186 if (columns[at] !== 1) return;
1187 suffixes.delete(at - 1);
1188 columns[at - 1] = 0;
1189 columns[at] = 0;
1190 };
1191​
1192 const clearRange = (start: number, end: number): boolean => {
1193 if (start >= end) return true;
1194 eraseBudget -= end - start;
1195 if (eraseBudget < 0) return false;
1196 columns.fill(0, start, end);
1197 if (prefixes.size > 0 || suffixes.size > 0) {
1198 for (let at = start; at < end; at += 1) {
1199 prefixes.delete(at);
1200 suffixes.delete(at);
1203 return true;
1204 };
1205​
1206 const erase = (mode: number): boolean => {
1207 plainParts = undefined;
1208 base = undefined;
1209 wrotePrefix = false;
1210 if (mode === 2) {
1211 eraseBudget -= length;
1212 if (eraseBudget < 0) return false;
1213 columns.fill(0, 0, length);
1214 length = 0;
1215 clearedPrefix = 0;
1216 dirtyStart = Infinity;
1217 dirtyEnd = 0;
1218 prefixes.clear();
1219 suffixes.clear();
1220 return true;
1222 const boundary = Math.min(length, mode === 0 ? col : col + 1);
1223 if (mode === 0) {
1224 prefixes.delete(length);
1225 clearBoundary(boundary);
1226 if (!clearRange(boundary, length)) return false;
1227 length = boundary;
1228 clearedPrefix = Math.min(clearedPrefix, boundary);
1229 dirtyEnd = Math.min(dirtyEnd, boundary);
1230 } else {
1231 clearBoundary(boundary);
1232 if (!clearRange(dirtyStart, Math.min(dirtyEnd, boundary))) return false;
1233 if (!clearRange(clearedPrefix, boundary)) return false;
1234 clearedPrefix = Math.max(clearedPrefix, boundary);
1235 dirtyStart = Math.max(dirtyStart, boundary);
1237 if (dirtyStart >= dirtyEnd) {
1238 dirtyStart = Infinity;
1239 dirtyEnd = 0;
1241 return true;
1242 };
1243​
1244 for (let index = 0; index < line.length;) {
1245 const point = line.codePointAt(index)!;
1246 if (point === 0x1b || (point >= 0x80 && point <= 0x9f)) {
1247 const start = index;
1248 SAVED_CSI.lastIndex = index;
1249 const csi = SAVED_CSI.exec(line);
1250 if (csi) {
1251 index = SAVED_CSI.lastIndex;
1252 skipControl(start, index);
1253 if (!replayEdits) continue;
1254 const [, rawParams, intermediates, command] = csi;
1255 const params = rawParams!.replaceAll("\0", "");
1256 if (intermediates || !/^[\d;]*$/u.test(params)) continue;
1257 const [first, second] = params.split(";", 2).map(Number);
1258 const distance = first || 1;
1259 if (command === "K" && (first === 0 || first === 1 || first === 2)) {
1260 if (!erase(first)) return undefined;
1261 } else if (command === "s") savedCol = col;
1262 else if (command === "u" && savedCol !== undefined) moveTo(savedCol);
1263 else if (command === "E" || command === "F") moveTo(0);
1264 else if ("CDGHf".includes(command!)) {
1265 const next =
1266 command === "C"
1267 ? col + distance
1268 : command === "D"
1269 ? col - distance
1270 : command === "G"
1271 ? distance - 1
1272 : (second || 1) - 1;
1273 // Keep existing columns addressable without expanding short lines far beyond their input.
1274 moveTo(Math.max(0, Math.min(Math.max(length, col, columnLimit), next)));
1276 continue;
1278 const esc = point === 0x1b;
1279 let introducerIndex = index + 1;
1280 while (esc && line[introducerIndex] === "\0") introducerIndex += 1;
1281 const introducer = line[introducerIndex] ?? "";
1282 const osc = point === 0x9d || (esc && introducer === "]");
1283 if (
1284 osc ||
1285 point === 0x90 ||
1286 point === 0x98 ||
1287 point === 0x9e ||
1288 point === 0x9f ||
1289 (esc && STRING_SEQUENCE_INTRODUCERS.has(introducer))
1290 ) {
1291 const end = osc ? SAVED_OSC_END : SAVED_STRING_END;
1292 end.lastIndex = esc ? introducerIndex + 1 : index + 1;
1293 const terminator = end.exec(line);
1294 // A bare ESC interrupts the string and begins the next command.
1295 index =
1296 terminator?.[0] === ESC ? terminator.index : terminator ? end.lastIndex : line.length;
1297 } else if (esc) {
1298 if (replayEdits && introducer === "7") savedCol = col;
1299 else if (replayEdits && introducer === "8" && savedCol !== undefined) moveTo(savedCol);
1300 const escapeStart = introducerIndex - 1;
1301 const size = escapeLength(line, escapeStart);
1302 index = size === -1 ? line.length : escapeStart + size;
1303 } else index += 1;
1304 skipControl(start, index);
1305 continue;
1307 index += point > 0xffff ? 2 : 1;
1308 if (point === 0x09) {
1309 moveTo(col + SAVED_TAB_WIDTH - (col % SAVED_TAB_WIDTH));
1310 continue;
1312 if (point < 0x20) {
1313 base = undefined;
1314 wrotePrefix = false;
1315 if (point === 0x0d) col = 0;
1316 else if (point === 0x08) col = Math.max(0, col - 1);
1317 continue;
1319 if (point === 0x7f) continue;
1320 const character = String.fromCodePoint(point);
1321 const width = characterWidth(character);
1322 if (col < clearedPrefix) {
1323 dirtyStart = Math.min(dirtyStart, col);
1324 dirtyEnd = Math.max(dirtyEnd, Math.min(clearedPrefix, col + Math.max(1, width)));
1326 if (width === 0) {
1327 if (base === undefined) {
1328 prefixes.set(col, (prefixes.get(col) ?? "") + character);
1329 wrotePrefix = true;
1330 length = Math.max(length, col);
1331 } else suffixes.set(base, (suffixes.get(base) ?? "") + character);
1332 continue;
1334 const end = col + width;
1335 if (end > columns.length) {
1336 const grown = new Uint32Array(Math.max(end, columns.length * 2, 32));
1337 grown.set(columns);
1338 columns = grown;
1340 clearBoundary(col);
1341 if (columns[end] === 1) columns[end] = 0;
1342 if (!wrotePrefix) prefixes.delete(col);
1343 suffixes.delete(col);
1344 columns[col] = point + 2;
1345 if (width === 2) {
1346 columns[col + 1] = 1;
1347 prefixes.delete(col + 1);
1348 suffixes.delete(col + 1);
1350 base = col;
1351 wrotePrefix = false;
1352 col = end;
1353 length = Math.max(length, end);
1355​
1356 // An apparent erase inside a control string does not activate horizontal replay.
1357 if (plainParts) {
1358 plainParts.push(line.slice(plainStart));
1359 return plainParts.join("");
1361​
1362 const parts: string[] = [];
1363 let text = "";
1364 for (let at = 0; at < length; at += 1) {
1365 const cell = columns[at] ?? 0;
1366 text +=
1367 (prefixes.get(at) ?? "") +
1368 (cell === 0 ? " " : cell === 1 ? "" : String.fromCodePoint(cell - 2)) +
1369 (suffixes.get(at) ?? "");
1370 if (text.length >= 4096) {
1371 parts.push(text);
1372 text = "";
1375 parts.push(text, prefixes.get(length) ?? "");
1376 return parts.join("");