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

terminalOutput.ts

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