Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/api/src/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -74,6 +74,7 @@ export type {
ContextNamespace,
LanguagesNamespace,
ThemesNamespace,
ClipboardNamespace,
Tecode,
} from "./namespaces";

Expand Down
58 changes: 57 additions & 1 deletion packages/api/src/namespaces.ts
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
/**
* The nine `tecode.*` namespaces (Req 10.1, design.md §12) and the
* The ten `tecode.*` namespaces (Req 10.1, design.md §12) and the
* aggregate {@link Tecode} interface that bundles them into the single
* frozen object handed to every extension.
*/
Expand DownExpand Up@@ -451,6 +451,61 @@ export interface ThemesNamespace {
onDidChange: Event<void>;
}

/* ------------------------------------------------------------------ */
/* tecode.clipboard */
/* ------------------------------------------------------------------ */

/**
* The clipboard (Issue #91): an internal buffer holding the last text
* copied or cut, write-through synced to the terminal's OWN system
* clipboard via OSC 52 (`@opentui/core`'s `CliRenderer.
* copyToClipboardOSC52`, `packages/cli/src/renderShell.tsx`'s
* `onClipboardWriterReady`) when the host terminal supports it and
* `clipboard.useSystemClipboard` (`editor-core`'s own configuration
* contribution) is enabled. Backs `editor-core`'s
* `editor.action.clipboardCopy`/`clipboardCut`/`clipboardPaste` commands
* (Issue #91), and is available to any other extension that wants
* programmatic access to the same buffer.
*
* **Never throws — matches `FileSystem`'s never-crash discipline, NOT its
* reject-on-failure one**: unlike {@link FileSystem}'s `read`/`write`
* (which reject the returned promise on a real I/O failure — a caller is
* expected to handle that), a clipboard write's OSC 52 half is a
* best-effort terminal escape sequence with no reliable failure signal at
* all — a terminal that ignores it produces neither an error nor any
* other observable difference from success. {@link write} therefore always
* resolves once the INTERNAL buffer is updated (the part every terminal
* supports unconditionally); an OSC 52 write that the host reports failing
* is logged (`HostLog`, design.md §14) and otherwise swallowed, never
* surfaced as a rejection.
*
* **OSC 52 is write-only here, deliberately**: reading a terminal's system
* clipboard back via OSC 52 is not portable across terminals (many either
* don't implement the query form at all or gate it behind a user prompt),
* so {@link read} only ever reports this namespace's OWN internal buffer —
* never attempts a live OSC 52 query. This means `read()` sees exactly
* what THIS process (or another `tecode.clipboard.write` caller) most
* recently wrote, not necessarily whatever the OS clipboard currently
* holds if something else changed it in between.
*/
export interface ClipboardNamespace {
/**
* The clipboard's current internal buffer contents (this namespace's
* TSDoc's "OSC 52 is write-only" note) — `""` when nothing has been
* copied/cut yet this session. Always resolves; never rejects.
*/
read(): Promise<string>;
/**
* Store `text` as the clipboard's new internal buffer contents, and
* (when system-clipboard sync is enabled and the host terminal
* supports it) write it through to the terminal's OWN clipboard via OSC
* 52. Always resolves once the internal buffer is updated — an OSC 52
* write failure is logged and swallowed, never surfaced as a rejection
* (this namespace's TSDoc).
*/
write(text: string): Promise<void>;
}

/* ------------------------------------------------------------------ */
/* Tecode — the aggregate namespace object */
/* ------------------------------------------------------------------ */
Expand All@@ -472,4 +527,5 @@ export interface Tecode {
context: ContextNamespace;
languages: LanguagesNamespace;
themes: ThemesNamespace;
clipboard: ClipboardNamespace;
Comment thread
goofmint marked this conversation as resolved.
}
1 change: 1 addition & 0 deletions packages/builtin/command-palette/index.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -136,6 +136,7 @@ function createFakeApi(tree: FakeTree, rootUri: Uri | undefined = "file:///works
},
languages: undefined as never,
themes: undefined as never,
clipboard: undefined as never,
};

