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.

fix: lsp syncing fixes for hover and completion (#5637)

Myles Scolnickf1c8751e7b28
diff --git a/docs/guides/editor_features/language_server.md b/docs/guides/editor_features/language_server.md
index 07ce635cde..914ffd1239 100644
--- a/docs/guides/editor_features/language_server.md
+++ b/docs/guides/editor_features/language_server.md
@@ -1,14 +1,5 @@
# Language Server Protocol (LSP)
-!!! warning "Experimental Feature"
-
- LSP support in marimo is currently an experimental feature. It may have bugs or performance issues. To enable it add the following to your `pyproject.toml` file:
-
- ```toml title="pyproject.toml"
- [tool.marimo.experimental]
- lsp = true
- ```
-
The marimo editor supports the Language Server Protocol (LSP) to provide enhanced code intelligence features like:
- Code completion
@@ -43,11 +34,6 @@ You may optionally install other `pylsp` plugins.
LSP support can be configured in your `pyproject.toml` file.
-```toml title="pyproject.toml"
-[tool.marimo.experimental]
-lsp = true
-```
-
```toml title="pyproject.toml"
# Language server configuration
diff --git a/frontend/package.json b/frontend/package.json
index ae0ad7a359..9eb07f44bd 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -46,7 +46,7 @@
"@lezer/markdown": "^1.4.3",
"@lezer/python": "^1.1.18",
"@marimo-team/codemirror-ai": "^0.1.11",
- "@marimo-team/codemirror-languageserver": "^1.15.19",
+ "@marimo-team/codemirror-languageserver": "^1.15.23",
"@marimo-team/marimo-api": "file:../openapi",
"@marimo-team/react-slotz": "^0.2.0",
"@mui/material": "^6.4.12",
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index 01a1dd75e7..96cadf52c2 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -115,8 +115,8 @@ importers:
specifier: ^0.1.11
version: 0.1.11(@codemirror/[email protected])(@codemirror/[email protected])
'@marimo-team/codemirror-languageserver':
- specifier: ^1.15.19
- version: 1.15.19(@codemirror/[email protected])(@codemirror/[email protected])
+ specifier: ^1.15.23
+ version: 1.15.23(@codemirror/[email protected])(@codemirror/[email protected])
'@marimo-team/marimo-api':
specifier: file:../openapi
version: file:../openapi
@@ -1623,8 +1623,8 @@ packages:
'@codemirror/state': ^6
'@codemirror/view': ^6
- '@marimo-team/[email protected]':
- resolution: {integrity: sha512-LLozJmWYC+rGqQINpDLcDHY4wxY96d4chmgwjB1DQUbUkCmKJHQS1Im0HgScB5FA289WfkAgQyIC59oYF5+wpw==}
+ '@marimo-team/[email protected]':
+ resolution: {integrity: sha512-96w6/0TJB9aM4cOFdh08LL+2Vd5jDMeUp9Ed5ZJmhrb3CKpXGBs7oUhgia6YE6nIK1IP2ijVSF7kxdMfdetXPA==}
peerDependencies:
'@codemirror/state': ^6
'@codemirror/view': ^6
@@ -10329,7 +10329,7 @@ snapshots:
'@codemirror/state': 6.5.2
'@codemirror/view': 6.38.0
- '@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.5
diff --git a/frontend/src/components/app-config/user-config-form.tsx b/frontend/src/components/app-config/user-config-form.tsx
index 04cc0f8b4f..71ba19af2b 100644
--- a/frontend/src/components/app-config/user-config-form.tsx
+++ b/frontend/src/components/app-config/user-config-form.tsx
@@ -427,6 +427,18 @@ export const UserConfigForm: React.FC = () => {
/>
</SettingGroup>
<SettingGroup title="Language Servers">
+ <FormDescription>
+ See the{" "}
+ <ExternalLink href="https://docs.marimo.io/guides/editor_features/language_server/">
+ docs
+ </ExternalLink>{" "}
+ for more information about language server support.
+ </FormDescription>
+ <FormDescription>
+ <strong>Note:</strong> When using multiple language servers,
+ different features may conflict.
+ </FormDescription>
+
<FormField
control={form.control}
name="language_servers.pylsp.enabled"
@@ -439,7 +451,7 @@ export const UserConfigForm: React.FC = () => {
</Badge>
Python Language Server (
<ExternalLink href="https://github.com/python-lsp/python-lsp-server">
- pylsp
+ docs
</ExternalLink>
)
</FormLabel>
@@ -482,7 +494,7 @@ export const UserConfigForm: React.FC = () => {
</Badge>
ty (
<ExternalLink href="https://github.com/astral-sh/ty">
- ty
+ docs
</ExternalLink>
)
</FormLabel>
@@ -512,14 +524,6 @@ export const UserConfigForm: React.FC = () => {
</div>
)}
/>
- <FormDescription>
- See the{" "}
- <ExternalLink href="https://docs.marimo.io/guides/editor_features/language_server/">
- docs
- </ExternalLink>{" "}
- for more information about language server support.
- </FormDescription>
-
<FormField
control={form.control}
name="diagnostics.enabled"
diff --git a/frontend/src/components/editor/columns/storage.ts b/frontend/src/components/editor/columns/storage.ts
index ed662d36e3..7ff03db118 100644
--- a/frontend/src/components/editor/columns/storage.ts
+++ b/frontend/src/components/editor/columns/storage.ts
@@ -17,7 +17,9 @@ function initialState(): ColumnSizes {
const storage = new NotebookScopedLocalStorage<ColumnSizes>(
BASE_KEY,
z.object({
- widths: z.array(z.union([z.number(), z.literal("contentWidth")])),
+ widths: z.array(
+ z.union([z.number(), z.literal("contentWidth")]).default("contentWidth"),
+ ),
}),
initialState,
);
diff --git a/frontend/src/core/codemirror/copilot/__tests__/getCode.test.ts b/frontend/src/core/codemirror/copilot/__tests__/getCodes.test.ts
similarity index 94%
rename from frontend/src/core/codemirror/copilot/__tests__/getCode.test.ts
rename to frontend/src/core/codemirror/copilot/__tests__/getCodes.test.ts
index 9c3446a3b0..2e156431ff 100644
--- a/frontend/src/core/codemirror/copilot/__tests__/getCode.test.ts
+++ b/frontend/src/core/codemirror/copilot/__tests__/getCodes.test.ts
@@ -67,12 +67,7 @@ function createMockEditorView(code: string) {
describe("getTopologicalCellIds", () => {
it("should return topologically sorted cell IDs", () => {
// Setup mock data
- store.set(notebookAtom, {
- ...initialNotebookState(),
- cellIds: MultiColumn.from([
- [Cells.cell1, Cells.cell2, Cells.cell3, Cells.cell4],
- ]),
- });
+ const cellIds = [Cells.cell1, Cells.cell2, Cells.cell3, Cells.cell4];
const variables: Variables = {
[Variables.var1]: {
name: Variables.var1,
@@ -90,10 +85,8 @@ describe("getTopologicalCellIds", () => {
usedBy: [],
},
};
- store.set(variablesAtom, variables);
- // Call the function
- const result = getTopologicalCellIds();
+ const result = getTopologicalCellIds(cellIds, variables);
// Assert the result
expect(result).toEqual(["cell1", "cell2", "cell3", "cell4"]);
diff --git a/frontend/src/core/codemirror/copilot/getCodes.ts b/frontend/src/core/codemirror/copilot/getCodes.ts
index d5b7189936..1fa38e2a02 100644
--- a/frontend/src/core/codemirror/copilot/getCodes.ts
+++ b/frontend/src/core/codemirror/copilot/getCodes.ts
@@ -1,8 +1,10 @@
/* Copyright 2024 Marimo. All rights reserved. */
+
+import { atom } from "jotai";
import { getAllEditorViews, notebookAtom } from "@/core/cells/cells";
import type { CellId } from "@/core/cells/ids";
-import { store } from "@/core/state/jotai";
import { variablesAtom } from "@/core/variables/state";
+import type { Variables } from "@/core/variables/types";
import { Objects } from "@/utils/objects";
import { getEditorCodeAsPython } from "../language/utils";
@@ -38,11 +40,36 @@ export function getOtherCellsCode(otherCode: string) {
return codes;
}
-export function getTopologicalCellIds() {
- const notebook = store.get(notebookAtom);
- const variables = store.get(variablesAtom);
- const cellIds = notebook.cellIds.inOrderIds;
+const notebookCellCodes = atom((get) => {
+ const notebook = get(notebookAtom);
+ const codes = Objects.fromEntries(
+ notebook.cellIds.inOrderIds.map((id) => {
+ const handle = notebook.cellHandles[id];
+ return [
+ id,
+ handle?.current ? getEditorCodeAsPython(handle.current.editorView) : "",
+ ];
+ }),
+ );
+ return codes;
+});
+const inOrderCellIdsAtom = atom((get) => {
+ const notebook = get(notebookAtom);
+ return notebook.cellIds.inOrderIds;
+});
+const topologicalCellIdsAtom = atom((get) => {
+ const cellIds = get(inOrderCellIdsAtom);
+ const variables = get(variablesAtom);
+ return getTopologicalCellIds(cellIds, variables);
+});
+
+export const topologicalCodesAtom = atom((get) => {
+ const sortedCellIds = get(topologicalCellIdsAtom);
+ const codes = get(notebookCellCodes);
+ return { cellIds: sortedCellIds, codes };
+});
+export function getTopologicalCellIds(cellIds: CellId[], variables: Variables) {
// Build adjacency list
const adjacency = new Map<CellId, CellId[]>();
cellIds.forEach((id) => adjacency.set(id, []));
@@ -96,22 +123,3 @@ export function getTopologicalCellIds() {
return sorted;
}
-
-export function getTopologicalCodes(): {
- cellIds: CellId[];
- codes: Record<CellId, string>;
-} {
- const cellIds = getTopologicalCellIds();
- const notebook = store.get(notebookAtom);
- const codes = Objects.fromEntries(
- cellIds.map((id) => {
- const handle = notebook.cellHandles[id];
- return [
- id,
- handle?.current ? getEditorCodeAsPython(handle.current.editorView) : "",
- ];
- }),
- );
-
- return { cellIds, codes };
-}
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 fb29199102..02bed04796 100644
--- a/frontend/src/core/codemirror/lsp/__tests__/notebook-lsp.test.ts
+++ b/frontend/src/core/codemirror/lsp/__tests__/notebook-lsp.test.ts
@@ -9,6 +9,8 @@ import {
import { beforeEach, describe, expect, it, type Mocked, vi } from "vitest";
import * as LSP from "vscode-languageserver-protocol";
import type { CellId } from "@/core/cells/ids";
+import { store } from "@/core/state/jotai";
+import { topologicalCodesAtom } from "../../copilot/getCodes";
import { createNotebookLens } from "../lens";
import { NotebookLanguageServerClient } from "../notebook-lsp";
import { CellDocumentUri, type ILanguageServerClient } from "../types";
@@ -204,14 +206,22 @@ describe("NotebookLanguageServerClient", () => {
request: vi.fn(),
} as unknown as Mocked<ILanguageServerClient>;
notebookClient = new NotebookLanguageServerClient(mockClient, {});
- (notebookClient as any).getNotebookCode = vi.fn().mockReturnValue({
- cellIds: [Cells.cell1, Cells.cell2, Cells.cell3],
- codes: {
- [Cells.cell1]: "# this is a comment",
- [Cells.cell2]: "import math\nimport numpy",
- [Cells.cell3]: "print(math.sqrt(4))",
- },
+
+ // Mock the atom instead of the instance method
+ vi.spyOn(store, "get").mockImplementation((atom) => {
+ if (atom === topologicalCodesAtom) {
+ return {
+ cellIds: [Cells.cell1, Cells.cell2, Cells.cell3],
+ codes: {
+ [Cells.cell1]: "# this is a comment",
+ [Cells.cell2]: "import math\nimport numpy",
+ [Cells.cell3]: "print(math.sqrt(4))",
+ },
+ };
+ }
+ return undefined;
});
+
(NotebookLanguageServerClient as any).SEEN_CELL_DOCUMENT_URIS.clear();
});
@@ -250,8 +260,7 @@ describe("NotebookLanguageServerClient", () => {
expect(result).toBeDefined();
expect(result?.contents).toEqual({
kind: "markdown",
- value:
- '<div class="docs-documentation mo-cm-tooltip">\ntest hover\n</div>',
+ value: "test hover",
});
});
@@ -406,7 +415,7 @@ describe("NotebookLanguageServerClient", () => {
{
range: {
start: { line: 0, character: 0 },
- end: { line: 5, character: 0 },
+ end: { line: 3, character: 17 },
},
newText:
"# this is a comment\nimport renamed_math\nimport numpy\nprint(renamed_math.sqrt(4))",
@@ -586,7 +595,7 @@ describe("NotebookLanguageServerClient", () => {
// Start the document version at 1
(notebookClient as any).documentVersion = 1;
- // Open a document
+ // Open documents for multiple cells so they get tracked
await notebookClient.textDocumentDidOpen({
textDocument: {
uri: CellDocumentUri.of(Cells.cell1),
@@ -596,6 +605,15 @@ describe("NotebookLanguageServerClient", () => {
},
});
+ await notebookClient.textDocumentDidOpen({
+ textDocument: {
+ uri: CellDocumentUri.of(Cells.cell2),
+ languageId: "python",
+ version: 1,
+ text: "import math\nimport numpy",
+ },
+ });
+
// Simulate receiving diagnostics
const diagnosticsNotification = {
method: "textDocument/publishDiagnostics",
@@ -605,8 +623,8 @@ describe("NotebookLanguageServerClient", () => {
diagnostics: [
{
range: {
- start: { line: 1, character: 0 },
- end: { line: 1, character: 4 },
+ start: { line: 2, character: 0 },
+ end: { line: 2, character: 4 },
},
message: "Test diagnostic",
severity: LSP.DiagnosticSeverity.Error,
@@ -630,8 +648,8 @@ describe("NotebookLanguageServerClient", () => {
expect(capturedDiagnostics).toHaveLength(2);
expect(capturedDiagnostics[0].diagnostics).toHaveLength(1);
expect(capturedDiagnostics[0].diagnostics[0].range).toEqual({
- start: { line: 0, character: 0 },
- end: { line: 0, character: 4 },
+ start: { line: 1, character: 0 },
+ end: { line: 1, character: 4 },
});
// Rest are cleared
@@ -639,6 +657,8 @@ describe("NotebookLanguageServerClient", () => {
});
it("should clear diagnostics for all cells when receiving empty diagnostics", async () => {
+ await notebookClient.sync();
+
const seenNotifications: LSP.PublishDiagnosticsParams[] = [];
(mockClient as any).processNotification = vi
.fn()
@@ -652,6 +672,25 @@ describe("NotebookLanguageServerClient", () => {
// Start the document version at 1
(notebookClient as any).documentVersion = 1;
+ // Open documents so they get tracked
+ await notebookClient.textDocumentDidOpen({
+ textDocument: {
+ uri: CellDocumentUri.of(Cells.cell1),
+ languageId: "python",
+ version: 1,
+ text: "import math\nimport numpy",
+ },
+ });
+
+ await notebookClient.textDocumentDidOpen({
+ textDocument: {
+ uri: CellDocumentUri.of(Cells.cell2),
+ languageId: "python",
+ version: 1,
+ text: "import math\nimport numpy",
+ },
+ });
+
// Simulate receiving empty diagnostics
const emptyDiagnosticsNotification = {
method: "textDocument/publishDiagnostics",
@@ -685,7 +724,7 @@ describe("NotebookLanguageServerClient", () => {
// Start the document version at 1
(notebookClient as any).documentVersion = 1;
- // Open a document
+ // Open documents for multiple cells so they get tracked
await notebookClient.textDocumentDidOpen({
textDocument: {
uri: CellDocumentUri.of(Cells.cell1),
@@ -695,6 +734,15 @@ describe("NotebookLanguageServerClient", () => {
},
});
+ await notebookClient.textDocumentDidOpen({
+ textDocument: {
+ uri: CellDocumentUri.of(Cells.cell2),
+ languageId: "python",
+ version: 1,
+ text: "import math\nimport numpy",
+ },
+ });
+
// Simulate receiving diagnostics for multiple cells
const multiCellDiagnosticsNotification = {
method: "textDocument/publishDiagnostics",
@@ -742,14 +790,13 @@ describe("NotebookLanguageServerClient", () => {
});
it("should handle version updates in textDocumentDidChange", async () => {
- let capturedChange: LSP.DidChangeTextDocumentParams | undefined;
mockClient.textDocumentDidChange = vi
.fn()
.mockImplementation((params) => {
- capturedChange = params;
+ return params;
});
- await notebookClient.textDocumentDidChange({
+ const result = await notebookClient.textDocumentDidChange({
textDocument: {
uri: CellDocumentUri.of(Cells.cell1),
version: 5,
@@ -757,10 +804,10 @@ describe("NotebookLanguageServerClient", () => {
contentChanges: [{ text: "new code" }],
});
- expect(capturedChange).toBeDefined();
- expect(capturedChange?.textDocument.version).toBeGreaterThan(0);
- expect(capturedChange?.contentChanges).toHaveLength(1);
- expect(capturedChange?.contentChanges[0].text).toMatchInlineSnapshot(`
+ expect(result).toBeDefined();
+ expect(result.textDocument.version).toBeGreaterThan(0);
+ expect(result.contentChanges).toHaveLength(1);
+ expect(result.contentChanges[0].text).toMatchInlineSnapshot(`
"# this is a comment
import math
import numpy
diff --git a/frontend/src/core/codemirror/lsp/federated-lsp.ts b/frontend/src/core/codemirror/lsp/federated-lsp.ts
index 382b326af1..2473b5df60 100644
--- a/frontend/src/core/codemirror/lsp/federated-lsp.ts
+++ b/frontend/src/core/codemirror/lsp/federated-lsp.ts
@@ -201,7 +201,7 @@ export class FederatedLanguageServerClient implements ILanguageServerClient {
return result;
}
}
- throw new Error("No hover provider found");
+ return { contents: [] };
}
}
diff --git a/frontend/src/core/codemirror/lsp/notebook-lsp.ts b/frontend/src/core/codemirror/lsp/notebook-lsp.ts
index 5681ef6768..8508881d30 100644
--- a/frontend/src/core/codemirror/lsp/notebook-lsp.ts
+++ b/frontend/src/core/codemirror/lsp/notebook-lsp.ts
@@ -2,11 +2,12 @@
import type * as LSP from "vscode-languageserver-protocol";
import type { CellId } from "@/core/cells/ids";
+import { store } from "@/core/state/jotai";
import { invariant } from "@/utils/invariant";
import { Logger } from "@/utils/Logger";
import { LRUCache } from "@/utils/lru";
-import { getTopologicalCodes } from "../copilot/getCodes";
-import { createNotebookLens } from "./lens";
+import { topologicalCodesAtom } from "../copilot/getCodes";
+import { createNotebookLens, type NotebookLens } from "./lens";
import {
CellDocumentUri,
type ILanguageServerClient,
@@ -15,22 +16,72 @@ import {
} from "./types";
import { getLSPDocument } from "./utils";
-export class NotebookLanguageServerClient implements ILanguageServerClient {
- public readonly documentUri: LSP.DocumentUri;
+class Snapshotter {
private documentVersion = 0;
- private readonly client: ILanguageServerClient;
+
+ constructor(
+ private readonly getNotebookCode: () => {
+ cellIds: CellId[];
+ codes: Record<CellId, string>;
+ },
+ ) {}
/**
* Map from the global document version to the cell id and version.
*/
- private versionToCellNumberAndVersion = new LRUCache<
- number,
- {
- cellDocumentUri: LSP.DocumentUri;
- version: number;
- lens: ReturnType<typeof createNotebookLens>;
+ private versionToCellNumberAndVersion = new LRUCache<number, NotebookLens>(
+ 20,
+ );
+
+ private lastSnapshot: NotebookLens | null = null;
+
+ public snapshot() {
+ const lens = this.getLens();
+ const didChange = this.lastSnapshot?.mergedText !== lens.mergedText;
+ if (!didChange) {
+ return {
+ lens,
+ didChange,
+ version: this.documentVersion,
+ };
+ }
+
+ // Increment the version and update the snapshot
+ this.documentVersion++;
+ this.lastSnapshot = lens;
+
+ return {
+ lens,
+ didChange,
+ version: this.documentVersion,
+ };
+ }
+
+ public getSnapshot(version: number) {
+ const snapshot = this.versionToCellNumberAndVersion.get(version);
+ if (!snapshot) {
+ throw new Error(`No snapshot for version ${version}`);
}
- >(20);
+ return snapshot;
+ }
+
+ public getLatestSnapshot() {
+ if (!this.lastSnapshot) {
+ throw new Error("No snapshots");
+ }
+ return { lens: this.lastSnapshot, version: this.documentVersion };
+ }
+
+ private getLens() {
+ const { cellIds, codes } = this.getNotebookCode();
+ return createNotebookLens(cellIds, codes);
+ }
+}
+
+export class NotebookLanguageServerClient implements ILanguageServerClient {
+ public readonly documentUri: LSP.DocumentUri;
+ private readonly client: ILanguageServerClient;
+ private readonly snapshotter: Snapshotter;
private static readonly SEEN_CELL_DOCUMENT_URIS = new Set<CellDocumentUri>();
@@ -53,39 +104,160 @@ export class NotebookLanguageServerClient implements ILanguageServerClient {
settings: initialSettings,
});
});
+
+ this.snapshotter = new Snapshotter(this.getNotebookCode.bind(this));
}
- textDocumentDefinition(
+ get ready(): boolean {
+ return this.client.ready;
+ }
+
+ set ready(value: boolean) {
+ this.client.ready = value;
+ }
+
+ get capabilities(): LSP.ServerCapabilities | null {
+ return this.client.capabilities;
+ }
+
+ set capabilities(value: LSP.ServerCapabilities) {
+ this.client.capabilities = value;
+ }
+
+ get initializePromise(): Promise<void> {
+ return this.client.initializePromise;
+ }
+
+ set initializePromise(value: Promise<void>) {
+ this.client.initializePromise = value;
+ }
+
+ get clientCapabilities() {
+ return this.client.clientCapabilities;
+ }
+
+ async initialize(): Promise<void> {
+ await this.client.initialize();
+ }
+
+ close(): void {
+ this.client.close();
+ }
+
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ detachPlugin(plugin: any): void {
+ this.client.detachPlugin(plugin);
+ }
+
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ attachPlugin(plugin: any): void {
+ this.client.attachPlugin(plugin);
+ }
+
+ private getNotebookCode() {
+ return store.get(topologicalCodesAtom);
+ }
+
+ private assertCellDocumentUri(
+ uri: LSP.DocumentUri,
+ ): asserts uri is CellDocumentUri {
+ invariant(CellDocumentUri.is(uri), "Execpted URI to be CellDocumentUri");
+ }
+
+ /**
+ * Example of "zoom in" for textDocumentDidOpen, so server sees a merged doc.
+ */
+ public async textDocumentDidOpen(params: LSP.DidOpenTextDocumentParams) {
+ Logger.debug("[lsp] textDocumentDidOpen", params);
+ const cellDocumentUri = params.textDocument.uri;
+ this.assertCellDocumentUri(cellDocumentUri);
+
+ const { lens, version } = this.snapshotter.snapshot();
+
+ NotebookLanguageServerClient.SEEN_CELL_DOCUMENT_URIS.add(cellDocumentUri);
+
+ // Pass merged doc to LSP
+ const result = await this.client.textDocumentDidOpen({
+ textDocument: {
+ languageId: params.textDocument.languageId,
+ text: lens.mergedText,
+ uri: this.documentUri,
+ version: version,
+ },
+ });
+
+ if (!result) {
+ return params;
+ }
+
+ return {
+ ...result,
+ textDocument: {
+ ...result.textDocument,
+ text: lens.mergedText,
+ },
+ };
+ }
+
+ async sync(): Promise<LSP.DidChangeTextDocumentParams> {
+ const { lens, version, didChange } = this.snapshotter.snapshot();
+ if (!didChange) {
+ return {
+ textDocument: {
+ uri: this.documentUri,
+ version: version,
+ },
+ contentChanges: [{ text: lens.mergedText }],
+ };
+ }
+
+ // Update changes for merged doc, etc.
+ return this.client.textDocumentDidChange({
+ textDocument: {
+ uri: this.documentUri,
+ version: version,
+ },
+ contentChanges: [{ text: lens.mergedText }],
+ });
+ }
+
+ public async textDocumentDidChange(params: LSP.DidChangeTextDocumentParams) {
+ Logger.debug("[lsp] textDocumentDidChange", params);
+ // We know how to only handle single content changes
+ // But that is all we expect to receive
+ if (params.contentChanges.length === 1) {
+ return this.sync();
+ }
+
+ Logger.warn("[lsp] Unhandled textDocumentDidChange", params);
+
+ return this.client.textDocumentDidChange(params);
+ }
+
+ async 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);
+ return null;
}
+ // This LSP method has no version, so lets sync and then get the latest snapshot
+ await this.sync();
+ const { lens } = this.snapshotter.getLatestSnapshot();
+
// Find the lens for this cell
const cellId = CellDocumentUri.parse(cellDocumentUri);
- const versionInfo = [...this.versionToCellNumberAndVersion.values()].find(
- (info) => info.cellDocumentUri === cellDocumentUri,
- );
-
- if (!versionInfo) {
- Logger.warn("No lens found for cell", cellId);
- return Promise.resolve(null);
- }
-
- // Use the lens to transform the position
- const { lens } = versionInfo;
- const transformedPosition = lens.transformPosition(params.position, cellId);
return this.client.textDocumentDefinition({
...params,
textDocument: {
uri: this.documentUri,
},
- position: transformedPosition,
+ // Transform the position to the cell coordinates
+ position: lens.transformPosition(params.position, cellId),
});
}
@@ -98,25 +270,19 @@ export class NotebookLanguageServerClient implements ILanguageServerClient {
return null;
}
- const cellId = CellDocumentUri.parse(cellDocumentUri);
- const versionInfo = [...this.versionToCellNumberAndVersion.values()].find(
- (info) => info.cellDocumentUri === cellDocumentUri,
- );
-
- if (!versionInfo) {
- Logger.warn("No lens found for cell", cellId);
- return null;
- }
+ // This LSP method has no version, so lets sync and then get the latest snapshot
+ await this.sync();
+ const { lens } = this.snapshotter.getLatestSnapshot();
- const { lens } = versionInfo;
- const transformedPosition = lens.transformPosition(params.position, cellId);
+ const cellId = CellDocumentUri.parse(cellDocumentUri);
const response = await this.client.textDocumentSignatureHelp({
...params,
textDocument: {
uri: this.documentUri,
},
- position: transformedPosition,
+ // Transform the position to the cell coordinates
+ position: lens.transformPosition(params.position, cellId),
});
if (!response) {
@@ -156,16 +322,10 @@ export class NotebookLanguageServerClient implements ILanguageServerClient {
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;
- }
+ // This LSP method has no version, so lets sync and then get the latest snapshot
+ await this.sync();
+ const { lens } = this.snapshotter.getLatestSnapshot();
- // 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
@@ -272,15 +432,10 @@ export class NotebookLanguageServerClient implements ILanguageServerClient {
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;
- }
+ // This LSP method has no version, so lets sync and then get the latest snapshot
+ await this.sync();
+ const { lens } = this.snapshotter.getLatestSnapshot();
- // 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({
@@ -292,150 +447,14 @@ export class NotebookLanguageServerClient implements ILanguageServerClient {
});
}
- get ready(): boolean {
- return this.client.ready;
- }
-
- set ready(value: boolean) {
- this.client.ready = value;
- }
-
- get capabilities(): LSP.ServerCapabilities | null {
- return this.client.capabilities;
- }
-
- set capabilities(value: LSP.ServerCapabilities) {
- this.client.capabilities = value;
- }
-
- get initializePromise(): Promise<void> {
- return this.client.initializePromise;
- }
-
- set initializePromise(value: Promise<void>) {
- this.client.initializePromise = value;
- }
-
- get clientCapabilities() {
- return this.client.clientCapabilities;
- }
-
- async initialize(): Promise<void> {
- await this.client.initialize();
- }
-
- close(): void {
- this.client.close();
- }
-
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- detachPlugin(plugin: any): void {
- this.client.detachPlugin(plugin);
- }
-
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- attachPlugin(plugin: any): void {
- this.client.attachPlugin(plugin);
- }
-
- private getNotebookCode() {
- return getTopologicalCodes();
- }
-
- /**
- * Example of "zoom in" for textDocumentDidOpen, so server sees a merged doc.
- */
- public async textDocumentDidOpen(params: LSP.DidOpenTextDocumentParams) {
- Logger.debug("[lsp] textDocumentDidOpen", params);
- const cellDocumentUri = params.textDocument.uri;
- const { cellIds, codes } = this.getNotebookCode();
- const lens = createNotebookLens(cellIds, codes);
-
- // Store lens keyed by document version
- const version = params.textDocument.version;
- this.versionToCellNumberAndVersion.set(this.documentVersion, {
- cellDocumentUri,
- version,
- lens,
- });
- invariant(
- CellDocumentUri.is(cellDocumentUri),
- "Execpted URI to be CellDocumentUri",
- );
- NotebookLanguageServerClient.SEEN_CELL_DOCUMENT_URIS.add(cellDocumentUri);
-
- // Pass merged doc to super
- const result = await this.client.textDocumentDidOpen({
- textDocument: {
- languageId: params.textDocument.languageId,
- text: lens.mergedText,
- uri: this.documentUri,
- version: this.documentVersion,
- },
- });
-
- if (!result) {
- return params;
- }
-
- return {
- ...result,
- textDocument: {
- ...result.textDocument,
- text: lens.mergedText,
- },
- };
- }
-
- public async textDocumentDidChange(params: LSP.DidChangeTextDocumentParams) {
- Logger.debug("[lsp] textDocumentDidChange", params);
- // We know how to only handle single content changes
- // But that is all we expect to receive
- if (params.contentChanges.length === 1) {
- const cellDocumentUri = params.textDocument.uri;
- const { cellIds, codes } = this.getNotebookCode();
- const lens = createNotebookLens(cellIds, codes);
-
- const version = params.textDocument.version;
- this.documentVersion++;
- const globalDocumentVersion = this.documentVersion;
-
- this.versionToCellNumberAndVersion.set(globalDocumentVersion, {
- cellDocumentUri,
- version,
- lens,
- });
-
- // Update changes for merged doc, etc.
- return this.client.textDocumentDidChange({
- textDocument: {
- uri: this.documentUri,
- version: globalDocumentVersion,
- },
- contentChanges: [{ text: lens.mergedText }],
- });
- }
-
- Logger.warn("[lsp] Unhandled textDocumentDidChange", params);
-
- return this.client.textDocumentDidChange(params);
- }
-
public async textDocumentHover(params: LSP.HoverParams) {
Logger.debug("[lsp] textDocumentHover", params);
- const latestVersion = [...this.versionToCellNumberAndVersion.keys()].at(-1);
- if (latestVersion === undefined) {
- Logger.debug("[lsp] no latest version");
- return this.client.textDocumentHover(params);
- }
- const payload = this.versionToCellNumberAndVersion.get(latestVersion);
- if (!payload) {
- Logger.debug("[lsp] no payload for latest version");
- return this.client.textDocumentHover(params);
- }
- const { lens, cellDocumentUri } = payload;
- const cellId = CellDocumentUri.parse(cellDocumentUri);
+ // This LSP method has no version, so lets sync and then get the latest snapshot
+ await this.sync();
+ const { lens } = this.snapshotter.getLatestSnapshot();
+
+ const cellId = CellDocumentUri.parse(params.textDocument.uri);
const hover = await this.client.textDocumentHover({
...params,
@@ -454,7 +473,7 @@ export class NotebookLanguageServerClient implements ILanguageServerClient {
if (typeof hover.contents === "object" && "kind" in hover.contents) {
hover.contents = {
kind: "markdown",
- value: `<div class="docs-documentation mo-cm-tooltip">\n${hover.contents.value}\n</div>`,
+ value: hover.contents.value,
};
}
@@ -472,19 +491,8 @@ export class NotebookLanguageServerClient implements ILanguageServerClient {
}
public async textDocumentCompletion(params: LSP.CompletionParams) {
- const latestVersion = [...this.versionToCellNumberAndVersion.keys()].at(-1);
-
- if (latestVersion === undefined) {
- return this.client.textDocumentCompletion(params);
- }
-
- const payload = this.versionToCellNumberAndVersion.get(latestVersion);
- if (!payload) {
- return this.client.textDocumentCompletion(params);
- }
-
- const { lens, cellDocumentUri } = payload;
- const cellId = CellDocumentUri.parse(cellDocumentUri);
+ const { lens } = this.snapshotter.getLatestSnapshot();
+ const cellId = CellDocumentUri.parse(params.textDocument.uri);
return this.client.textDocumentCompletion({
...params,
@@ -521,13 +529,7 @@ export class NotebookLanguageServerClient implements ILanguageServerClient {
if (notification.method === "textDocument/publishDiagnostics") {
Logger.debug("[lsp] handling diagnostics", notification);
// Use the correct lens by version
- const globalVersion = notification.params.version || 0;
- const payload = this.versionToCellNumberAndVersion.get(globalVersion);
-
- if (!payload) {
- Logger.warn("[lsp] missing payload for version", globalVersion);
- return previousProcessNotification(notification);
- }
+ const payload = this.snapshotter.getLatestSnapshot();
const diagnostics = notification.params.diagnostics;
diff --git a/frontend/src/css/app/codemirror.css b/frontend/src/css/app/codemirror.css
index 6995906bbe..f114c58c55 100644
--- a/frontend/src/css/app/codemirror.css
+++ b/frontend/src/css/app/codemirror.css
@@ -78,6 +78,8 @@
/* -- Linting -- */
.cm-tooltip-lint {
+ @apply text-sm;
+
code {
@apply bg-muted border border-border rounded-md px-1;
}