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.

improvement: open external document on go-to-definction when LSP is enabled (#4092)

Myles Scolnick827bae06692e
diff --git a/frontend/package.json b/frontend/package.json
index 407d08dbed..82d7e8340d 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.5",
+ "@marimo-team/codemirror-languageserver": "^1.13.6",
"@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 b5c9293add..364a63ff17 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.5
- version: 1.13.5(@codemirror/[email protected])(@codemirror/[email protected])
+ specifier: ^1.13.6
+ version: 1.13.6(@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-rinzDRfL0dyjcdfOLHq0hh0nbzhtB8XZ3kkLx/MRekJyNnsSfGklSrGno9hXSNhegtUpcT3sIss4u4dvEwpxdg==}
+ '@marimo-team/[email protected]':
+ resolution: {integrity: sha512-53iaZY/1mk+WspRvzesECdZSP/YJBCCySnHJC+MNsUa4CyxizpiRogyyZ26/Xab2wMDWsAimtxhEE+wOPnd0+w==}
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/language/python.ts b/frontend/src/core/codemirror/language/python.ts
index e372a1f457..f4839cad1f 100644
--- a/frontend/src/core/codemirror/language/python.ts
+++ b/frontend/src/core/codemirror/language/python.ts
@@ -32,6 +32,10 @@ import { autocompletion } from "@codemirror/autocomplete";
import { completer } from "../completion/completer";
import { getFilenameFromDOM } from "@/core/dom/htmlUtils";
import { Paths } from "@/utils/paths";
+import type { CellId } from "@/core/cells/ids";
+import { cellActionsState } from "../cells/state";
+import { openFile } from "@/core/network/requests";
+import { Logger } from "@/utils/Logger";
const pylspTransport = once(() => {
const transport = new WebSocketTransport(resolveToWsUrl("/lsp/pylsp"));
@@ -112,11 +116,9 @@ const lspClient = once((lspConfig: LSPConfig) => {
autoClose: false,
}),
settings,
- ) as unknown as LanguageServerClient;
+ );
});
-import type { CellId } from "@/core/cells/ids";
-import { cellActionsState } from "../cells/state";
/**
* Language adapter for Python.
*/
@@ -143,30 +145,48 @@ export class PythonLanguageAdapter implements LanguageAdapter {
placeholderType: PlaceholderType,
lspConfig: LSPConfig,
): Extension[] {
+ const getCompletionsExtension = () => {
+ if (getFeatureFlag("lsp") && lspConfig?.pylsp?.enabled) {
+ const client = lspClient(lspConfig);
+ return languageServerWithTransport({
+ client: client as unknown as LanguageServerClient,
+ documentUri: CellDocumentUri.of(cellId),
+ transport: pylspTransport(),
+ rootUri: "file:///",
+ languageId: "python",
+ workspaceFolders: [],
+ allowHTMLContent: true,
+ onGoToDefinition: (result) => {
+ Logger.debug("onGoToDefinition", result);
+ if (client.documentUri === result.uri) {
+ // Local definition
+ return;
+ }
+
+ openFile({
+ path: result.uri.replace("file://", ""),
+ });
+ },
+ });
+ }
+
+ // Whether or not to require keypress to activate autocompletion (default
+ // keymap is Ctrl+Space)
+ return autocompletion({
+ activateOnTyping: completionConfig.activate_on_typing,
+ // The Cell component handles the blur event. `closeOnBlur` is too
+ // aggressive and doesn't let the user click into the completion info
+ // element (which contains the docstring/type --- users might want to
+ // copy paste from the docstring). The main issue is that the completion
+ // tooltip is not part of the editable DOM tree:
+ // https://discuss.codemirror.net/t/adding-click-event-listener-to-autocomplete-tooltip-info-panel-is-not-working/4741
+ closeOnBlur: false,
+ override: [completer],
+ });
+ };
+
return [
- getFeatureFlag("lsp") && lspConfig?.pylsp?.enabled
- ? languageServerWithTransport({
- client: lspClient(lspConfig),
- documentUri: CellDocumentUri.of(cellId),
- transport: pylspTransport(),
- rootUri: "file:///",
- languageId: "python",
- workspaceFolders: [],
- allowHTMLContent: true,
- })
- : // Whether or not to require keypress to activate autocompletion (default
- // keymap is Ctrl+Space)
- autocompletion({
- activateOnTyping: completionConfig.activate_on_typing,
- // The Cell component handles the blur event. `closeOnBlur` is too
- // aggressive and doesn't let the user click into the completion info
- // element (which contains the docstring/type --- users might want to
- // copy paste from the docstring). The main issue is that the completion
- // tooltip is not part of the editable DOM tree:
- // https://discuss.codemirror.net/t/adding-click-event-listener-to-autocomplete-tooltip-info-panel-is-not-working/4741
- closeOnBlur: false,
- override: [completer],
- }),
+ getCompletionsExtension(),
customPythonLanguageSupport(),
placeholderType === "marimo-import"
? Prec.highest(smartPlaceholderExtension("import marimo as mo"))
diff --git a/frontend/src/core/codemirror/lsp/notebook-lsp.ts b/frontend/src/core/codemirror/lsp/notebook-lsp.ts
index bc7aea5406..2b75027d2b 100644
--- a/frontend/src/core/codemirror/lsp/notebook-lsp.ts
+++ b/frontend/src/core/codemirror/lsp/notebook-lsp.ts
@@ -10,8 +10,7 @@ import type { CellId } from "@/core/cells/ids";
import { getFilenameFromDOM } from "@/core/dom/htmlUtils";
export class NotebookLanguageServerClient implements ILanguageServerClient {
- private readonly documentUri =
- `file://${getFilenameFromDOM() ?? "/__marimo_notebook__.py"}`;
+ public readonly documentUri: LSP.DocumentUri;
private documentVersion = 0;
private readonly client: ILanguageServerClient;
@@ -33,6 +32,8 @@ export class NotebookLanguageServerClient implements ILanguageServerClient {
client: ILanguageServerClient,
initialSettings: Record<string, unknown>,
) {
+ this.documentUri = `file://${getFilenameFromDOM() ?? "/__marimo_notebook__.py"}`;
+
this.client = client;
this.patchProcessNotification();
@@ -52,7 +53,34 @@ export class NotebookLanguageServerClient implements ILanguageServerClient {
textDocumentDefinition(
params: LSP.DefinitionParams,
): Promise<LSP.Definition | LSP.LocationLink[] | null> {
- return this.client.textDocumentDefinition(params);
+ // Get the cell document URI from the params
+ const cellDocumentUri = params.textDocument.uri;
+ if (!CellDocumentUri.is(cellDocumentUri)) {
+ return Promise.resolve(null);
+ }
+
+ // 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,
+ });
}
textDocumentCodeAction(
@@ -107,6 +135,10 @@ export class NotebookLanguageServerClient implements ILanguageServerClient {
this.client.initializePromise = value;
}
+ get clientCapabilities() {
+ return this.client.clientCapabilities;
+ }
+
async initialize(): Promise<void> {
await this.client.initialize();
}
diff --git a/frontend/src/utils/lru.ts b/frontend/src/utils/lru.ts
index 7db0691eab..a70c853286 100644
--- a/frontend/src/utils/lru.ts
+++ b/frontend/src/utils/lru.ts
@@ -37,4 +37,12 @@ export class LRUCache<K, V> {
public keys() {
return this.cache.keys();
}
+
+ public values() {
+ return this.cache.values();
+ }
+
+ public entries() {
+ return this.cache.entries();
+ }
}