return {
Expand Down
129 changes: 129 additions & 0 deletions packages/builtin/editor-core/clipboard.test.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
import { describe, expect, test } from "bun:test";
import type { Position, Selection } from "@tecode/api";
import type { LineReader } from "./movement";
import { buildClipboardText, buildCutResult, buildPasteResult } from "./clipboard";
import { collapsedSelection } from "./selectionMerge";

function pos(line: number, character: number): Position {
return { line, character };
}

function cursorAt(line: number, character: number): Selection {
return collapsedSelection(pos(line, character));
}

function selectionOf(startLine: number, startChar: number, endLine: number, endChar: number): Selection {
const start = pos(startLine, startChar);
const end = pos(endLine, endChar);
return { start, end, anchor: start, active: end };
}

function reversedSelectionOf(startLine: number, startChar: number, endLine: number, endChar: number): Selection {
const start = pos(startLine, startChar);
const end = pos(endLine, endChar);
return { start, end, anchor: end, active: start };
}

function reader(lines: string[]): LineReader {
return { getLine: (n) => lines[n] ?? "", lineCount: lines.length };
}

describe("buildClipboardText (Issue #91)", () => {
test("empty selections array: \"\"", () => {
expect(buildClipboardText(reader(["abc"]), [])).toBe("");
});

test("a single collapsed cursor: \"\" (nothing selected)", () => {
expect(buildClipboardText(reader(["abc"]), [cursorAt(0, 1)])).toBe("");
});

test("a single non-collapsed selection: its own text", () => {
const text = buildClipboardText(reader(["hello world"]), [selectionOf(0, 6, 0, 11)]);
expect(text).toBe("world");
});

test("a selection spanning multiple lines includes the real newline(s) in between", () => {
const text = buildClipboardText(reader(["abc", "def", "ghi"]), [selectionOf(0, 1, 2, 2)]);
expect(text).toBe("bc\ndef\ngh");
});

test("multiple cursors: each selection's own text, joined by \\n, in selection order", () => {
const text = buildClipboardText(reader(["foo bar", "baz qux"]), [
selectionOf(0, 0, 0, 3),
selectionOf(1, 4, 1, 7),
]);
expect(text).toBe("foo\nqux");
});

test("direction (forward vs backward selection) does not change the copied text", () => {
const forward = buildClipboardText(reader(["abcdef"]), [selectionOf(0, 1, 0, 4)]);
const backward = buildClipboardText(reader(["abcdef"]), [reversedSelectionOf(0, 1, 0, 4)]);
expect(forward).toBe("bcd");
expect(backward).toBe("bcd");
});
});

describe("buildCutResult (Issue #91)", () => {
test("a collapsed cursor: no edit, unchanged position, empty clipboard text", () => {
const result = buildCutResult(reader(["abc"]), [cursorAt(0, 1)]);
expect(result.text).toBe("");
expect(result.edits).toHaveLength(0);
expect(result.selections).toEqual([cursorAt(0, 1)]);
});

test("a single non-collapsed selection: deletes the range, collapses the cursor to the start, copies the cut text", () => {
const result = buildCutResult(reader(["hello world"]), [selectionOf(0, 6, 0, 11)]);
expect(result.text).toBe("world");
expect(result.edits).toEqual([{ range: { start: pos(0, 6), end: pos(0, 11) }, newText: "" }]);
expect(result.selections).toEqual([cursorAt(0, 6)]);
});

test("multiple cursors: only non-collapsed selections produce edits; the batch is ONE edits array, both cursors' text is still copied", () => {
const result = buildCutResult(reader(["aaa bbb ccc"]), [
selectionOf(0, 0, 0, 3), // "aaa"
cursorAt(0, 5), // collapsed — nothing to delete
selectionOf(0, 8, 0, 11), // "ccc"
]);
expect(result.text).toBe("aaa\n\nccc");
expect(result.edits).toHaveLength(2); // only the two non-collapsed selections
});

test("a backward (reversed anchor/active) selection still cuts correctly and collapses to its start", () => {
const result = buildCutResult(reader(["abcdef"]), [reversedSelectionOf(0, 1, 0, 4)]);
expect(result.text).toBe("bcd");
expect(result.selections).toEqual([cursorAt(0, 1)]);
});
});

describe("buildPasteResult (Issue #91)", () => {
test("a single collapsed cursor: inserts the pasted text, caret lands after it", () => {
const result = buildPasteResult([cursorAt(0, 1)], "XY");
expect(result.edits).toEqual([{ range: { start: pos(0, 1), end: pos(0, 1) }, newText: "XY" }]);
expect(result.selections).toEqual([cursorAt(0, 3)]);
});

test("a non-collapsed selection is replaced wholesale, caret lands at the end of the pasted text", () => {
const result = buildPasteResult([selectionOf(0, 1, 0, 4)], "Z");
expect(result.edits).toEqual([{ range: { start: pos(0, 1), end: pos(0, 4) }, newText: "Z" }]);
expect(result.selections).toEqual([cursorAt(0, 2)]);
});

test("a backward selection is still replaced correctly, not from the wrong end", () => {
const result = buildPasteResult([reversedSelectionOf(0, 1, 0, 4)], "Z");
expect(result.selections).toEqual([cursorAt(0, 2)]);
});

test("multi-line pasted text at a single cursor lands the caret on the pasted text's own last line", () => {
// Regression coverage for the exact class of bug `positionTransform.ts`
// (both `@tecode/core`'s and this package's own copy) had to get right
// for a multi-line replacement whose edit does not start at column 0.
const result = buildPasteResult([cursorAt(0, 1)], "line1\nline2\nline3");
expect(result.selections).toEqual([cursorAt(2, 5)]); // "line3".length
});

test("two cursors on the same line: the second cursor's position accounts for the first's own paste", () => {
const result = buildPasteResult([cursorAt(0, 2), cursorAt(0, 5)], "ab");
expect(result.edits).toHaveLength(2);
expect(result.selections).toEqual([cursorAt(0, 4), cursorAt(0, 9)]);
});
});
114 changes: 114 additions & 0 deletions packages/builtin/editor-core/clipboard.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
/**
* Pure per-selection logic for `editor-core`'s clipboard commands (Issue
* #91): `editor.action.clipboardCopy`/`clipboardCut`/`clipboardPaste`.
* Copy/cut read the text under every selection (joined by `"\n"` across
* multiple cursors — a multi-cursor copy/cut's clipboard text has one line
* per cursor, in selection order); cut also builds the delete-the-selection
* edit batch, reusing `editing.ts`'s `buildEditBatch` exactly like
* `deleteLeft`/`deleteRight` do. Paste reuses `editing.ts`'s own
* `buildInsertEdit` — a paste and a Tab/Enter keystroke both "insert this
* text, replacing any active selection" (that function's own TSDoc).
*
* No `@tecode/core` import (the ESLint layering rule); reads through a
* {@link LineReader}, matching `movement.ts`/`multiCursor.ts`.
*/

import type { Position, Selection, TextEdit } from "@tecode/api";
import { buildEditBatch, buildInsertEdit, type EditBatch } from "./editing";
import type { LineReader } from "./movement";
import { comparePositions } from "./positionTransform";

/** Whether `selection` is a plain collapsed cursor (no selected range) —
* duplicated locally (`editing.ts`'s own private `isCollapsed`, `movement.
* ts`'s `multiCursor.ts`'s own copies) rather than exported/shared, matching
* this package's existing convention for this one-line check. */
function isCollapsed(selection: Selection): boolean {
return comparePositions(selection.start, selection.end) === 0;
}

/** Join every line of the document into one string with the offset each
* line starts at, and the inverse offset→position lookup — duplicated from
* `multiCursor.ts`'s own private `readBuffer`/`toOffset` (not exported
* there) rather than imported, for the same "no cross-module coupling
* beyond what's actually shared" reasoning `multiCursor.ts`'s own TSDoc
* gives for not depending on `movement.ts`. */
function readBuffer(reader: LineReader): { text: string; lineStarts: number[] } {
const lines: string[] = [];
const lineStarts: number[] = [];
let offset = 0;
for (let i = 0; i < reader.lineCount; i++) {
const line = reader.getLine(i);
lineStarts.push(offset);
lines.push(line);
offset += line.length + 1;
}
return { text: lines.join("\n"), lineStarts };
}

/** Convert `position` to an offset into {@link readBuffer}'s `text`. */
function toOffset(position: Position, lineStarts: readonly number[]): number {
return lineStarts[position.line]! + position.character;
}

/**
* The text `editor.action.clipboardCopy`/`clipboardCut` write to the
* clipboard (Issue #91): each selection's own text (`""` for a collapsed
* cursor with nothing selected), joined with `"\n"` across multiple
* cursors, in `selections`' own order. `""` for an empty `selections`
* array (the no-active-editor/no-op case — `index.ts`'s command handlers
* already guard on this before ever calling here, matching every other
* command in this package's convention).
*/
export function buildClipboardText(reader: LineReader, selections: readonly Selection[]): string {
if (selections.length === 0) return "";
const { text, lineStarts } = readBuffer(reader);
return selections
.map((selection) => text.slice(toOffset(selection.start, lineStarts), toOffset(selection.end, lineStarts)))
.join("\n");
}

/** Build the edit that deletes `selection`'s own range for
* `editor.action.clipboardCut` — `undefined` for a collapsed selection
* (nothing to delete for that cursor, matching `buildBackspaceEdit`/
* `buildDeleteEdit`'s own "boundary no-op" convention in `editing.ts`,
* rather than deleting a whole line the way some editors do with nothing
* selected — Issue #91 does not ask for that). */
function buildCutRangeEdit(selection: Selection): TextEdit | undefined {
if (isCollapsed(selection)) return undefined;
return { range: { start: selection.start, end: selection.end }, newText: "" };
}

/** What {@link buildCutResult} produces: the clipboard text (this module's
* {@link buildClipboardText}) plus the delete edit batch (`editing.ts`'s
* `EditBatch` shape — `edits` to apply, `selections` the resulting
* collapsed cursors). */
export interface CutResult extends EditBatch {
text: string;
}

/**
* Build `editor.action.clipboardCut`'s full result (Issue #91): the text to
* write to the clipboard (every selection's own text, even a collapsed
* one's `""`, so a cut always copies exactly what a copy of the same
* selections would have), and the edit batch that deletes each
* NON-collapsed selection's range — reusing `editing.ts`'s `buildEditBatch`
* exactly like `deleteLeft`/`deleteRight` do (this module's TSDoc).
*/
export function buildCutResult(reader: LineReader, selections: readonly Selection[]): CutResult {
const text = buildClipboardText(reader, selections);
const { edits, selections: newSelections } = buildEditBatch(selections, buildCutRangeEdit);
return { text, edits, selections: newSelections };
}

/**
* Build `editor.action.clipboardPaste`'s edit batch (Issue #91): insert
* `text` at every selection, replacing its range if it has one — reusing
* `editing.ts`'s own `buildInsertEdit(selection, text)` (the exact
* "insert, replacing any active selection" shape Tab/Enter already use)
* through `buildEditBatch`, so a multi-line/multi-cursor paste is one
* batch, one `applyEdits` call, one undo step, exactly like every other
* `editor-core` editing command.
*/
export function buildPasteResult(selections: readonly Selection[], text: string): EditBatch {
return buildEditBatch(selections, (selection) => buildInsertEdit(selection, text));
}
Loading
Loading