Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

feat: rename symbols with LSP (#4159)

Myles Scolnick68064ec83bd5
diff --git a/frontend/package.json b/frontend/package.json
index 82d7e8340d..4266630eb1 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -42,7 +42,7 @@
"@lezer/python": "^1.1.16",
"@marimo-team/codemirror-ai": "^0.1.9",
"@marimo-team/marimo-api": "file:../openapi",
- "@marimo-team/codemirror-languageserver": "^1.13.6",
+ "@marimo-team/codemirror-languageserver": "^1.13.8",
"@marimo-team/react-slotz": "^0.1.8",
"@open-rpc/client-js": "^1.8.1",
"@paralleldrive/cuid2": "^2.2.2",
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index 364a63ff17..c8e329f948 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -103,8 +103,8 @@ importers:
specifier: ^0.1.9
version: 0.1.9(@codemirror/[email protected])(@codemirror/[email protected])
'@marimo-team/codemirror-languageserver':
- specifier: ^1.13.6
- version: 1.13.6(@codemirror/[email protected])(@codemirror/[email protected])
+ specifier: ^1.13.8
+ version: 1.13.8(@codemirror/[email protected])(@codemirror/[email protected])
'@marimo-team/marimo-api':
specifier: file:../openapi
version: file:../openapi
@@ -1546,8 +1546,8 @@ packages:
'@codemirror/state': ^6
'@codemirror/view': ^6
- '@marimo-team/[email protected]':
- resolution: {integrity: sha512-53iaZY/1mk+WspRvzesECdZSP/YJBCCySnHJC+MNsUa4CyxizpiRogyyZ26/Xab2wMDWsAimtxhEE+wOPnd0+w==}
+ '@marimo-team/[email protected]':
+ resolution: {integrity: sha512-EoDdfLZXl/a7MQOT/1q6LKmDPb67PkZ2HrMdQA554sX1R4mkoS6z/DpXzAZmCrhQb6J1PA7OrXqW0Qb+LszJxg==}
peerDependencies:
'@codemirror/state': ^6
'@codemirror/view': ^6
@@ -10225,7 +10225,7 @@ snapshots:
'@codemirror/state': 6.5.2
'@codemirror/view': 6.36.4
- '@marimo-team/[email protected](@codemirror/[email protected])(@codemirror/[email protected])':
+ '@marimo-team/[email protected](@codemirror/[email protected])(@codemirror/[email protected])':
dependencies:
'@codemirror/autocomplete': 6.18.6
'@codemirror/lint': 6.8.4
diff --git a/frontend/src/core/codemirror/lsp/__tests__/notebook-lsp.test.ts b/frontend/src/core/codemirror/lsp/__tests__/notebook-lsp.test.ts
index 6a819f83f6..1757e0f160 100644
--- a/frontend/src/core/codemirror/lsp/__tests__/notebook-lsp.test.ts
+++ b/frontend/src/core/codemirror/lsp/__tests__/notebook-lsp.test.ts
@@ -6,6 +6,11 @@ import * as LSP from "vscode-languageserver-protocol";
import { NotebookLanguageServerClient } from "../notebook-lsp";
import { CellDocumentUri, type ILanguageServerClient } from "../types";
import type { CellId } from "@/core/cells/ids";
+import { EditorView } from "@codemirror/view";
+import {
+ type LanguageServerClient,
+ languageServerWithTransport,
+} from "@marimo-team/codemirror-languageserver";
const Cells = {
cell1: "cell1" as CellId,
@@ -130,25 +135,69 @@ describe("createNotebookLens", () => {
const transformed = lens.transformPosition(pos, Cells.cell2);
expect(transformed.line).toBe(3);
});
+
+ it("should clip range and text to cell boundaries", () => {
+ const cellIds: CellId[] = [Cells.cell1, Cells.cell2, Cells.cell3];
+ const codes: Record<CellId, string> = {
+ [Cells.cell1]: "line1\nline2",
+ [Cells.cell2]: "line3\nline4\nline5",
+ [Cells.cell3]: "line6\nline7",
+ };
+ const lens = createNotebookLens(cellIds, codes);
+
+ // Assume the line length does not change
+ const newText = "a\nb\nc\nd\ne\nf\ng";
+
+ const edits = lens.getEditsForNewText(newText);
+
+ expect(edits).toMatchInlineSnapshot(`
+ [
+ {
+ "cellId": "cell1",
+ "text": "a
+ b",
+ },
+ {
+ "cellId": "cell2",
+ "text": "c
+ d
+ e",
+ },
+ {
+ "cellId": "cell3",
+ "text": "f
+ g",
+ },
+ ]
+ `);
+ });
});
describe("NotebookLanguageServerClient", () => {
+ let plugins: any[] = [];
let mockClient: Mocked<ILanguageServerClient>;
let notebookClient: NotebookLanguageServerClient;
beforeEach(() => {
+ plugins = [];
mockClient = {
+ plugins,
ready: true,
capabilities: {},
initializePromise: Promise.resolve(),
initialize: vi.fn(),
close: vi.fn(),
- detachPlugin: vi.fn(),
- attachPlugin: vi.fn(),
+ detachPlugin: vi.fn().mockImplementation((plugin) => {
+ plugins = plugins.filter((p) => p !== plugin);
+ }),
+ attachPlugin: vi.fn().mockImplementation((plugin) => {
+ plugins.push(plugin);
+ }),
textDocumentDidOpen: vi.fn(),
textDocumentDidChange: vi.fn(),
textDocumentHover: vi.fn(),
textDocumentCompletion: vi.fn(),
+ textDocumentRename: vi.fn(),
processNotification: vi.fn(),
notify: vi.fn(),
request: vi.fn(),
@@ -267,6 +316,259 @@ describe("NotebookLanguageServerClient", () => {
});
});
+ describe("textDocumentRename", () => {
+ it("should transform rename position and apply edits to editor views", async () => {
+ const props = {
+ workspaceFolders: null,
+ capabilities: {
+ textDocument: {
+ rename: {
+ prepareSupport: true,
+ },
+ },
+ },
+ languageId: "python",
+ transport: {
+ sendData: vi.fn(),
+ subscribe: vi.fn(),
+ connect: vi.fn(),
+ transportRequestManager: {
+ send: vi.fn(),
+ },
+ } as any,
+ };
+
+ // Setup mock plugins with editor views
+ const mockView1 = new EditorView({
+ doc: "# this is a comment",
+ extensions: [
+ languageServerWithTransport({
+ client: mockClient as unknown as LanguageServerClient,
+ rootUri: "file:///",
+ documentUri: CellDocumentUri.of(Cells.cell1),
+ ...props,
+ }),
+ ],
+ });
+ expect(mockView1.state.doc.toString()).toBe("# this is a comment");
+
+ const mockView2 = new EditorView({
+ doc: "import math\nimport numpy",
+ extensions: [
+ languageServerWithTransport({
+ client: mockClient as unknown as LanguageServerClient,
+ rootUri: "file:///",
+ documentUri: CellDocumentUri.of(Cells.cell2),
+ ...props,
+ }),
+ ],
+ });
+ expect(mockView2.state.doc.toString()).toBe("import math\nimport numpy");
+
+ const mockView3 = new EditorView({
+ doc: "print(math.sqrt(4))",
+ extensions: [
+ languageServerWithTransport({
+ client: mockClient as unknown as LanguageServerClient,
+ rootUri: "file:///",
+ documentUri: CellDocumentUri.of(Cells.cell3),
+ ...props,
+ }),
+ ],
+ });
+ expect(mockView3.state.doc.toString()).toBe("print(math.sqrt(4))");
+
+ // Setup rename params
+ const renameParams: LSP.RenameParams = {
+ textDocument: { uri: CellDocumentUri.of(Cells.cell2) },
+ position: { line: 0, character: 7 },
+ newName: "renamed_math",
+ };
+
+ // Open a document first to set up the lens
+ await notebookClient.textDocumentDidOpen({
+ textDocument: {
+ uri: CellDocumentUri.of(Cells.cell2),
+ languageId: "python",
+ version: 1,
+ text: "import math\nimport numpy",
+ },
+ });
+
+ // Mock the response from the language server
+ const mockRenameResponse: LSP.WorkspaceEdit = {
+ documentChanges: [
+ {
+ textDocument: {
+ uri: "file:///__marimo_notebook__.py",
+ version: 1,
+ },
+ edits: [
+ {
+ range: {
+ start: { line: 0, character: 0 },
+ end: { line: 5, character: 0 },
+ },
+ newText:
+ "# this is a comment\nimport renamed_math\nimport numpy\nprint(renamed_math.sqrt(4))",
+ },
+ ],
+ },
+ ],
+ };
+
+ mockClient.textDocumentRename = vi
+ .fn()
+ .mockResolvedValue(mockRenameResponse);
+
+ // Call rename
+ const result = await notebookClient.textDocumentRename(renameParams);
+ expect(result).toMatchInlineSnapshot(`
+ {
+ "documentChanges": [
+ {
+ "edits": [],
+ "textDocument": {
+ "uri": "file:///cell2",
+ "version": 0,
+ },
+ },
+ ],
+ }
+ `);
+
+ expect(mockView2.state.doc.toString()).toBe(
+ "import renamed_math\nimport numpy",
+ );
+ expect(mockView1.state.doc.toString()).toBe("# this is a comment");
+ });
+
+ it("should return null for invalid cell document URIs", async () => {
+ const invalidParams: LSP.RenameParams = {
+ textDocument: { uri: "file:///invalid.py" },
+ position: { line: 0, character: 0 },
+ newName: "new_name",
+ };
+
+ const result = await notebookClient.textDocumentRename(invalidParams);
+ expect(result).toBeNull();
+ });
+
+ it("should return null when no lens is found", async () => {
+ const renameParams: LSP.RenameParams = {
+ textDocument: { uri: CellDocumentUri.of(Cells.cell1) },
+ position: { line: 0, character: 0 },
+ newName: "new_name",
+ };
+
+ const result = await notebookClient.textDocumentRename(renameParams);
+ expect(result).toBeNull();
+ });
+
+ it("should return the original response when edits are not as expected", async () => {
+ // Setup response with multiple edits
+ const multiEditResponse: LSP.WorkspaceEdit = {
+ documentChanges: [
+ {
+ textDocument: {
+ uri: "file:///__marimo_notebook__.py",
+ version: 1,
+ },
+ edits: [
+ {
+ range: {
+ start: { line: 0, character: 0 },
+ end: { line: 0, character: 5 },
+ },
+ newText: "edit1",
+ },
+ {
+ range: {
+ start: { line: 1, character: 0 },
+ end: { line: 1, character: 5 },
+ },
+ newText: "edit2",
+ },
+ ],
+ },
+ ],
+ };
+
+ mockClient.textDocumentRename = vi
+ .fn()
+ .mockResolvedValue(multiEditResponse);
+
+ // Open a document first to set up the lens
+ await notebookClient.textDocumentDidOpen({
+ textDocument: {
+ uri: CellDocumentUri.of(Cells.cell1),
+ languageId: "python",
+ version: 1,
+ text: "test",
+ },
+ });
+
+ const renameParams: LSP.RenameParams = {
+ textDocument: { uri: CellDocumentUri.of(Cells.cell1) },
+ position: { line: 0, character: 0 },
+ newName: "new_name",
+ };
+
+ const result = await notebookClient.textDocumentRename(renameParams);
+
+ // Should return the original response when edits don't meet expectations
+ expect(result).toEqual(multiEditResponse);
+ });
+
+ it("should return the original response when edits don't have newText property", async () => {
+ // Setup response with an edit that doesn't have newText
+ const invalidEditResponse: LSP.WorkspaceEdit = {
+ documentChanges: [
+ {
+ textDocument: {
+ uri: "file:///__marimo_notebook__.py",
+ version: 1,
+ },
+ edits: [
+ {
+ range: {
+ start: { line: 0, character: 0 },
+ end: { line: 0, character: 5 },
+ },
+ // Missing newText property
+ } as any,
+ ],
+ },
+ ],
+ };
+
+ mockClient.textDocumentRename = vi
+ .fn()
+ .mockResolvedValue(invalidEditResponse);
+
+ // Open a document first to set up the lens
+ await notebookClient.textDocumentDidOpen({
+ textDocument: {
+ uri: CellDocumentUri.of(Cells.cell1),
+ languageId: "python",
+ version: 1,
+ text: "test",
+ },
+ });
+
+ const renameParams: LSP.RenameParams = {
+ textDocument: { uri: CellDocumentUri.of(Cells.cell1) },
+ position: { line: 0, character: 0 },
+ newName: "new_name",
+ };
+
+ const result = await notebookClient.textDocumentRename(renameParams);
+
+ // Should return the original response when edits don't have proper properties
+ expect(result).toEqual(invalidEditResponse);
+ });
+ });
+
describe("diagnostics handling", () => {
it("should transform diagnostic ranges and filter out-of-bounds diagnostics", async () => {
// Mock processNotification to capture the transformed diagnostics
diff --git a/frontend/src/core/codemirror/lsp/lens.ts b/frontend/src/core/codemirror/lsp/lens.ts
index 24c284305d..2f9313c5a1 100644
--- a/frontend/src/core/codemirror/lsp/lens.ts
+++ b/frontend/src/core/codemirror/lsp/lens.ts
@@ -1,5 +1,6 @@
/* Copyright 2024 Marimo. All rights reserved. */
import type { CellId } from "@/core/cells/ids";
+import { Objects } from "@/utils/objects";
import type * as LSP from "vscode-languageserver-protocol";
export interface NotebookLens {
@@ -18,6 +19,12 @@ export interface NotebookLens {
/** Transform a position from notebook coordinates back to cell coordinates */
reversePosition: (position: LSP.Position, cellId: CellId) => LSP.Position;
+ /** Clip a range to the given cell */
+ getEditsForNewText: (newText: string) => Array<{
+ cellId: CellId;
+ text: string;
+ }>;
+
/** Check if a range falls within the given cell */
isInRange: (range: LSP.Range, cellId: CellId) => boolean;
}
@@ -43,10 +50,12 @@ export function createNotebookLens(
return cellLineOffsets.get(cellId) || 0;
}
+ const mergedText = Object.values(codes).join("\n");
+
return {
cellIds: sortedCellIds,
- mergedText: Object.values(codes).join("\n"),
+ mergedText,
transformRange: (range: LSP.Range, cellId: CellId) =>
shiftRange(range, getCurrentLineOffset(cellId)),
@@ -62,6 +71,37 @@ export function createNotebookLens(
return startLine >= 0 && endLine < cellLines;
},
+ getEditsForNewText: (newText: string) => {
+ const newLines = newText.split("\n");
+ const oldLines = mergedText.split("\n");
+
+ if (newLines.length !== oldLines.length) {
+ throw new Error("Cannot apply rename when there are new lines");
+ }
+
+ const edits: Array<{
+ cellId: CellId;
+ text: string;
+ }> = [];
+
+ for (const [cellId, code] of Objects.entries(codes)) {
+ if (!cellLineOffsets.has(cellId)) {
+ continue;
+ }
+ const offset = cellLineOffsets.get(cellId) || 0;
+
+ const numCellLines = code.split("\n").length;
+ const newCellLines = newLines.slice(offset, offset + numCellLines);
+
+ edits.push({
+ cellId,
+ text: newCellLines.join("\n"),
+ });
+ }
+
+ return edits;
+ },
+
transformPosition: (position: LSP.Position, cellId: CellId) =>
shiftPosition(position, getCurrentLineOffset(cellId)),
diff --git a/frontend/src/core/codemirror/lsp/notebook-lsp.ts b/frontend/src/core/codemirror/lsp/notebook-lsp.ts
index 2b75027d2b..e8386a7315 100644
--- a/frontend/src/core/codemirror/lsp/notebook-lsp.ts
+++ b/frontend/src/core/codemirror/lsp/notebook-lsp.ts
@@ -8,6 +8,7 @@ import { Logger } from "@/utils/Logger";
import { LRUCache } from "@/utils/lru";
import type { CellId } from "@/core/cells/ids";
import { getFilenameFromDOM } from "@/core/dom/htmlUtils";
+import type { EditorView } from "@codemirror/view";
export class NotebookLanguageServerClient implements ILanguageServerClient {
public readonly documentUri: LSP.DocumentUri;
@@ -50,12 +51,14 @@ export class NotebookLanguageServerClient implements ILanguageServerClient {
});
});
}
+
textDocumentDefinition(
params: LSP.DefinitionParams,
): Promise<LSP.Definition | LSP.LocationLink[] | null> {
// Get the cell document URI from the params
const cellDocumentUri = params.textDocument.uri;
if (!CellDocumentUri.is(cellDocumentUri)) {
+ Logger.warn("Invalid cell document URI", cellDocumentUri);
return Promise.resolve(null);
}
@@ -93,10 +96,117 @@ export class NotebookLanguageServerClient implements ILanguageServerClient {
return this.client.textDocumentCodeAction(params);
}
- textDocumentRename(
+ /**
+ * HACK
+ * This whole function is a hack to work around the fact that we don't have
+ * a great way to map the edits back to the appropriate LSP view plugin.
+ *
+ * Instead, we parse out the new text from the response and then update the
+ * code in the plugins manually, instead of using the LSP.
+ */
+ async textDocumentRename(
params: LSP.RenameParams,
): Promise<LSP.WorkspaceEdit | null> {
- return this.client.textDocumentRename(params);
+ // Get the cell document URI from the params
+ const cellDocumentUri = params.textDocument.uri;
+ if (!CellDocumentUri.is(cellDocumentUri)) {
+ Logger.warn("Invalid cell document URI", cellDocumentUri);
+ return null;
+ }
+
+ const cellId = CellDocumentUri.parse(cellDocumentUri);
+
+ // Find the latest lens
+ const latestVersion = [...this.versionToCellNumberAndVersion.keys()].at(-1);
+ if (latestVersion === undefined) {
+ Logger.warn("No lens found for cell", cellDocumentUri);
+ return null;
+ }
+
+ // Use the lens to transform the position
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+ const { lens } = this.versionToCellNumberAndVersion.get(latestVersion)!;
+ const transformedPosition = lens.transformPosition(params.position, cellId);
+
+ // Request
+ const response = await this.client.textDocumentRename({
+ ...params,
+ textDocument: {
+ uri: this.documentUri,
+ },
+ position: transformedPosition,
+ });
+
+ if (!response) {
+ return null;
+ }
+
+ // Get all the edits from the response
+ const edits = response.documentChanges?.flatMap((change) => {
+ if ("edits" in change) {
+ return change.edits;
+ }
+ return [];
+ });
+
+ // Validate its a single edit
+ if (!edits || edits.length !== 1) {
+ Logger.warn("Expected exactly one edit", edits);
+ return response;
+ }
+
+ const edit = edits[0];
+ if (!("newText" in edit)) {
+ Logger.warn("Expected newText in edit", edit);
+ return response;
+ }
+
+ // Get the new text for all the cells (some may be unchanged)
+ const newEdits = lens.getEditsForNewText(edit.newText);
+ const editsToNewCode = new Map(newEdits.map((e) => [e.cellId, e.text]));
+
+ // Update the code in the plugins manually
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ for (const plugin of (this.client as any).plugins) {
+ const documentUri: string = plugin.documentUri;
+ if (!CellDocumentUri.is(documentUri)) {
+ Logger.warn("Invalid cell document URI", documentUri);
+ continue;
+ }
+
+ const cellId = CellDocumentUri.parse(documentUri);
+ const newCode = editsToNewCode.get(cellId);
+ if (!newCode) {
+ Logger.warn("No new code for cell", cellId);
+ continue;
+ }
+
+ const view: EditorView = plugin.view;
+ if (!view) {
+ Logger.warn("No view for plugin", plugin);
+ continue;
+ }
+
+ // Only update if it has changed
+ if (view.state.doc.toString() !== newCode) {
+ view.dispatch({
+ changes: { from: 0, to: view.state.doc.length, insert: newCode },
+ });
+ }
+ }
+
+ return {
+ ...response,
+ documentChanges: [
+ {
+ edits: [],
+ textDocument: {
+ uri: cellDocumentUri,
+ version: 0,
+ },
+ },
+ ],
+ };
}
completionItemResolve(
@@ -105,10 +215,34 @@ export class NotebookLanguageServerClient implements ILanguageServerClient {
return this.client.completionItemResolve(params);
}
- textDocumentPrepareRename(
+ async textDocumentPrepareRename(
params: LSP.PrepareRenameParams,
): Promise<LSP.PrepareRenameResult | null> {
- return this.client.textDocumentPrepareRename(params);
+ // Get the cell document URI from the params
+ const cellDocumentUri = params.textDocument.uri;
+ if (!CellDocumentUri.is(cellDocumentUri)) {
+ Logger.warn("Invalid cell document URI", cellDocumentUri);
+ return null;
+ }
+
+ // Get the latest updated lens
+ const latestVersion = [...this.versionToCellNumberAndVersion.keys()].at(-1);
+ if (!latestVersion) {
+ Logger.warn("No lens found for cell", cellDocumentUri);
+ return null;
+ }
+
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+ const { lens } = this.versionToCellNumberAndVersion.get(latestVersion)!;
+ const cellId = CellDocumentUri.parse(cellDocumentUri);
+
+ return this.client.textDocumentPrepareRename({
+ ...params,
+ textDocument: {
+ uri: this.documentUri,
+ },
+ position: lens.transformPosition(params.position, cellId),
+ });
}
get ready(): boolean {