Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

keep fullscreen table selections within cells (#419)

ktcdc94cc8a108
diff --git a/packages/tui/CHANGELOG.md b/packages/tui/CHANGELOG.md
index 33467f832f..8dd25e6f1d 100644
--- a/packages/tui/CHANGELOG.md
+++ b/packages/tui/CHANGELOG.md
@@ -2,6 +2,7 @@
## [Unreleased]
+- Fixed fullscreen Markdown table selections copying borders instead of tab-separated cell content ([ENG-4629](https://linear.app/primeintellect/issue/ENG-4629/respect-table-boundaries-when-selecting)).
- Fixed fullscreen drag selection so holding at a transcript edge scrolls through offscreen text ([ENG-4644](https://linear.app/primeintellect/issue/ENG-4644/copy-issues)).
- Fixed slash-command and skill autocomplete not appearing for references typed in the middle of prompts ([ENG-4628](https://linear.app/primeintellect/issue/ENG-4628/support-skill-and-command-autocomplete-mid-prompt)).
- Fixed focused full-pane overlays becoming slow to navigate on wider terminals.
diff --git a/packages/tui/src/components/box.ts b/packages/tui/src/components/box.ts
index c99b8600b7..e1f265479a 100644
--- a/packages/tui/src/components/box.ts
+++ b/packages/tui/src/components/box.ts
@@ -1,3 +1,4 @@
+import type { TableCellSelectionRegion } from "../selection-metadata.js";
import type { Component } from "../tui.js";
import { applyBackgroundToLine, visibleWidth } from "../utils.js";
@@ -6,6 +7,7 @@ type RenderCache = {
width: number;
bgSample: string | undefined;
lines: string[];
+ selectionRegions: TableCellSelectionRegion[];
};
/**
@@ -73,6 +75,7 @@ export class Box implements Component {
render(width: number): string[] {
if (this.children.length === 0) {
+ this.cache = undefined;
return [];
}
@@ -81,14 +84,28 @@ export class Box implements Component {
// Render all children
const childLines: string[] = [];
+ const selectionRegions: TableCellSelectionRegion[] = [];
for (const child of this.children) {
+ const lineOffset = childLines.length;
const lines = child.render(contentWidth);
+ for (const region of child.getSelectionRegions?.() ?? []) {
+ selectionRegions.push({
+ ...region,
+ line: region.line + lineOffset + this.paddingY,
+ col: region.col + this.paddingX,
+ tableTop: region.tableTop + lineOffset + this.paddingY,
+ tableBottom: region.tableBottom + lineOffset + this.paddingY,
+ tableLeft: region.tableLeft + this.paddingX,
+ tableRight: region.tableRight + this.paddingX,
+ });
+ }
for (const line of lines) {
childLines.push(leftPad + line);
}
}
if (childLines.length === 0) {
+ this.cache = undefined;
return [];
}
@@ -97,6 +114,7 @@ export class Box implements Component {
// Check cache validity
if (this.matchCache(width, childLines, bgSample)) {
+ this.cache!.selectionRegions = selectionRegions;
return this.cache!.lines;
}
@@ -119,11 +137,15 @@ export class Box implements Component {
}
// Update cache
- this.cache = { childLines, width, bgSample, lines: result };
+ this.cache = { childLines, width, bgSample, lines: result, selectionRegions };
return result;
}
+ getSelectionRegions(): ReadonlyArray<TableCellSelectionRegion> {
+ return this.cache?.selectionRegions ?? [];
+ }
+
private applyBg(line: string, width: number): string {
const visLen = visibleWidth(line);
const padNeeded = Math.max(0, width - visLen);
diff --git a/packages/tui/src/components/markdown.ts b/packages/tui/src/components/markdown.ts
index e7ddbc8d27..16e7fe752a 100644
--- a/packages/tui/src/components/markdown.ts
+++ b/packages/tui/src/components/markdown.ts
@@ -1,8 +1,15 @@
import { Marked, type Token, Tokenizer, type TokenizerExtension, type Tokens } from "marked";
import { latexToUnicode } from "../latex.js";
+import {
+ extractTableCellSelectionRegions,
+ markTableCell,
+ markTableEnd,
+ markTableStart,
+ type TableCellSelectionRegion,
+} from "../selection-metadata.js";
import { getCapabilities, hyperlink, isImageLine } from "../terminal-image.js";
import type { Component } from "../tui.js";
-import { applyBackgroundToLine, visibleWidth, wrapTextWithAnsi } from "../utils.js";
+import { applyBackgroundToLine, stripAnsi, visibleWidth, wrapTextWithAnsi } from "../utils.js";
const STRICT_STRIKETHROUGH_REGEX = /^(~~)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/;
@@ -184,6 +191,8 @@ export class Markdown implements Component {
private cachedText?: string;
private cachedWidth?: number;
private cachedLines?: string[];
+ private selectionRegions: TableCellSelectionRegion[] = [];
+ private tableIdentities: object[] = [];
// Per-block render cache so streaming appends only re-render the changing
// final block instead of the whole document. Keyed by width/type/nextType/raw;
// rebuilt each render so it stays bounded to the current document's blocks.
@@ -210,12 +219,14 @@ export class Markdown implements Component {
this.cachedText = undefined;
this.cachedWidth = undefined;
this.cachedLines = undefined;
+ this.selectionRegions = [];
}
invalidate(): void {
this.cachedText = undefined;
this.cachedWidth = undefined;
this.cachedLines = undefined;
+ this.selectionRegions = [];
// External invalidation (e.g. theme change) affects rendered output, so
// the per-block cache must go too.
this.blockCache = new Map();
@@ -233,6 +244,7 @@ export class Markdown implements Component {
// Don't render anything if there's no actual text
if (!this.text || this.text.trim() === "") {
const result: string[] = [];
+ this.selectionRegions = [];
// Update cache
this.cachedText = this.text;
this.cachedWidth = width;
@@ -282,7 +294,12 @@ export class Markdown implements Component {
}
// Combine top padding, content, and bottom padding
- const result = [...emptyLines, ...contentLines, ...emptyLines];
+ const markedResult = [...emptyLines, ...contentLines, ...emptyLines];
+ const { lines: result, regions } = extractTableCellSelectionRegions(markedResult, (index) => {
+ this.tableIdentities[index] ??= {};
+ return this.tableIdentities[index];
+ });
+ this.selectionRegions = regions;
// Update cache
this.cachedText = this.text;
@@ -292,6 +309,10 @@ export class Markdown implements Component {
return result.length > 0 ? result : [""];
}
+ getSelectionRegions(): ReadonlyArray<TableCellSelectionRegion> {
+ return this.selectionRegions;
+ }
+
/** Render one top-level block: token lines, wrapping, margins, background. */
private renderBlock(token: Token, nextTokenType: string | undefined, width: number, contentWidth: number): string[] {
const tokenLines = this.renderToken(token, contentWidth, nextTokenType);
@@ -933,20 +954,20 @@ export class Markdown implements Component {
// Render top border
const topBorderCells = columnWidths.map((w) => "─".repeat(w));
- lines.push(`┌─${topBorderCells.join("─┬─")}─┐`);
+ lines.push(markTableStart(`┌─${topBorderCells.join("─┬─")}─┐`));
// Render header with wrapping
- const headerCellLines: string[][] = token.header.map((cell, i) => {
+ const headerCells = token.header.map((cell, i) => {
const text = this.renderInlineTokens(cell.tokens || [], styleContext);
- return this.wrapCellText(text, columnWidths[i]);
+ return { lines: this.wrapCellText(text, columnWidths[i]), content: stripAnsi(text) };
});
- const headerLineCount = Math.max(...headerCellLines.map((c) => c.length));
+ const headerLineCount = Math.max(...headerCells.map((cell) => cell.lines.length));
for (let lineIdx = 0; lineIdx < headerLineCount; lineIdx++) {
- const rowParts = headerCellLines.map((cellLines, colIdx) => {
- const text = cellLines[lineIdx] || "";
+ const rowParts = headerCells.map((cell, colIdx) => {
+ const text = cell.lines[lineIdx] || "";
const padded = text + " ".repeat(Math.max(0, columnWidths[colIdx] - visibleWidth(text)));
- return this.theme.bold(padded);
+ return markTableCell(this.theme.bold(padded), 0, colIdx, lineIdx, cell.content);
});
lines.push(`│ ${rowParts.join(" │ ")} │`);
}
@@ -959,16 +980,17 @@ export class Markdown implements Component {
// Render rows with wrapping
for (let rowIndex = 0; rowIndex < token.rows.length; rowIndex++) {
const row = token.rows[rowIndex];
- const rowCellLines: string[][] = row.map((cell, i) => {
+ const rowCells = row.map((cell, i) => {
const text = this.renderInlineTokens(cell.tokens || [], styleContext);
- return this.wrapCellText(text, columnWidths[i]);
+ return { lines: this.wrapCellText(text, columnWidths[i]), content: stripAnsi(text) };
});
- const rowLineCount = Math.max(...rowCellLines.map((c) => c.length));
+ const rowLineCount = Math.max(...rowCells.map((cell) => cell.lines.length));
for (let lineIdx = 0; lineIdx < rowLineCount; lineIdx++) {
- const rowParts = rowCellLines.map((cellLines, colIdx) => {
- const text = cellLines[lineIdx] || "";
- return text + " ".repeat(Math.max(0, columnWidths[colIdx] - visibleWidth(text)));
+ const rowParts = rowCells.map((cell, colIdx) => {
+ const text = cell.lines[lineIdx] || "";
+ const padded = text + " ".repeat(Math.max(0, columnWidths[colIdx] - visibleWidth(text)));
+ return markTableCell(padded, rowIndex + 1, colIdx, lineIdx, cell.content);
});
lines.push(`│ ${rowParts.join(" │ ")} │`);
}
@@ -980,7 +1002,7 @@ export class Markdown implements Component {
// Render bottom border
const bottomBorderCells = columnWidths.map((w) => "─".repeat(w));
- lines.push(`└─${bottomBorderCells.join("─┴─")}─┘`);
+ lines.push(markTableEnd(`└─${bottomBorderCells.join("─┴─")}─┘`));
if (nextTokenType && nextTokenType !== "space") {
lines.push(""); // Add spacing after table
diff --git a/packages/tui/src/fullscreen.ts b/packages/tui/src/fullscreen.ts
index 5a330c7006..b11e9a9963 100644
--- a/packages/tui/src/fullscreen.ts
+++ b/packages/tui/src/fullscreen.ts
@@ -5,6 +5,7 @@
* scroll position is application state, not terminal scrollback.
*/
+import type { TableCellSelectionRegion } from "./selection-metadata.js";
import { isImageLine } from "./terminal-image.js";
import { sliceByColumn, stripAnsi, visibleWidth } from "./utils.js";
@@ -51,7 +52,24 @@ interface FrameSelectionSnapshot {
visibleHeight: number;
}
-type SelectionMode = "transcript" | "frame";
+interface TableCellPosition {
+ row: number;
+ column: number;
+}
+
+interface ActiveTableSelection {
+ table: object;
+ anchor: TableCellPosition;
+}
+
+interface TableSelectionRange {
+ fromRow: number;
+ toRow: number;
+ fromColumn: number;
+ toColumn: number;
+}
+
+type SelectionMode = "transcript" | "table" | "frame";
export class FullscreenViewport {
private scrollTop = 0;
@@ -66,7 +84,9 @@ export class FullscreenViewport {
private lastFrameVisibleStart = 0;
private lastFrameVisibleHeight = 0;
private frameSelectionRegions: ReadonlyArray<FrameSelectionRegion> = [];
+ private tableCellSelectionRegions: ReadonlyArray<TableCellSelectionRegion> = [];
private activeFrameSelection: FrameSelectionSnapshot | null = null;
+ private activeTableSelection: ActiveTableSelection | null = null;
private selectionAnchor: SelectionPoint | null = null;
private selectionHead: SelectionPoint | null = null;
private selectionMode: SelectionMode | null = null;
@@ -76,7 +96,12 @@ export class FullscreenViewport {
* top, dock pinned to the bottom. Following pins the window to the
* transcript end; otherwise it stays frozen while content appends.
*/
- composeFrame(transcript: string[], dock: string[], height: number): string[] {
+ composeFrame(
+ transcript: string[],
+ dock: string[],
+ height: number,
+ tableCellSelectionRegions: ReadonlyArray<TableCellSelectionRegion> = [],
+ ): string[] {
let dockLines = dock;
const dockHeight = clippedFullscreenDockHeight(dockLines.length, height);
if (dockLines.length > dockHeight) {
@@ -94,6 +119,7 @@ export class FullscreenViewport {
this.lastMaxScroll = maxScroll;
this.lastWindowHeight = windowHeight;
this.lastTranscript = transcript;
+ this.tableCellSelectionRegions = tableCellSelectionRegions;
const window = transcript.slice(this.scrollTop, this.scrollTop + windowHeight);
for (let i = 0; i < window.length; i++) {
@@ -124,13 +150,18 @@ export class FullscreenViewport {
}
private highlightSelection(window: string[]): void {
- if (this.selectionMode !== "transcript") return;
+ if (this.selectionMode !== "transcript" && this.selectionMode !== "table") return;
const sel = this.orderedSelection();
if (!sel) return;
for (let i = 0; i < window.length; i++) {
- const span = this.selectionSpan(this.scrollTop + i, sel);
- if (!span) continue;
- window[i] = this.highlightLine(window[i], span);
+ const lineIndex = this.scrollTop + i;
+ const spans =
+ this.selectionMode === "table"
+ ? this.selectedTableSpans(lineIndex, sel)
+ : [this.selectionSpan(lineIndex, sel)].filter((span): span is ColumnSpan => span !== null);
+ for (let spanIndex = spans.length - 1; spanIndex >= 0; spanIndex--) {
+ window[i] = this.highlightLine(window[i], spans[spanIndex]);
+ }
}
}
@@ -144,19 +175,32 @@ export class FullscreenViewport {
const point = { line, col: Math.max(0, screenCol) };
this.selectionAnchor = point;
this.selectionHead = { ...point };
- this.selectionMode = "transcript";
+ const table = this.tableAtPoint(point);
+ const tableCell = table ? this.closestTableCell(table, point) : null;
+ if (table && tableCell) {
+ this.activeTableSelection = { table, anchor: tableCell };
+ this.selectionMode = "table";
+ } else {
+ this.activeTableSelection = null;
+ this.selectionMode = "transcript";
+ }
return true;
}
extendSelection(screenRow: number, screenCol: number): void {
- if (!this.selectionAnchor || this.selectionMode !== "transcript") return;
+ if (!this.selectionAnchor || (this.selectionMode !== "transcript" && this.selectionMode !== "table")) return;
const line = this.transcriptLineForScreenRow(screenRow, true);
if (line === null) return;
this.selectionHead = { line, col: Math.max(0, screenCol) };
}
selectionAutoScrollDirection(screenRow: number): SelectionScrollDirection | null {
- if (!this.selectionAnchor || !this.selectionHead || this.selectionMode !== "transcript") return null;
+ if (
+ !this.selectionAnchor ||
+ !this.selectionHead ||
+ (this.selectionMode !== "transcript" && this.selectionMode !== "table")
+ )
+ return null;
const bounds = this.transcriptScreenBounds();
if (!bounds) return null;
if (this.selectionHead.line < this.selectionAnchor.line && screenRow <= bounds.firstRow && this.scrollTop > 0) {
@@ -173,7 +217,8 @@ export class FullscreenViewport {
}
scrollSelection(direction: SelectionScrollDirection, screenCol: number): boolean {
- if (!this.selectionAnchor || this.selectionMode !== "transcript") return false;
+ if (!this.selectionAnchor || (this.selectionMode !== "transcript" && this.selectionMode !== "table"))
+ return false;
const previousScrollTop = this.scrollTop;
this.scrollBy(direction);
if (this.scrollTop === previousScrollTop) return false;
@@ -185,20 +230,24 @@ export class FullscreenViewport {
/** Finish the selection and return its plain text (null when empty). */
endSelection(): string | null {
- if (this.selectionMode !== "transcript") {
+ if (this.selectionMode !== "transcript" && this.selectionMode !== "table") {
this.clearSelection();
return null;
}
const sel = this.orderedSelection();
+ const text = sel
+ ? this.selectionMode === "table"
+ ? this.extractTableSelectionText(this.lastTranscript, sel)
+ : this.extractSelectionText(this.lastTranscript, sel)
+ : null;
this.clearSelection();
- if (!sel) return null;
- return this.extractSelectionText(this.lastTranscript, sel);
+ return text;
}
extendActiveSelection(screenRow: number, screenCol: number): void {
if (this.selectionMode === "frame") {
this.extendFrameSelection(screenRow, screenCol);
- } else if (this.selectionMode === "transcript") {
+ } else if (this.selectionMode === "transcript" || this.selectionMode === "table") {
this.extendSelection(screenRow, screenCol);
}
}
@@ -207,7 +256,7 @@ export class FullscreenViewport {
if (this.selectionMode === "frame") {
return this.endFrameSelection();
}
- if (this.selectionMode === "transcript") {
+ if (this.selectionMode === "transcript" || this.selectionMode === "table") {
return this.endSelection();
}
this.clearSelection();
@@ -343,6 +392,87 @@ export class FullscreenViewport {
);
}
+ private tableRegions(table: object): TableCellSelectionRegion[] {
+ return this.tableCellSelectionRegions.filter((region) => region.table === table);
+ }
+
+ private tableAtPoint(point: SelectionPoint): object | null {
+ const tables = new Set(this.tableCellSelectionRegions.map((region) => region.table));
+ for (const table of tables) {
+ const region = this.tableRegions(table)[0];
+ if (
+ region &&
+ point.line >= region.tableTop &&
+ point.line <= region.tableBottom &&
+ point.col >= Math.max(0, region.tableLeft - 1) &&
+ point.col <= region.tableRight
+ ) {
+ return table;
+ }
+ }
+ return null;
+ }
+
+ private closestTableCell(table: object, point: SelectionPoint): TableCellPosition | null {
+ let closest: TableCellPosition | null = null;
+ let closestLineDistance = Number.POSITIVE_INFINITY;
+ let closestColumnDistance = Number.POSITIVE_INFINITY;
+ for (const region of this.tableRegions(table)) {
+ const lineDistance = Math.abs(point.line - region.line);
+ const end = region.col + region.width;
+ const columnDistance = point.col < region.col ? region.col - point.col : point.col > end ? point.col - end : 0;
+ if (
+ lineDistance < closestLineDistance ||
+ (lineDistance === closestLineDistance && columnDistance < closestColumnDistance)
+ ) {
+ closest = { row: region.row, column: region.column };
+ closestLineDistance = lineDistance;
+ closestColumnDistance = columnDistance;
+ }
+ }
+ return closest;
+ }
+
+ private activeTableRange(): TableSelectionRange | null {
+ const active = this.activeTableSelection;
+ const head = this.selectionHead;
+ if (!active || !head) return null;
+ const headCell = this.closestTableCell(active.table, head);
+ if (!headCell) return null;
+ return {
+ fromRow: Math.min(active.anchor.row, headCell.row),
+ toRow: Math.max(active.anchor.row, headCell.row),
+ fromColumn: Math.min(active.anchor.column, headCell.column),
+ toColumn: Math.max(active.anchor.column, headCell.column),
+ };
+ }
+
+ private selectedTableSpans(lineIndex: number, sel: { start: SelectionPoint; end: SelectionPoint }): ColumnSpan[] {
+ const active = this.activeTableSelection;
+ const range = this.activeTableRange();
+ if (!active || !range) return [];
+ const singleCell = range.fromRow === range.toRow && range.fromColumn === range.toColumn;
+ const selectionSpan = singleCell ? this.selectionSpan(lineIndex, sel) : null;
+ if (singleCell && !selectionSpan) return [];
+
+ const spans: ColumnSpan[] = [];
+ for (const region of this.tableCellSelectionRegions) {
+ if (
+ region.line !== lineIndex ||
+ region.table !== active.table ||
+ region.row < range.fromRow ||
+ region.row > range.toRow ||
+ region.column < range.fromColumn ||
+ region.column > range.toColumn
+ )
+ continue;
+ const from = selectionSpan ? Math.max(selectionSpan.from, region.col) : region.col;
+ const to = selectionSpan ? Math.min(selectionSpan.to, region.col + region.width) : region.col + region.width;
+ if (to > from) spans.push({ from, to });
+ }
+ return spans.sort((a, b) => a.from - b.from);
+ }
+
private frameRegionsForLine(
line: number,
regions = this.activeFrameSelection?.regions ?? this.frameSelectionRegions,
@@ -426,11 +556,69 @@ export class FullscreenViewport {
return text.trim().length > 0 ? text : null;
}
+ private compareSelectionPoints(a: SelectionPoint, b: SelectionPoint): number {
+ return a.line === b.line ? a.col - b.col : a.line - b.line;
+ }
+
+ private extractTableSelectionText(
+ sourceLines: string[],
+ sel: { start: SelectionPoint; end: SelectionPoint },
+ ): string | null {
+ const active = this.activeTableSelection;
+ const range = this.activeTableRange();
+ if (!active || !range) return null;
+
+ if (range.fromRow !== range.toRow || range.fromColumn !== range.toColumn) {
+ const contents = new Map<string, string>();
+ for (const region of this.tableRegions(active.table)) {
+ contents.set(`${region.row}:${region.column}`, region.content);
+ }
+ const rows: string[] = [];
+ for (let row = range.fromRow; row <= range.toRow; row++) {
+ const cells: string[] = [];
+ for (let column = range.fromColumn; column <= range.toColumn; column++) {
+ cells.push(contents.get(`${row}:${column}`) ?? "");
+ }
+ rows.push(cells.join("\t"));
+ }
+ const text = rows.join("\n");
+ return text.trim().length > 0 ? text : null;
+ }
+
+ const cellRegions = this.tableRegions(active.table)
+ .filter((region) => region.row === range.fromRow && region.column === range.fromColumn)
+ .sort((a, b) => a.line - b.line || a.segment - b.segment);
+ const first = cellRegions[0];
+ const last = cellRegions.at(-1);
+ if (first && last) {
+ const cellStart = { line: first.line, col: first.col };
+ const cellEnd = { line: last.line, col: last.col + last.width };
+ if (
+ this.compareSelectionPoints(sel.start, cellStart) <= 0 &&
+ this.compareSelectionPoints(sel.end, cellEnd) >= 0
+ ) {
+ return first.content.trim().length > 0 ? first.content : null;
+ }
+ }
+
+ const lines: string[] = [];
+ for (let lineIndex = sel.start.line; lineIndex <= sel.end.line; lineIndex++) {
+ const line = sourceLines[lineIndex] ?? "";
+ const spans = this.selectedTableSpans(lineIndex, sel);
+ if (spans.length === 0) continue;
+ const parts = spans.map((span) => stripAnsi(sliceByColumn(line, span.from, Math.max(0, span.to - span.from))));
+ lines.push(parts.join("").trimEnd());
+ }
+ const text = lines.join("\n");
+ return text.trim().length > 0 ? text : null;
+ }
+
clearSelection(): void {
this.selectionAnchor = null;
this.selectionHead = null;
this.selectionMode = null;
this.activeFrameSelection = null;
+ this.activeTableSelection = null;
}
hasSelection(): boolean {
diff --git a/packages/tui/src/index.ts b/packages/tui/src/index.ts
index c9b34c5e12..4accb4fe8b 100644
--- a/packages/tui/src/index.ts
+++ b/packages/tui/src/index.ts
@@ -78,6 +78,7 @@ export {
} from "./mouse.js";
// Render caching
export { VersionedRenderCache } from "./render-cache.js";
+export type { TableCellSelectionRegion } from "./selection-metadata.js";
// Input buffering for batch splitting
export { StdinBuffer, type StdinBufferEventMap, type StdinBufferOptions } from "./stdin-buffer.js";
// Terminal interface and implementations
diff --git a/packages/tui/src/selection-metadata.ts b/packages/tui/src/selection-metadata.ts
new file mode 100644
index 0000000000..329ba3337f
--- /dev/null
+++ b/packages/tui/src/selection-metadata.ts
@@ -0,0 +1,181 @@
+import { extractAnsiCode, visibleWidth } from "./utils.js";
+
+const TABLE_MARKER_PREFIX = "\x1b_pi:table:";
+const TABLE_START_MARKER = `${TABLE_MARKER_PREFIX}start\x07`;
+const TABLE_END_MARKER = `${TABLE_MARKER_PREFIX}end\x07`;
+
+export interface TableCellSelectionRegion {
+ line: number;
+ col: number;
+ width: number;
+ table: object;
+ tableTop: number;
+ tableBottom: number;
+ tableLeft: number;
+ tableRight: number;
+ row: number;
+ column: number;
+ segment: number;
+ content: string;
+}
+
+interface CellMarker {
+ kind: "cell-start" | "cell-end";
+ row: number;
+ column: number;
+ segment: number;
+ content?: string;
+}
+
+interface TableBounds {
+ top: number;
+ bottom: number;
+ left: number;
+ right: number;
+}
+
+function cellMarker(kind: CellMarker["kind"], row: number, column: number, segment: number, content?: string): string {
+ const encodedContent = content === undefined ? "" : `:${encodeURIComponent(content)}`;
+ return `${TABLE_MARKER_PREFIX}${kind}:${row}:${column}:${segment}${encodedContent}\x07`;
+}
+
+function parseCellMarker(code: string): CellMarker | null {
+ if (!code.startsWith(TABLE_MARKER_PREFIX) || !code.endsWith("\x07")) return null;
+ const [kind, rowText, columnText, segmentText, encodedContent] = code
+ .slice(TABLE_MARKER_PREFIX.length, -1)
+ .split(":");
+ if (kind !== "cell-start" && kind !== "cell-end") return null;
+ const row = Number(rowText);
+ const column = Number(columnText);
+ const segment = Number(segmentText);
+ if (![row, column, segment].every(Number.isInteger)) return null;
+ return {
+ kind,
+ row,
+ column,
+ segment,
+ content: encodedContent === undefined ? undefined : decodeURIComponent(encodedContent),
+ };
+}
+
+export function markTableStart(line: string): string {
+ return TABLE_START_MARKER + line;
+}
+
+export function markTableEnd(line: string): string {
+ return line + TABLE_END_MARKER;
+}
+
+export function markTableCell(text: string, row: number, column: number, segment: number, content: string): string {
+ const markerContent = segment === 0 ? content : undefined;
+ return (
+ cellMarker("cell-start", row, column, segment, markerContent) +
+ text +
+ cellMarker("cell-end", row, column, segment)
+ );
+}
+
+export function extractTableCellSelectionRegions(
+ lines: string[],
+ getTableIdentity: (index: number) => object,
+): { lines: string[]; regions: TableCellSelectionRegion[] } {
+ if (!lines.some((line) => line.includes(TABLE_MARKER_PREFIX))) {
+ return { lines, regions: [] };
+ }
+
+ const cleanLines: string[] = [];
+ const regions: TableCellSelectionRegion[] = [];
+ const cellContents = new Map<object, Map<string, string>>();
+ const tableBounds = new Map<object, TableBounds>();
+ let table: object | null = null;
+ let tableIndex = 0;
+
+ for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
+ const source = lines[lineIndex];
+ if (!source.includes(TABLE_MARKER_PREFIX)) {
+ cleanLines.push(source);
+ continue;
+ }
+ let clean = "";
+ let activeCell: (CellMarker & { col: number }) | null = null;
+ let offset = 0;
+
+ while (offset < source.length) {
+ const ansi = extractAnsiCode(source, offset);
+ if (!ansi) {
+ clean += source[offset];
+ offset++;
+ continue;
+ }
+
+ if (ansi.code === TABLE_START_MARKER) {
+ table = getTableIdentity(tableIndex++);
+ const col = visibleWidth(clean);
+ tableBounds.set(table, { top: lineIndex, bottom: lineIndex, left: col, right: col });
+ } else if (ansi.code === TABLE_END_MARKER) {
+ if (table) {
+ const bounds = tableBounds.get(table);
+ if (bounds) {
+ bounds.bottom = lineIndex;
+ bounds.right = visibleWidth(clean);
+ }
+ }
+ table = null;
+ activeCell = null;
+ } else {
+ const marker = parseCellMarker(ansi.code);
+ if (marker?.kind === "cell-start") {
+ activeCell = { ...marker, col: visibleWidth(clean) };
+ if (table && marker.content !== undefined) {
+ let tableContents = cellContents.get(table);
+ if (!tableContents) {
+ tableContents = new Map();
+ cellContents.set(table, tableContents);
+ }
+ tableContents.set(`${marker.row}:${marker.column}`, marker.content);
+ }
+ } else if (marker?.kind === "cell-end" && table && activeCell) {
+ const width = visibleWidth(clean) - activeCell.col;
+ if (
+ width > 0 &&
+ marker.row === activeCell.row &&
+ marker.column === activeCell.column &&
+ marker.segment === activeCell.segment
+ ) {
+ regions.push({
+ line: lineIndex,
+ col: activeCell.col,
+ width,
+ table,
+ tableTop: 0,
+ tableBottom: 0,
+ tableLeft: 0,
+ tableRight: 0,
+ row: marker.row,
+ column: marker.column,
+ segment: marker.segment,
+ content: "",
+ });
+ }
+ activeCell = null;
+ } else {
+ clean += ansi.code;
+ }
+ }
+ offset += ansi.length;
+ }
+ cleanLines.push(clean);
+ }
+ for (const region of regions) {
+ const bounds = tableBounds.get(region.table);
+ if (bounds) {
+ region.tableTop = bounds.top;
+ region.tableBottom = bounds.bottom;
+ region.tableLeft = bounds.left;
+ region.tableRight = bounds.right;
+ }
+ region.content = cellContents.get(region.table)?.get(`${region.row}:${region.column}`) ?? "";
+ }
+
+ return { lines: cleanLines, regions };
+}
diff --git a/packages/tui/src/tui.ts b/packages/tui/src/tui.ts
index ef2c63bcec..90e7a9c324 100644
--- a/packages/tui/src/tui.ts
+++ b/packages/tui/src/tui.ts
@@ -10,6 +10,7 @@ import { FullscreenViewport, type ScrollInfo, type SelectionScrollDirection } fr
import { getKeybindings } from "./keybindings.js";
import { isKeyRelease, matchesKey } from "./keys.js";
import { isMouseSequence, isWheelDown, isWheelUp, MOUSE_BUTTON_LEFT, parseSgrMouseEvent } from "./mouse.js";
+import type { TableCellSelectionRegion } from "./selection-metadata.js";
import type { Terminal } from "./terminal.js";
import { deleteKittyImage, getCapabilities, isImageLine, setCellDimensions } from "./terminal-image.js";
import {
@@ -54,6 +55,8 @@ export interface Component {
*/
render(width: number): string[];
+ getSelectionRegions?(): ReadonlyArray<TableCellSelectionRegion>;
+
/**
* Optional handler for keyboard input when component has focus
*/
@@ -238,23 +241,28 @@ export interface OverlayHandle {
*/
export class Container implements Component {
children: Component[] = [];
+ private selectionRegions: TableCellSelectionRegion[] = [];
addChild(component: Component): void {
this.children.push(component);
+ this.selectionRegions = [];
}
removeChild(component: Component): void {
const index = this.children.indexOf(component);
if (index !== -1) {
this.children.splice(index, 1);
+ this.selectionRegions = [];
}
}
clear(): void {
this.children = [];
+ this.selectionRegions = [];
}
invalidate(): void {
+ this.selectionRegions = [];
for (const child of this.children) {
child.invalidate?.();
}
@@ -262,14 +270,29 @@ export class Container implements Component {
render(width: number): string[] {
const lines: string[] = [];
+ const selectionRegions: TableCellSelectionRegion[] = [];
for (const child of this.children) {
+ const lineOffset = lines.length;
const childLines = child.render(width);
+ for (const region of child.getSelectionRegions?.() ?? []) {
+ selectionRegions.push({
+ ...region,
+ line: region.line + lineOffset,
+ tableTop: region.tableTop + lineOffset,
+ tableBottom: region.tableBottom + lineOffset,
+ });
+ }
for (const line of childLines) {
lines.push(line);
}
}
+ this.selectionRegions = selectionRegions;
return lines;
}
+
+ getSelectionRegions(): ReadonlyArray<TableCellSelectionRegion> {
+ return this.selectionRegions;
+ }
}
/**
@@ -1389,14 +1412,25 @@ export class TUI extends Container {
this.overlaySelectionRegions = [];
const transcript: string[] = [];
+ const selectionRegions: TableCellSelectionRegion[] = [];
for (const component of fullscreen.scroll) {
- for (const line of component.render(width)) {
+ const lineOffset = transcript.length;
+ const componentLines = component.render(width);
+ for (const region of component.getSelectionRegions?.() ?? []) {
+ selectionRegions.push({
+ ...region,
+ line: region.line + lineOffset,
+ tableTop: region.tableTop + lineOffset,
+ tableBottom: region.tableBottom + lineOffset,
+ });
+ }
+ for (const line of componentLines) {
transcript.push(line);
}
}
const dock = fullscreen.dock.render(width);
- let frame = fullscreen.viewport.composeFrame(transcript, dock, height);
+ let frame = fullscreen.viewport.composeFrame(transcript, dock, height, selectionRegions);
this.overlaySelectionRegions.push(
...this.createDockSelectionRegions(frame, fullscreen.viewport.windowHeight(), width),
);
diff --git a/packages/tui/test/fullscreen.test.ts b/packages/tui/test/fullscreen.test.ts
index 1a07b18321..d05c8bf664 100644
--- a/packages/tui/test/fullscreen.test.ts
+++ b/packages/tui/test/fullscreen.test.ts
@@ -1,7 +1,10 @@
import assert from "node:assert";
import { describe, it } from "node:test";
+import { Box } from "../src/components/box.js";
+import { Markdown } from "../src/components/markdown.js";
import type { TerminalStopOptions } from "../src/terminal.js";
-import { type Component, TUI } from "../src/tui.js";
+import { type Component, Container, TUI } from "../src/tui.js";
+import { defaultMarkdownTheme } from "./test-themes.js";
import { VirtualTerminal } from "./virtual-terminal.js";
class TestComponent implements Component {
@@ -642,6 +645,97 @@ describe("TUI fullscreen mode", () => {
tui.stop();
});
+ it("keeps wrapped table-cell selection inside the originating cell", async () => {
+ const terminal = new LoggingVirtualTerminal(40, 12);
+ const tui = new TUI(terminal);
+ const markdown = new Markdown(
+ `| URL | Status |
+| --- | --- |
+| https://example.com/this/is/a/very/long/path | should-not-copy |`,
+ 0,
+ 0,
+ defaultMarkdownTheme,
+ );
+ const box = new Box(1, 0);
+ box.addChild(markdown);
+ const chat = new Container();
+ chat.addChild(box);
+ const dock = new TestComponent();
+ dock.lines = ["> prompt", "footer"];
+ const copies: string[] = [];
+ tui.onCopy = (text) => copies.push(text);
+ tui.addChild(chat);
+ tui.addChild(dock);
+ tui.start();
+ tui.enterFullscreen({ scroll: [chat], dock });
+ await terminal.waitForRender();
+
+ const lines = chat.render(40);
+ const regions = chat
+ .getSelectionRegions()
+ .filter((region) => region.row === 1 && region.column === 0)
+ .sort((a, b) => a.segment - b.segment);
+ assert.ok(regions.length > 1, "URL cell should wrap across physical lines");
+ assert.ok(lines.length <= 10, "table should fit without scrolling");
+
+ const first = regions[0];
+ const last = regions.at(-1)!;
+ const expected = first.content;
+ terminal.sendInput(`\x1b[<0;${first.col + 1};${first.line + 1}M`);
+ terminal.sendInput(`\x1b[<32;${last.col + last.width + 1};${last.line + 1}M`);
+ await terminal.waitForRender();
+ assert.ok(terminal.getWrites().includes("\x1b[7m"), "cell selection should be highlighted");
+
+ terminal.sendInput(`\x1b[<0;${last.col + last.width + 1};${last.line + 1}m`);
+ await terminal.waitForRender();
+ assert.deepStrictEqual(copies, [expected]);
+ assert.ok(!copies[0].includes("should-not-copy"));
+
+ tui.stop();
+ });
+
+ it("copies table selections as tab-separated content without borders", async () => {
+ const terminal = new LoggingVirtualTerminal(40, 12);
+ const tui = new TUI(terminal);
+ const markdown = new Markdown(
+ `| Name | Score | City |
+| --- | --- | --- |
+| Avery | 87 | Seattle |
+| Jordan | 92 | Austin |
+| Morgan | 74 | Boston |`,
+ 0,
+ 0,
+ defaultMarkdownTheme,
+ );
+ const box = new Box(1, 0);
+ box.addChild(markdown);
+ const chat = new Container();
+ chat.addChild(box);
+ const dock = new TestComponent();
+ dock.lines = ["> prompt", "footer"];
+ const copies: string[] = [];
+ tui.onCopy = (text) => copies.push(text);
+ tui.addChild(chat);
+ tui.addChild(dock);
+ tui.start();
+ tui.enterFullscreen({ scroll: [chat], dock });
+ await terminal.waitForRender();
+
+ const tableRegions = chat.getSelectionRegions();
+ const { tableTop: top, tableBottom: bottom, tableLeft: left, tableRight: right } = tableRegions[0];
+ terminal.sendInput(`\x1b[<0;${left};${top + 1}M`);
+ terminal.sendInput(`\x1b[<32;${right};${bottom + 1}M`);
+ await terminal.waitForRender();
+ assert.ok(terminal.getWrites().includes("\x1b[7m"), "table cell contents should be highlighted");
+
+ terminal.sendInput(`\x1b[<0;${right};${bottom + 1}m`);
+ await terminal.waitForRender();
+ assert.deepStrictEqual(copies, ["Name\tScore\tCity\nAvery\t87\tSeattle\nJordan\t92\tAustin\nMorgan\t74\tBoston"]);
+ assert.ok(!/[┌┬┐├┼┤└┴┘│─]/.test(copies[0]));
+
+ tui.stop();
+ });
+
it("auto-scrolls upward while selecting at the transcript edge", async () => {
const { terminal, tui, chat, dock } = setup(lines(30));
const copies: string[] = [];
diff --git a/packages/tui/test/markdown.test.ts b/packages/tui/test/markdown.test.ts
index 77e75b8d19..264b35caf9 100644
--- a/packages/tui/test/markdown.test.ts
+++ b/packages/tui/test/markdown.test.ts
@@ -362,6 +362,38 @@ describe("Markdown component", () => {
assert.ok(extracted.includes(url), "Should preserve URL");
});
+ it("should expose wrapped table cell boundaries without changing rendered text", () => {
+ setCapabilities({ images: null, trueColor: false, hyperlinks: false });
+ const url = "https://example.com/this/is/a/long/path";
+ const markdown = new Markdown(
+ `| URL | Status |
+| --- | --- |
+| ${url} | ready |`,
+ 0,
+ 0,
+ defaultMarkdownTheme,
+ );
+
+ const lines = markdown.render(32);
+ resetCapabilitiesCache();
+ const regions = markdown.getSelectionRegions();
+ const urlRegions = regions.filter((region) => region.row === 1 && region.column === 0);
+ const statusRegions = regions.filter((region) => region.row === 1 && region.column === 1);
+
+ assert.ok(urlRegions.length > 1, "URL cell should wrap across physical lines");
+ assert.strictEqual(statusRegions.length, urlRegions.length);
+ assert.ok(
+ lines.every((line) => !line.includes("\x1b_pi:table:")),
+ "metadata markers must be stripped",
+ );
+ assert.ok(urlRegions.every((region) => region.table === urlRegions[0].table));
+ assert.ok(urlRegions.every((region) => region.content === url));
+ for (let i = 0; i < urlRegions.length; i++) {
+ assert.strictEqual(urlRegions[i].line, statusRegions[i].line);
+ assert.ok(urlRegions[i].col + urlRegions[i].width < statusRegions[i].col);
+ }
+ });
+
it("should wrap styled inline code inside table cells without breaking borders", () => {
const markdown = new Markdown(
`| Code |