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

terminalOutput.ts

1,312 lines45.3 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​
371/** Length of a complete escape sequence whose introducer follows `index`, or -1 if unfinished. */
372function escapeLength(input: string, index: number): number {
373 const next = input[index + 1];
374 if (next === undefined) return -1;
375 // A second ESC restarts the sequence.
376 if (next === ESC) return 1;
377 if (next === "[") {
378 for (let cursor = index + 2; cursor < input.length; cursor += 1) {
379 const code = input.charCodeAt(cursor);
380 // Like xterm.js, a new ESC cancels an unfinished CSI so the next sequence parses intact.
381 if (code === 0x1b) return cursor - index;
382 // CAN and SUB cancel the CSI and are consumed.
383 if (code === 0x18 || code === 0x1a) return cursor - index + 1;
384 if (code >= 0x40 && code <= 0x7e) return cursor - index + 1;
385 // Like xterm.js, a non-ASCII code point aborts the CSI and is consumed, both halves of a surrogate pair.
386 if (code >= 0x80) {
387 if (code >= 0xd800 && code <= 0xdbff) {
388 if (cursor + 1 >= input.length) return -1;
389 const low = input.charCodeAt(cursor + 1);
390 if (low >= 0xdc00 && low <= 0xdfff) return cursor - index + 2;
391 }
392 return cursor - index + 1;
393 }
394 }
395 return -1;
396 }
397 if (STRING_SEQUENCE_INTRODUCERS.has(next)) {
398 // ST (and BEL for OSC) ends string sequences; also stop at newlines so stray binary introducers cannot hide later output.
399 for (let cursor = index + 2; cursor < input.length; cursor += 1) {
400 if (next === "]" && input[cursor] === "\u0007") return cursor - index + 1;
401 if (input[cursor] === "\u0018" || input[cursor] === "\u001a") return cursor - index + 1;
402 if (input[cursor] === "\n") return cursor - index;
403 // Like xterm.js, an ESC that does not start ST ends the string and begins the next sequence.
404 if (input[cursor] === ESC) {
405 if (cursor + 1 >= input.length) return -1;
406 return input[cursor + 1] === "\\" ? cursor - index + 2 : cursor - index;
407 }
408 }
409 return -1;
410 }
411 // ECMA-35: any intermediate bytes (0x20-0x2F, e.g. charset designations, DECALN) precede one final byte.
412 let cursor = index + 1;
413 while (
414 cursor < input.length &&
415 input.charCodeAt(cursor) >= 0x20 &&
416 input.charCodeAt(cursor) <= 0x2f
417 ) {
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; // BEL has 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 if (code === 0x1b) {
681 let start = index + 1;
682 while (this.control(input.charCodeAt(start))) start += 1;
683 const length = escapeLength(input, start - 1);
684 const end = length === -1 ? -1 : start - 1 + length;
685 let sequence = ESC + input.slice(start, end === -1 ? input.length : end);
686 if (sequence[1] === "[") {
687 // Apply controls now and leave them out of the CSI, including any pending fragment.
688 sequence = sequence.replace(/[\u0007\b\n\r]/gu, (control) => {
689 this.control(control.charCodeAt(0));
690 return "";
691 });
692 }
693 if (end === -1) {
694 if (sequence.length <= MAX_PENDING_ESCAPE) return sequence;
695 // Retain the introducer and possible ST prefix so long string payloads stay hidden until termination.
696 if (STRING_SEQUENCE_INTRODUCERS.has(sequence[1]!)) {
697 return sequence.slice(0, 2) + (sequence.endsWith(ESC) ? ESC : "");
698 }
699 return "";
700 }
701 this.escape(sequence);
702 index = end - 1;
703 printable = end;
704 } else {
705 this.control(code);
706 }
707 }
708 const last = input.charCodeAt(input.length - 1);
709 if (last >= 0xd800 && last <= 0xdbff) {
710 flush(input.length - 1);
711 return input.slice(-1);
712 }
713 flush(input.length);
714 return "";
715 }
717​
718/** The active style at `index` of `text` and where a cut there may safely start. */
719function styleAt(text: string, index: number): { readonly start: number; readonly prefix: string } {
720 const lineStart = text.lastIndexOf("\n", index - 1) + 1;
721 let prefix = "";
722 let cursor = lineStart;
723 while (cursor < index) {
724 const found = text.indexOf(`${ESC}[`, cursor);
725 if (found === -1 || found >= index) break;
726 const end = text.indexOf("m", found);
727 if (end === -1) break;
728 if (end >= index) return { start: end + 1, prefix: text.slice(found, end + 1) };
729 prefix = text.slice(found, end + 1);
730 cursor = end + 1;
731 }
732 return { start: index, prefix: prefix === sgr("") ? "" : prefix };
734​
735/** Keeps the last `maxChars`, preferring to start on a fresh line. */
736export function terminalOutputTail(
737 text: string,
738 maxChars: number,
739): { readonly text: string; readonly truncated: boolean } {
740 if (text.length <= maxChars) return { text, truncated: false };
741 let start = text.length - maxChars;
742 if (text[start - 1] === "\n") return { text: text.slice(start), truncated: true };
743 const newline = text.indexOf("\n", start);
744 // Drop the partial first line unless that would discard most of the tail.
745 if (newline !== -1 && newline - start < maxChars / 4) {
746 return { text: text.slice(newline + 1), truncated: true };
747 }
748 // Cutting inside a line: never split an escape, keep the colour in force, and skip
749 // detached marks and modifiers, and lone low surrogates.
750 const style = styleAt(text, start);
751 let prefix = style.prefix;
752 start = style.start;
753 while (start < text.length) {
754 if (text.startsWith(`${ESC}[`, start)) {
755 const end = text.indexOf("m", start + 2);
756 if (end === -1) break;
757 const seq = text.slice(start, end + 1);
758 prefix = seq === sgr("") ? "" : seq;
759 start = end + 1;
760 continue;
761 }
762 const character = String.fromCodePoint(text.codePointAt(start)!);
763 if (!isDetachedTailStart(character, () => previousCharacters(text, start))) break;
764 start += character.length;
765 }
766 return { text: start < text.length ? prefix + text.slice(start) : "", truncated: true };
768​
769/**
770 * terminalOutputTail of the parts' concatenation, kept as parts. V8 copies a concatenated string
771 * the first time it is searched or sliced, so a newline cut slices only the part it lands in.
772 */
773function terminalOutputTailParts(
774 parts: readonly [string, ...Array<string>],
775 maxChars: number,
776): { readonly parts: readonly [string, ...Array<string>]; readonly truncated: boolean } {
777 let total = 0;
778 for (const part of parts) total += part.length;
779 if (total <= maxChars) return { parts, truncated: false };
780 const start = total - maxChars;
781 let previousEndedWithNewline = false;
782 let offset = 0;
783 for (let index = 0; index < parts.length; index += 1) {
784 const part = parts[index]!;
785 if (offset + part.length > start) {
786 const localStart = start - offset;
787 if (
788 localStart >= 0 &&
789 (localStart === 0 ? previousEndedWithNewline : part[localStart - 1] === "\n")
790 ) {
791 return { parts: [part.slice(localStart), ...parts.slice(index + 1)], truncated: true };
792 }
793 const newline = part.indexOf("\n", Math.max(0, localStart));
794 if (newline !== -1) {
795 if (offset + newline - start >= maxChars / 4) break;
796 return { parts: [part.slice(newline + 1), ...parts.slice(index + 1)], truncated: true };
797 }
798 }
799 if (part.length > 0) previousEndedWithNewline = part.endsWith("\n");
800 offset += part.length;
801 }
802 return { parts: [terminalOutputTail(parts.join(""), maxChars).text], truncated: true };
804​
805export function appendTerminalOutput(
806 state: TerminalOutputState,
807 chunk: string,
808 maxChars: number = TERMINAL_OUTPUT_TAIL_CHARS,
809): TerminalOutputState {
810 const input = state.pending + chunk;
811 if (input.length === 0) return state;
812 const terminal = new Terminal(state.screen, maxChars);
813 const pending = terminal.feed(input);
814 let truncated = state.truncated;
815 let windowChars = terminal.lines.reduce((total, line) => total + lineLength(line), 0);
816 while (windowChars > maxChars && terminal.row > 0) windowChars -= terminal.scrollOut();
817 // Lines below a cursor that moved up can't scroll out; they keep only their ends.
818 if (windowChars > maxChars) {
819 let budget = maxChars;
820 for (let row = 0; row <= terminal.row; row += 1) budget -= lineLength(terminal.lines[row]!);
821 for (let row = terminal.row + 1; row < terminal.lines.length; row += 1) {
822 const line = terminal.lines[row]!;
823 const length = lineLength(line);
824 const keep = Math.max(0, Math.min(length, budget));
825 if (keep < length) {
826 truncated = true;
827 const runs = line.slice();
828 const removed = trimLineStart(runs, length - keep);
829 terminal.lines[row] = runs;
830 if (terminal.saved !== null && terminal.saved.row === row) {
831 terminal.saved = {
832 ...terminal.saved,
833 col: Math.max(0, terminal.saved.col - removed),
834 };
835 }
836 }
837 budget -= lineLength(terminal.lines[row]!);
838 }
839 }
840 if (terminal.dropped) truncated = true;
841 const settled = terminalOutputTailParts([terminal.settledHead, terminal.settledTail], maxChars);
842 const window = terminal.lines.map(serializeLine).join("\n");
843 const tail = terminalOutputTailParts([...settled.parts, window], maxChars);
844 return {
845 text: tail.parts.reduce((text, part) => text + part, ""),
846 truncated: truncated || settled.truncated || tail.truncated,
847 pending,
848 screen: {
849 settled: [settled.parts[0], settled.parts[1] ?? ""],
850 lines: terminal.lines,
851 row: terminal.row,
852 col: terminal.col,
853 pen: terminal.pen,
854 saved: terminal.saved,
855 },
856 };
858​
859/** Rebuilds state from empty, including cursor/style/pending escapes, so later raw chunks fold identically. */
860export function terminalOutputResumeText(state: TerminalOutputState): string {
861 const { screen } = state;
862 const lastRow = screen.lines.length - 1;
863 // A full live window can hide retained scrollback from the display tail until the next redraw.
864 let replay = screen.settled.join("");
865 if (replay !== "" && lastRow < LIVE_LINES - 1) {
866 // Scroll the history out with blank rows, then clear them before replaying the live window.
867 replay += "\n".repeat(LIVE_LINES - 1) + `${ESC}[2J`;
868 }
869 replay += screen.lines.map(serializeLine).join("\n");
870 const up = (row: number) => lastRow - row;
871 const goTo = (row: number, col: number) =>
872 (up(row) > 0 ? `${ESC}[${up(row)}A` : "") + `${ESC}[${col + 1}G`;
873 let suffix = "";
874 let pen = "";
875 if (screen.saved !== null) {
876 const save = screen.saved.pen === undefined ? `${ESC}[s` : `${ESC}7`;
877 if (screen.saved.pen !== undefined && screen.saved.pen !== "") {
878 suffix += sgr(screen.saved.pen);
879 pen = screen.saved.pen;
880 }
881 if (screen.saved.row > lastRow) {
882 const extra = screen.saved.row - lastRow;
883 suffix +=
884 "\n".repeat(extra) +
885 `${ESC}[${screen.saved.col + 1}G${save}` +
886 `${ESC}[${extra}A${ESC}[${lineWidth(screen.lines[lastRow]!) + 2}G${ESC}[J`;
887 } else {
888 suffix += `${goTo(screen.saved.row, screen.saved.col)}${save}`;
889 if (up(screen.saved.row) > 0) suffix += `${ESC}[${up(screen.saved.row)}B`;
890 }
891 }
892 if (
893 screen.saved !== null ||
894 screen.row < lastRow ||
895 screen.col !== lineWidth(screen.lines[screen.row]!)
896 ) {
897 suffix += goTo(screen.row, screen.col);
898 }
899 if (screen.pen !== pen) suffix += sgr(screen.pen);
900 return replay + suffix + state.pending;
902​
903export function normalizeTerminalOutput(
904 text: string,
905 maxChars: number = TERMINAL_OUTPUT_TAIL_CHARS,
906): { readonly text: string; readonly truncated: boolean } {
907 const state = appendTerminalOutput(EMPTY_TERMINAL_OUTPUT, text, maxChars);
908 return { text: state.text, truncated: state.truncated };
910​
911export interface TerminalSpan {
912 readonly text: string;
913 readonly style: TerminalSpanStyle | null;
915​
916export interface TerminalSpanStyle {
917 /** CSS colours, already resolved against the palette. */
918 readonly color?: string;
919 readonly backgroundColor?: string;
920 readonly fontWeight?: "600";
921 readonly opacity?: number;
922 readonly fontStyle?: "italic";
923 readonly textDecorationLine?: "underline" | "line-through" | "underline line-through";
925​
926export const TERMINAL_PALETTES = {
927 dark: [
928 "#3b4048",
929 "#f47067",
930 "#57ab5a",
931 "#c69026",
932 "#539bf5",
933 "#b083f0",
934 "#39c5cf",
935 "#adbac7",
936 "#768390",
937 "#ff938a",
938 "#6bc46d",
939 "#daaa3f",
940 "#6cb6ff",
941 "#dcbdfb",
942 "#56d4dd",
943 "#cdd9e5",
944 ],
945 light: [
946 "#24292f",
947 "#cf222e",
948 "#116329",
949 "#7d4e00",
950 "#0550ae",
951 "#8250df",
952 "#1b7c83",
953 "#6e7781",
954 "#57606a",
955 "#a40e26",
956 "#1a7f37",
957 "#633c01",
958 "#0969da",
959 "#6639ba",
960 "#3192aa",
961 "#8c959f",
962 ],
963} as const;
964​
965function xtermColor(index: number, palette: ReadonlyArray<string>): string {
966 if (index < 16) return palette[index]!;
967 if (index >= 232) {
968 const level = 8 + (index - 232) * 10;
969 return `rgb(${level},${level},${level})`;
970 }
971 const cube = index - 16;
972 const channel = (value: number) => (value === 0 ? 0 : 55 + value * 40);
973 return `rgb(${channel(Math.floor(cube / 36))},${channel(Math.floor(cube / 6) % 6)},${channel(cube % 6)})`;
975​
976function resolveColor(
977 code: string,
978 base: number,
979 palette: ReadonlyArray<string>,
980): string | undefined {
981 const parts = code.split(";").map(Number);
982 const head = parts[0]!;
983 if (head === base + 8) {
984 if (parts[1] === 5) return xtermColor(parts[2]!, palette);
985 return `rgb(${parts[2]},${parts[3]},${parts[4]})`;
986 }
987 if (head >= base && head <= base + 7) return palette[head - base];
988 if (head >= base + 60 && head <= base + 67) return palette[head - base - 52];
989 return undefined;
991​
992type Rgb = readonly [number, number, number];
993​
994function parseCssColor(color: string): Rgb | undefined {
995 if (color.startsWith("#") && color.length === 7) {
996 return [1, 3, 5].map((offset) =>
997 Number.parseInt(color.slice(offset, offset + 2), 16),
998 ) as unknown as Rgb;
999 }
1000 const match = /^rgb\((\d+),(\d+),(\d+)\)$/u.exec(color);
1001 return match === null ? undefined : [Number(match[1]), Number(match[2]), Number(match[3])];
1003​
1004function luminance([r, g, b]: Rgb): number {
1005 const channel = (value: number) => {
1006 const scaled = value / 255;
1007 return scaled <= 0.03928 ? scaled / 12.92 : ((scaled + 0.055) / 1.055) ** 2.4;
1008 };
1009 return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b);
1011​
1012function contrastRatio(a: Rgb, b: Rgb): number {
1013 const [first, second] = [luminance(a), luminance(b)];
1014 return (Math.max(first, second) + 0.05) / (Math.min(first, second) + 0.05);
1016​
1017function spanStyle(pen: string, palette: ReadonlyArray<string>): TerminalSpanStyle | null {
1018 if (pen === "") return null;
1019 const attributes = parsePen(pen);
1020 let color = attributes.fg === "" ? undefined : resolveColor(attributes.fg, 30, palette);
1021 let backgroundColor = attributes.bg === "" ? undefined : resolveColor(attributes.bg, 40, palette);
1022 if (attributes.inverse) {
1023 [color, backgroundColor] = [backgroundColor, color ?? palette[7]];
1025 // Badges like "PASS" on green assume a terminal's own palette; keep their text readable.
1026 if (backgroundColor !== undefined) {
1027 const background = parseCssColor(backgroundColor);
1028 const foreground = color === undefined ? undefined : parseCssColor(color);
1029 if (
1030 background !== undefined &&
1031 (foreground === undefined || contrastRatio(foreground, background) < 3)
1032 ) {
1033 color = luminance(background) > 0.3 ? "#1f2328" : "#ffffff";
1036 const textDecorationLine = attributes.underline
1037 ? attributes.strike
1038 ? "underline line-through"
1039 : "underline"
1040 : attributes.strike
1041 ? "line-through"
1042 : undefined;
1043 return {
1044 ...(color === undefined ? {} : { color }),
1045 ...(backgroundColor === undefined ? {} : { backgroundColor }),
1046 ...(attributes.bold ? { fontWeight: "600" } : {}),
1047 ...(attributes.dim ? { opacity: 0.65 } : {}),
1048 ...(attributes.italic ? { fontStyle: "italic" } : {}),
1049 ...(textDecorationLine === undefined ? {} : { textDecorationLine }),
1050 };
1052​
1053/** Caps styled spans at maxSpans, then emits one plain remainder to bound DOM/native nodes. */
1054export function terminalOutputSpans(
1055 text: string,
1056 palette: ReadonlyArray<string>,
1057 maxSpans = 2_000,
1058): ReadonlyArray<TerminalSpan> {
1059 const spans: Array<TerminalSpan> = [];
1060 const styles = new Map<string, TerminalSpanStyle | null>();
1061 let pen = "";
1062 let cursor = 0;
1063 const push = (end: number) => {
1064 if (end <= cursor) return;
1065 let style = styles.get(pen);
1066 if (style === undefined) {
1067 style = spanStyle(pen, palette);
1068 styles.set(pen, style);
1070 spans.push({ text: text.slice(cursor, end), style });
1071 };
1072 while (cursor < text.length) {
1073 const escape = text.indexOf(`${ESC}[`, cursor);
1074 if (escape === -1 || spans.length >= maxSpans) break;
1075 push(escape);
1076 const end = text.indexOf("m", escape);
1077 if (end === -1) break;
1078 const params = text.slice(escape + 2, end);
1079 pen = params === "0" ? "" : params.replace(/^0;/u, "");
1080 cursor = end + 1;
1082 if (cursor < text.length) {
1083 if (spans.length >= maxSpans) {
1084 spans.push({ text: terminalOutputPlainText(text.slice(cursor)), style: null });
1085 } else {
1086 push(text.length);
1089 return spans;
1091​
1092// Colours and the cursor, erase and mode controls a saved transcript cannot replay.
1093const CSI_PATTERN = new RegExp(`${ESC}\\[[0-?]*[ -/]*[@-~]`, "gu");
1094​
1095export function terminalOutputPlainText(text: string): string {
1096 return text.replace(CSI_PATTERN, "");
1098​
1099// tqdm redraws a progress bar after a carriage return; JupyterLab shows only what the last
1100// redraws leave on the line. Walking the frames from the last keeps this linear.
1101function lastFrame(line: string): string {
1102 const frames = line.split("\r");
1103 let row = frames.pop()!;
1104 if (frames.length === 0) return row;
1105 let width = textWidth(row);
1106 for (const frame of frames.reverse()) {
1107 const frameWidth = textWidth(frame);
1108 if (frameWidth <= width) continue;
1109 row += sliceLine([{ pen: "", text: frame }], width, frameWidth)[0]?.text ?? "";
1110 width = frameWidth;
1112 return row;
1114​
1115export function terminalOutputCollapseRedraws(text: string): string {
1116 return /\r(?!\n)/.test(text)
1117 ? text.replaceAll("\r\n", "\n").split("\n").map(lastFrame).join("\n")
1118 : text;
1120​
1121const SAVED_CSI = /(?:\u001b\[|\u009b)([0-?]*)([ -/]*)([@-~])/uy;
1122const SAVED_STRING_END = /\u001b\\?|\u009c|[\u0018\u001a]/gu;
1123const SAVED_OSC_END = /\u001b\\?|\u009c|[\u0007\u0018\u001a]/gu;
1124​
1125/** Replays saved horizontal edits in original columns, without a terminal scrollback limit.
1126 * Undefined when erases would revisit too many columns, so hostile input stays linear. */
1127export function terminalOutputReplayLineEdits(line: string): string | undefined {
1128 // Zero is blank, one continues a wide glyph, and other values encode code points.
1129 let columns = new Uint32Array(0);
1130 const prefixes = new Map<number, string>();
1131 const suffixes = new Map<number, string>();
1132 let base: number | undefined;
1133 let wrotePrefix = false;
1134 let length = 0;
1135 let col = 0;
1136 let savedCol: number | undefined;
1137 let plainParts: string[] | undefined = [];
1138 let plainStart = 0;
1139 let eraseBudget = 4 * line.length;
1140​
1141 const skipControl = (start: number, end: number) => {
1142 if (start > plainStart) plainParts?.push(line.slice(plainStart, start));
1143 plainStart = end;
1144 };
1145​
1146 const moveTo = (next: number) => {
1147 base = undefined;
1148 wrotePrefix = false;
1149 col = next;
1150 };
1151​
1152 const clearBoundary = (at: number) => {
1153 if (columns[at] !== 1) return;
1154 suffixes.delete(at - 1);
1155 columns[at - 1] = 0;
1156 columns[at] = 0;
1157 };
1158​
1159 const erase = (mode: number): boolean => {
1160 plainParts = undefined;
1161 base = undefined;
1162 wrotePrefix = false;
1163 if (mode === 2) {
1164 eraseBudget -= length;
1165 if (eraseBudget < 0) return false;
1166 columns.fill(0, 0, length);
1167 length = 0;
1168 prefixes.clear();
1169 suffixes.clear();
1170 return true;
1172 const boundary = Math.min(length, mode === 0 ? col : col + 1);
1173 const start = mode === 0 ? boundary : 0;
1174 const end = mode === 0 ? length : boundary;
1175 if (mode === 0) prefixes.delete(end);
1176 if (start === end) return true;
1177 eraseBudget -= end - start;
1178 if (eraseBudget < 0) return false;
1179​
1180 clearBoundary(boundary);
1181 columns.fill(0, start, end);
1182 if (prefixes.size > 0 || suffixes.size > 0) {
1183 for (let at = start; at < end; at += 1) {
1184 prefixes.delete(at);
1185 suffixes.delete(at);
1188 if (mode === 0) length = boundary;
1189 return true;
1190 };
1191​
1192 for (let index = 0; index < line.length;) {
1193 const point = line.codePointAt(index)!;
1194 if (point === 0x1b || (point >= 0x80 && point <= 0x9f)) {
1195 const start = index;
1196 SAVED_CSI.lastIndex = index;
1197 const csi = SAVED_CSI.exec(line);
1198 if (csi) {
1199 index = SAVED_CSI.lastIndex;
1200 skipControl(start, index);
1201 const [, params, intermediates, command] = csi;
1202 if (intermediates || !/^[\d;]*$/u.test(params!)) continue;
1203 const [first, second] = params!.split(";", 2).map(Number);
1204 const distance = first || 1;
1205 if (command === "K" && (first === 0 || first === 1 || first === 2)) {
1206 if (!erase(first)) return undefined;
1207 } else if (command === "s") savedCol = col;
1208 else if (command === "u" && savedCol !== undefined) moveTo(savedCol);
1209 else if (command === "E" || command === "F") moveTo(0);
1210 else if ("CDGHf".includes(command!)) {
1211 const next =
1212 command === "C"
1213 ? col + distance
1214 : command === "D"
1215 ? col - distance
1216 : command === "G"
1217 ? distance - 1
1218 : (second || 1) - 1;
1219 // Keep existing columns addressable without expanding short lines far beyond their input.
1220 moveTo(Math.max(0, Math.min(Math.max(length, line.length), next)));
1222 continue;
1224 const esc = point === 0x1b;
1225 const introducer = line[index + 1] ?? "";
1226 const osc = point === 0x9d || (esc && introducer === "]");
1227 if (
1228 osc ||
1229 point === 0x90 ||
1230 point === 0x98 ||
1231 point === 0x9e ||
1232 point === 0x9f ||
1233 (esc && STRING_SEQUENCE_INTRODUCERS.has(introducer))
1234 ) {
1235 const end = osc ? SAVED_OSC_END : SAVED_STRING_END;
1236 end.lastIndex = index + (esc ? 2 : 1);
1237 const terminator = end.exec(line);
1238 // A bare ESC interrupts the string and begins the next command.
1239 index =
1240 terminator?.[0] === ESC ? terminator.index : terminator ? end.lastIndex : line.length;
1241 } else if (esc) {
1242 if (introducer === "7") savedCol = col;
1243 else if (introducer === "8" && savedCol !== undefined) moveTo(savedCol);
1244 const size = escapeLength(line, index);
1245 index = size === -1 ? line.length : index + size;
1246 } else index += 1;
1247 skipControl(start, index);
1248 continue;
1250 index += point > 0xffff ? 2 : 1;
1251 if (point < 0x20 && point !== 0x09) {
1252 base = undefined;
1253 wrotePrefix = false;
1254 if (point === 0x0d) col = 0;
1255 else if (point === 0x08) col = Math.max(0, col - 1);
1256 continue;
1258 if (point === 0x7f) continue;
1259 const character = String.fromCodePoint(point);
1260 const width = characterWidth(character);
1261 if (width === 0) {
1262 if (base === undefined) {
1263 prefixes.set(col, (prefixes.get(col) ?? "") + character);
1264 wrotePrefix = true;
1265 length = Math.max(length, col);
1266 } else suffixes.set(base, (suffixes.get(base) ?? "") + character);
1267 continue;
1269 const end = col + width;
1270 if (end > columns.length) {
1271 const grown = new Uint32Array(Math.max(end, columns.length * 2, 32));
1272 grown.set(columns);
1273 columns = grown;
1275 clearBoundary(col);
1276 if (columns[end] === 1) columns[end] = 0;
1277 if (!wrotePrefix) prefixes.delete(col);
1278 suffixes.delete(col);
1279 columns[col] = point + 2;
1280 if (width === 2) {
1281 columns[col + 1] = 1;
1282 prefixes.delete(col + 1);
1283 suffixes.delete(col + 1);
1285 base = col;
1286 wrotePrefix = false;
1287 col = end;
1288 length = Math.max(length, end);
1290​
1291 // An apparent erase inside a control string does not activate horizontal replay.
1292 if (plainParts) {
1293 plainParts.push(line.slice(plainStart));
1294 return plainParts.join("");
1296​
1297 const parts: string[] = [];
1298 let text = "";
1299 for (let at = 0; at < length; at += 1) {
1300 const cell = columns[at] ?? 0;
1301 text +=
1302 (prefixes.get(at) ?? "") +
1303 (cell === 0 ? " " : cell === 1 ? "" : String.fromCodePoint(cell - 2)) +
1304 (suffixes.get(at) ?? "");
1305 if (text.length >= 4096) {
1306 parts.push(text);
1307 text = "";
1310 parts.push(text, prefixes.get(length) ?? "");
1311 return parts.join("");