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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
experimental: lsp server (#3414)
Myles Scolnickf9c1bfe2ff5c
diff --git a/frontend/e2e-tests/tsconfig.json b/frontend/e2e-tests/tsconfig.jsonindex 25dcabd63b..9757244bce 100644--- a/frontend/e2e-tests/tsconfig.json+++ b/frontend/e2e-tests/tsconfig.json@@ -3,7 +3,7 @@"lib": ["ES2022", "DOM"],"noEmit": true,"module": "ESNext",- "moduleResolution": "node",+ "moduleResolution": "Bundler","types": ["@types/node"],"esModuleInterop": true,"forceConsistentCasingInFileNames": true,diff --git a/frontend/package.json b/frontend/package.jsonindex 19576f4c25..f06164ccd1 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -42,6 +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/react-slotz": "^0.1.8","@open-rpc/client-js": "^1.8.1","@paralleldrive/cuid2": "^2.2.2",@@ -96,7 +97,6 @@"clsx": "^2.1.1","cmdk": "^1.0.4","codemirror-extension-inline-suggestion": "^0.0.3",- "codemirror-languageserver": "^1.12.1","compassql": "^0.21.2","cssnano": "^7.0.6","date-fns": "^4.1.0",@@ -241,7 +241,8 @@"packageManager": "[email protected]","pnpm": {"patchedDependencies": {- "react-plotly.js": "patches/react-plotly.js.patch"+ "react-plotly.js": "patches/react-plotly.js.patch",+ "codemirror-extension-inline-suggestion": "patches/codemirror-extension-inline-suggestion.patch"}}}diff --git a/frontend/patches/codemirror-extension-inline-suggestion.patch b/frontend/patches/codemirror-extension-inline-suggestion.patchnew file mode 100644index 0000000000..353c405be5--- /dev/null+++ b/frontend/patches/codemirror-extension-inline-suggestion.patch@@ -0,0 +1,12 @@+diff --git a/dist/extension.js b/dist/extension.js+index 85ae3900124b575165fc4891e271c97bc1485b5e..7c3385b5381d0aaa4183cc2d293643a046ac2caa 100644+--- a/dist/extension.js++++ b/dist/extension.js+@@ -12,6 +12,7 @@ const u = p.define({+ const e = n.effects.find(+ (s) => s.is(l)+ );++ if (!n.docChanged && !e && !n.selection) return t;+ return n.state.doc && e && n.state.doc == e.value.doc ? { suggestion: e.value.text } : { suggestion: null };+ }+ }), l = S.define();diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yamlindex f52668948e..3c23038a58 100644--- a/frontend/pnpm-lock.yaml+++ b/frontend/pnpm-lock.yaml@@ -7,6 +7,9 @@ settings:pnpmfileChecksum: eqzj7c6t3bs5v7xcjer2wfwkp4patchedDependencies:+ codemirror-extension-inline-suggestion:+ hash: khbxbgrsjmwb5ecklr5ujxzp5i+ path: patches/codemirror-extension-inline-suggestion.patchreact-plotly.js:hash: bpeex744nmt6722etqry6essaqpath: patches/react-plotly.js.patch@@ -99,6 +102,9 @@ importers:'@marimo-team/codemirror-ai':specifier: ^0.1.9version: 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])'@marimo-team/marimo-api':specifier: file:../openapiversion: file:../openapi@@ -263,10 +269,7 @@ importers:version: 1.0.4(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])codemirror-extension-inline-suggestion:specifier: ^0.0.3- version: 0.0.3(@codemirror/[email protected])(@codemirror/[email protected])- codemirror-languageserver:- specifier: ^1.12.1- version: 1.12.1+ version: 0.0.3(patch_hash=khbxbgrsjmwb5ecklr5ujxzp5i)(@codemirror/[email protected])(@codemirror/[email protected])compassql:specifier: ^0.21.2version: 0.21.2([email protected])@@ -1543,6 +1546,12 @@ packages:'@codemirror/state': ^6'@codemirror/view': ^6+ '@marimo-team/[email protected]':+ resolution: {integrity: sha512-rinzDRfL0dyjcdfOLHq0hh0nbzhtB8XZ3kkLx/MRekJyNnsSfGklSrGno9hXSNhegtUpcT3sIss4u4dvEwpxdg==}+ peerDependencies:+ '@codemirror/state': ^6+ '@codemirror/view': ^6+'@marimo-team/marimo-api@file:../openapi':resolution: {directory: ../openapi, type: directory}@@ -4365,9 +4374,6 @@ packages:resolution: {integrity: sha512-Taw/2gPCyNArQJCxIP/HSUif+3zrvD+6Ugt7KJZ2dUKou/8r3ZhcfG8krNTZfV2iu8AuGnymKuo7bLPFyqsh/A==}- resolution: {integrity: sha512-B71XofYRsVsyUpkiWtdTcHIwVoEpws01PqHpkr/o5k4EET9kQEpRqDH/G+f+hQI4eZxwONOx8n5Dz2fsf02PrA==}-resolution: {integrity: sha512-J8j+nZ+CdWmIeFIGXEFbFPtpiYacFMDR8GlHK3IyHQJMCaVRfGx9NT+Hxivv1ckLWPvNdZqndbr/7lVhrf/Svg==}@@ -10199,6 +10205,20 @@ snapshots:'@codemirror/state': 6.5.2'@codemirror/view': 6.36.4+ dependencies:+ '@codemirror/autocomplete': 6.18.6+ '@codemirror/lint': 6.8.4+ '@codemirror/state': 6.5.2+ '@codemirror/view': 6.36.4+ '@open-rpc/client-js': 1.8.1+ marked: 15.0.7+ vscode-languageserver-protocol: 3.17.5+ transitivePeerDependencies:+ - bufferutil+ - encoding+ - utf-8-validate+'@marimo-team/marimo-api@file:../openapi':dependencies:openapi-fetch: 0.9.7@@ -13770,7 +13790,7 @@ snapshots:+ [email protected](patch_hash=khbxbgrsjmwb5ecklr5ujxzp5i)(@codemirror/[email protected])(@codemirror/[email protected]):dependencies:'@codemirror/state': 6.5.2'@codemirror/view': 6.36.4@@ -13781,20 +13801,6 @@ snapshots:'@lezer/highlight': 1.2.1'@lezer/lr': 1.4.2- dependencies:- '@codemirror/autocomplete': 6.18.6- '@codemirror/lint': 6.8.4- '@codemirror/state': 6.5.2- '@codemirror/view': 6.36.4- '@open-rpc/client-js': 1.8.1- marked: 15.0.7- vscode-languageserver-protocol: 3.17.5- transitivePeerDependencies:- - bufferutil- - encoding- - utf-8-validate-dependencies:'@codemirror/autocomplete': 6.18.6diff --git a/frontend/src/components/editor/cell/code/cell-editor.tsx b/frontend/src/components/editor/cell/code/cell-editor.tsxindex ab948fccf9..e244800047 100644--- a/frontend/src/components/editor/cell/code/cell-editor.tsx+++ b/frontend/src/components/editor/cell/code/cell-editor.tsx@@ -162,6 +162,7 @@ const CellEditorInternal = ({},completionConfig: userConfig.completion,keymapConfig: userConfig.keymap,+ lspConfig: userConfig.language_servers,theme,hotkeys: new OverridingHotkeyProvider(userConfig.keymap.overrides ?? {}),});@@ -245,6 +246,7 @@ const CellEditorInternal = ({editorViewRef.current,userConfig.completion,new OverridingHotkeyProvider(userConfig.keymap.overrides ?? {}),+ userConfig.language_servers,),],});diff --git a/frontend/src/core/cells/__tests__/cells.test.ts b/frontend/src/core/cells/__tests__/cells.test.tsindex 1afebac7b4..3a4a6c08d0 100644--- a/frontend/src/core/cells/__tests__/cells.test.ts+++ b/frontend/src/core/cells/__tests__/cells.test.ts@@ -88,6 +88,7 @@ function createEditor(content: string) {},hotkeys: new OverridingHotkeyProvider({}),placeholderType: "marimo-import",+ lspConfig: {},}),],});diff --git a/frontend/src/core/codemirror/__tests__/setup.test.ts b/frontend/src/core/codemirror/__tests__/setup.test.tsindex 749f21db2c..c1fb7b90ba 100644--- a/frontend/src/core/codemirror/__tests__/setup.test.ts+++ b/frontend/src/core/codemirror/__tests__/setup.test.ts@@ -9,6 +9,14 @@ import { OverridingHotkeyProvider } from "@/core/hotkeys/hotkeys";import { PythonLanguageAdapter } from "../language/python";import type { CodemirrorCellActions } from "../cells/state";+vi.mock("@/core/config/config", async (importOriginal) => {+ const original = await importOriginal<{}>();+ return {+ ...original,+ parseAppConfig: () => ({}),+ parseUserConfig: () => ({}),+ };+});vi.mock("@/core/config/config", async (importOriginal) => {const original = await importOriginal<{}>();return {@@ -46,6 +54,11 @@ function getOpts() {preset: "default",overrides: {},},+ lspConfig: {+ pylsp: {+ enabled: false,+ },+ },hotkeys: new OverridingHotkeyProvider({}),theme: "light",} as const;@@ -120,10 +133,17 @@ test("placeholder adds another extension", () => {opts.completionConfig,opts.hotkeys,"marimo-import",+ opts.lspConfig,).flat();const withoutAI = new PythonLanguageAdapter()- .getExtension(opts.cellId, opts.completionConfig, opts.hotkeys, "none")+ .getExtension(+ opts.cellId,+ opts.completionConfig,+ opts.hotkeys,+ "none",+ opts.lspConfig,+ ).flat();expect(withAI.length - 1).toBe(withoutAI.length);});@@ -131,10 +151,22 @@ test("placeholder adds another extension", () => {test("ai adds more extensions", () => {const opts = getOpts();const withAI = new PythonLanguageAdapter()- .getExtension(opts.cellId, opts.completionConfig, opts.hotkeys, "ai")+ .getExtension(+ opts.cellId,+ opts.completionConfig,+ opts.hotkeys,+ "ai",+ opts.lspConfig,+ ).flat();const withoutAI = new PythonLanguageAdapter()- .getExtension(opts.cellId, opts.completionConfig, opts.hotkeys, "none")+ .getExtension(+ opts.cellId,+ opts.completionConfig,+ opts.hotkeys,+ "none",+ opts.lspConfig,+ ).flat();expect(withAI.length - 2).toBe(withoutAI.length);});diff --git a/frontend/src/core/codemirror/cm.ts b/frontend/src/core/codemirror/cm.tsindex fc515cfce8..c6bc2d8bb7 100644--- a/frontend/src/core/codemirror/cm.ts+++ b/frontend/src/core/codemirror/cm.ts@@ -13,6 +13,7 @@ import {indentWithTab,indentMore,} from "@codemirror/commands";+import { lintGutter } from "@codemirror/lint";import {bracketMatching,defaultHighlightStyle,@@ -36,7 +37,11 @@ import {} from "@codemirror/view";import { EditorState, type Extension, Prec } from "@codemirror/state";-import type { CompletionConfig, KeymapConfig } from "../config/config-schema";+import type {+ CompletionConfig,+ KeymapConfig,+ LSPConfig,+} from "../config/config-schema";import type { Theme } from "../../theme/useTheme";import { findReplaceBundle } from "./find-replace/extension";@@ -72,6 +77,7 @@ export interface CodeMirrorSetupOpts {keymapConfig: KeymapConfig;theme: Theme;hotkeys: HotkeyProvider;+ lspConfig: LSPConfig;}function getPlaceholderType(opts: CodeMirrorSetupOpts) {@@ -90,6 +96,7 @@ export const setupCodeMirror = (opts: CodeMirrorSetupOpts): Extension[] => {enableAI,cellActions,completionConfig,+ lspConfig,} = opts;const placeholderType = getPlaceholderType(opts);@@ -100,12 +107,13 @@ export const setupCodeMirror = (opts: CodeMirrorSetupOpts): Extension[] => {pasteBundle(),jupyterHelpExtension(),// Cell editing- cellConfigExtension(completionConfig, hotkeys, placeholderType),+ cellConfigExtension(completionConfig, hotkeys, placeholderType, lspConfig),cellBundle(cellId, hotkeys, cellActions),// Comes last so that it can be overriddenbasicBundle(opts),// Underline cmd+clickable placeholdergoToDefinitionBundle(),+ getFeatureFlag("lsp") ? lintGutter() : [],// AI edit inlineenableAI && getFeatureFlag("inline_ai_tooltip")? aiExtension({@@ -139,7 +147,7 @@ const startCompletionAtEndOfLine = (cm: EditorView): boolean => {// Based on codemirror's basicSetup extensionexport const basicBundle = (opts: CodeMirrorSetupOpts): Extension[] => {- const { theme, hotkeys, completionConfig, cellId } = opts;+ const { theme, hotkeys, completionConfig, cellId, lspConfig } = opts;const placeholderType = getPlaceholderType(opts);return [@@ -181,6 +189,7 @@ export const basicBundle = (opts: CodeMirrorSetupOpts): Extension[] => {completionConfig,hotkeys,cellId,+ lspConfig,}),///// Editingdiff --git a/frontend/src/core/codemirror/completion/hints.ts b/frontend/src/core/codemirror/completion/hints.tsindex 3ebe5f5491..3d5d47c87a 100644--- a/frontend/src/core/codemirror/completion/hints.ts+++ b/frontend/src/core/codemirror/completion/hints.ts@@ -7,19 +7,23 @@ import type { EditorState, Text } from "@codemirror/state";import { debounce } from "lodash-es";import { documentationAtom } from "@/core/documentation/state";import { store } from "@/core/state/jotai";+import { getFeatureFlag } from "@/core/config/feature-flag";export function hintTooltip() {return [- hoverTooltip(- async (view, pos) => {- const result = await requestDocumentation(view, pos, ["tooltip"]);- if (result === null || result === "cancelled") {- return null;- }- return result;- },- { hideOnChange: true },- ),+ // Hover tooltip is already covered by LSP+ getFeatureFlag("lsp")+ ? []+ : hoverTooltip(+ async (view, pos) => {+ const result = await requestDocumentation(view, pos, ["tooltip"]);+ if (result === null || result === "cancelled") {+ return null;+ }+ return result;+ },+ { hideOnChange: true },+ ),cursorPositionDocumentation,];}diff --git a/frontend/src/core/codemirror/config/extension.ts b/frontend/src/core/codemirror/config/extension.tsindex f42574dbd2..e3b7cdca46 100644--- a/frontend/src/core/codemirror/config/extension.ts+++ b/frontend/src/core/codemirror/config/extension.ts@@ -1,5 +1,5 @@/* Copyright 2024 Marimo. All rights reserved. */-import type { CompletionConfig } from "@/core/config/config-schema";+import type { CompletionConfig, LSPConfig } from "@/core/config/config-schema";import type { HotkeyProvider } from "@/core/hotkeys/hotkeys";import { Facet } from "@codemirror/state";import type { CellId } from "@/core/cells/ids";@@ -39,6 +39,13 @@ export const cellIdState = Facet.define<CellId, CellId>({combine: (values) => values[0],});+/**+ * State for LSP config+ */+export const lspConfigState = Facet.define<LSPConfig, LSPConfig>({+ combine: (values) => values[0],+});+/*** Extension for cell config*/@@ -46,11 +53,13 @@ export function cellConfigExtension(completionConfig: CompletionConfig,hotkeys: HotkeyProvider,placeholderType: PlaceholderType,+ lspConfig: LSPConfig,) {return [// Store statecompletionConfigState.of(completionConfig),hotkeysProviderState.of(hotkeys),placeholderState.of(placeholderType),+ lspConfigState.of(lspConfig),];}diff --git a/frontend/src/core/codemirror/copilot/__tests__/getCode.test.ts b/frontend/src/core/codemirror/copilot/__tests__/getCode.test.tsindex 034b7da228..dfbc92ceda 100644--- a/frontend/src/core/codemirror/copilot/__tests__/getCode.test.ts+++ b/frontend/src/core/codemirror/copilot/__tests__/getCode.test.ts@@ -41,6 +41,7 @@ function createMockEditorView(code: string) {},hotkeys: new OverridingHotkeyProvider({}),placeholderType: "marimo-import",+ lspConfig: {},}),cellConfigExtension({@@ -50,6 +51,7 @@ function createMockEditorView(code: string) {},new OverridingHotkeyProvider({}),"marimo-import",+ {},),],}),diff --git a/frontend/src/core/codemirror/copilot/client.ts b/frontend/src/core/codemirror/copilot/client.tsindex 54c2dd4d78..981ea2574f 100644--- a/frontend/src/core/codemirror/copilot/client.ts+++ b/frontend/src/core/codemirror/copilot/client.ts@@ -1,6 +1,6 @@/* Copyright 2024 Marimo. All rights reserved. */import { once } from "@/utils/once";-import { languageServerWithTransport } from "codemirror-languageserver";+import { languageServerWithTransport } from "@marimo-team/codemirror-languageserver";import { CopilotLanguageServerClient } from "./language-server";import { WebSocketTransport } from "@open-rpc/client-js";import { Transport } from "@open-rpc/client-js/build/transports/Transport";@@ -12,7 +12,7 @@ import { Logger } from "@/utils/Logger";import { toast } from "@/components/ui/use-toast";// Dummy file for the copilot language server-export const COPILOT_FILENAME = "/marimo.py";+export const COPILOT_FILENAME = "/__marimo_copilot__.py";export const LANGUAGE_ID = "copilot";const FILE_URI = `file://${COPILOT_FILENAME}`;diff --git a/frontend/src/core/codemirror/copilot/extension.ts b/frontend/src/core/codemirror/copilot/extension.tsindex b3c0916f79..c0e52de3af 100644--- a/frontend/src/core/codemirror/copilot/extension.ts+++ b/frontend/src/core/codemirror/copilot/extension.ts@@ -1,5 +1,10 @@/* Copyright 2024 Marimo. All rights reserved. */-import type { EditorState, Extension, Text } from "@codemirror/state";+import {+ Compartment,+ type EditorState,+ type Extension,+ type Text,+} from "@codemirror/state";import {COPILOT_FILENAME,LANGUAGE_ID,@@ -21,6 +26,8 @@ import type {} from "./types";import { Logger } from "@/utils/Logger";+const copilotCompartment = new Compartment();+export const copilotBundle = (config: CompletionConfig): Extension => {if (process.env.NODE_ENV === "test") {return [];@@ -86,8 +93,9 @@ export const copilotBundle = (config: CompletionConfig): Extension => {return [...extensions,- // pop off last 2 elements of the array which are tooltip and autocompletion- copilotServer().slice(0, -2),+ // grab the first 4 elements of the array is the LSP without hover/autocompletion+ // place in own compartment so it doesn't interfere with other LSP+ copilotCompartment.of(copilotServer().slice(0, 4)),];};diff --git a/frontend/src/core/codemirror/copilot/language-server.ts b/frontend/src/core/codemirror/copilot/language-server.tsindex c33f98be4a..bf2dc949ed 100644--- a/frontend/src/core/codemirror/copilot/language-server.ts+++ b/frontend/src/core/codemirror/copilot/language-server.ts@@ -10,7 +10,7 @@ import type {} from "vscode-languageserver-protocol";import { VersionedTextDocumentIdentifier } from "vscode-languageserver-protocol";-import { LanguageServerClient } from "codemirror-languageserver";+import { LanguageServerClient } from "@marimo-team/codemirror-languageserver";import type {CopilotStatus,CopilotSignInInitiateParams,@@ -79,10 +79,8 @@ export class CopilotLanguageServerClient extends LanguageServerClient {override async textDocumentCompletion(params: CompletionParams,): Promise<CompletionList | CompletionItem[]> {- if (this.isDisabled()) {- return [];- }- return super.textDocumentCompletion(params);+ // Not used in Copilot+ return [];}override async textDocumentDidChange(@@ -102,10 +100,8 @@ export class CopilotLanguageServerClient extends LanguageServerClient {}override textDocumentHover(params: HoverParams): Promise<Hover> {- if (this.isDisabled()) {- return Promise.resolve({ contents: [] });- }- return super.textDocumentHover(params);+ // Not used in Copilot+ return Promise.resolve({ contents: [] });}// AUTHdiff --git a/frontend/src/core/codemirror/language/__tests__/extension.test.ts b/frontend/src/core/codemirror/language/__tests__/extension.test.tsindex 4dded16d90..6cd082ac4a 100644--- a/frontend/src/core/codemirror/language/__tests__/extension.test.ts+++ b/frontend/src/core/codemirror/language/__tests__/extension.test.ts@@ -23,6 +23,7 @@ function createState(content: string, selection?: { anchor: number }) {activate_on_typing: true,codeium_api_key: null,},+ lspConfig: {},hotkeys: new OverridingHotkeyProvider({}),placeholderType: "marimo-import",}),@@ -34,6 +35,7 @@ function createState(content: string, selection?: { anchor: number }) {},new OverridingHotkeyProvider({}),"marimo-import",+ {},),],selection,diff --git a/frontend/src/core/codemirror/language/__tests__/utils.test.ts b/frontend/src/core/codemirror/language/__tests__/utils.test.tsindex 812f7fc073..66935d38c4 100644--- a/frontend/src/core/codemirror/language/__tests__/utils.test.ts+++ b/frontend/src/core/codemirror/language/__tests__/utils.test.ts@@ -24,8 +24,9 @@ function createEditor(doc: string) {codeium_api_key: null,},hotkeys: new OverridingHotkeyProvider({}),- placeholderType: "marimo-import",cellId: "cell1" as CellId,+ placeholderType: "marimo-import",+ lspConfig: {},}),cellConfigExtension({@@ -35,6 +36,11 @@ function createEditor(doc: string) {},new OverridingHotkeyProvider({}),"marimo-import",+ {+ pylsp: {+ enabled: true,+ },+ },),],}),diff --git a/frontend/src/core/codemirror/language/extension.ts b/frontend/src/core/codemirror/language/extension.tsindex a649e91e60..1c7091a4dd 100644--- a/frontend/src/core/codemirror/language/extension.ts+++ b/frontend/src/core/codemirror/language/extension.ts@@ -13,11 +13,12 @@ import {showPanel,} from "@codemirror/view";import { clamp } from "@/utils/math";-import type { CompletionConfig } from "@/core/config/config-schema";+import type { CompletionConfig, LSPConfig } from "@/core/config/config-schema";import {cellIdState,completionConfigState,hotkeysProviderState,+ lspConfigState,placeholderState,type PlaceholderType,} from "../config/extension";@@ -117,6 +118,7 @@ function updateLanguageAdapterAndCode(const hotkeysProvider = view.state.facet(hotkeysProviderState);const placeholderType = view.state.facet(placeholderState);const cellId = view.state.facet(cellIdState);+ const lspConfig = view.state.facet(lspConfigState);let cursor = view.state.selection.main.head;// If keepCodeAsIs is true, we just keep the original code@@ -147,6 +149,7 @@ function updateLanguageAdapterAndCode(completionConfig,hotkeysProvider,placeholderType,+ lspConfig,),),// Clear history@@ -181,9 +184,11 @@ export function adaptiveLanguageConfiguration(opts: {placeholderType: PlaceholderType;completionConfig: CompletionConfig;hotkeys: HotkeyProvider;+ lspConfig: LSPConfig;cellId: CellId;}) {- const { placeholderType, completionConfig, hotkeys, cellId } = opts;+ const { placeholderType, completionConfig, hotkeys, cellId, lspConfig } =+ opts;return [// Language adapter@@ -194,6 +199,7 @@ export function adaptiveLanguageConfiguration(opts: {completionConfig,hotkeys,placeholderType,+ lspConfig,),),languageAdapterState,@@ -258,6 +264,7 @@ export function reconfigureLanguageEffect(view: EditorView,completionConfig: CompletionConfig,hotkeysProvider: HotkeyProvider,+ lspConfig: LSPConfig,) {const language = view.state.field(languageAdapterState);const placeholderType = view.state.facet(placeholderState);@@ -268,6 +275,7 @@ export function reconfigureLanguageEffect(completionConfig,hotkeysProvider,placeholderType,+ lspConfig,),);}diff --git a/frontend/src/core/codemirror/language/markdown.ts b/frontend/src/core/codemirror/language/markdown.tsindex 56fc88c661..32da4ad547 100644--- a/frontend/src/core/codemirror/language/markdown.ts+++ b/frontend/src/core/codemirror/language/markdown.ts@@ -5,6 +5,7 @@ import { markdown } from "@codemirror/lang-markdown";import { languages } from "@codemirror/language-data";import { parseMixed } from "@lezer/common";import { python, pythonLanguage } from "@codemirror/lang-python";+// @ts-expect-error: no declaration fileimport dedent from "string-dedent";import {type Completion,diff --git a/frontend/src/core/codemirror/language/python.ts b/frontend/src/core/codemirror/language/python.tsindex 97d10e059a..e372a1f457 100644--- a/frontend/src/core/codemirror/language/python.ts+++ b/frontend/src/core/codemirror/language/python.ts@@ -11,15 +11,110 @@ import {foldInside,LanguageSupport,} from "@codemirror/language";-import type { CompletionConfig } from "@/core/config/config-schema";-import { autocompletion } from "@codemirror/autocomplete";-import { completer } from "../completion/completer";+import type { CompletionConfig, LSPConfig } from "@/core/config/config-schema";import type { HotkeyProvider } from "@/core/hotkeys/hotkeys";import type { PlaceholderType } from "../config/extension";import {smartPlaceholderExtension,clickablePlaceholderExtension,} from "../placeholder/extensions";+import {+ LanguageServerClient,+ languageServerWithTransport,+} from "@marimo-team/codemirror-languageserver";+import { resolveToWsUrl } from "@/core/websocket/createWsUrl";+import { WebSocketTransport } from "@open-rpc/client-js";+import { CellDocumentUri } from "../lsp/types";+import { NotebookLanguageServerClient } from "../lsp/notebook-lsp";+import { once } from "@/utils/once";+import { getFeatureFlag } from "@/core/config/feature-flag";+import { autocompletion } from "@codemirror/autocomplete";+import { completer } from "../completion/completer";+import { getFilenameFromDOM } from "@/core/dom/htmlUtils";+import { Paths } from "@/utils/paths";++const pylspTransport = once(() => {+ const transport = new WebSocketTransport(resolveToWsUrl("/lsp/pylsp"));+ return transport;+});++const lspClient = once((lspConfig: LSPConfig) => {+ const lspClientOpts = {+ transport: pylspTransport(),+ rootUri: `file://${Paths.dirname(getFilenameFromDOM() ?? "/")}`,+ languageId: "python",+ workspaceFolders: [],+ };+ const config = lspConfig?.pylsp;++ const ignoredStyleRules = [+ // Notebooks are not really public modules and are better documented+ // by having a markdown cell with explanations instead+ "D100", // Missing docstring in public module+ "D103", // Missing docstring in public function+ ];+ const ignoredFlakeRules = [+ // The final cell in the notebook is not required to have a new line+ "W292", // No newline at end of file+ // Modules can be imported in any cell+ "E402", // Module level import not at top of file+ ];+ const ignoredRuffRules = [+ // Even ruff documentation of this rule explains it is not useful in notebooks+ "B018", // Useless expression+ ];+ const settings = {+ pylsp: {+ plugins: {+ marimo_plugin: {+ enabled: true,+ },+ jedi: {+ auto_import_modules: ["marimo", "numpy"],+ },+ flake8: {+ enabled: config?.enable_flake8,+ extendIgnore: ignoredFlakeRules,+ },+ pydocstyle: {+ enabled: config?.enable_pydocstyle,+ // not `addIgnore`, see https://github.com/python-lsp/python-lsp-server/issues/626+ ignore: ignoredStyleRules,+ },+ pylint: {+ enabled: config?.enable_pylint,+ },+ pyflakes: {+ enabled: config?.enable_pyflakes,+ },+ pylsp_mypy: {+ enabled: config?.enable_mypy,+ live_mode: true,+ },+ ruff: {+ enabled: config?.enable_ruff,+ extendIgnore: [+ ...ignoredFlakeRules,+ ...ignoredStyleRules,+ ...ignoredRuffRules,+ ],+ },+ },+ },+ };++ // We wrap the client in a NotebookLanguageServerClient to add some+ // additional functionality to handle multiple cells+ return new NotebookLanguageServerClient(+ new LanguageServerClient({+ ...lspClientOpts,+ documentUri: "file:///unused.py", // Incorrect types+ autoClose: false,+ }),+ settings,+ ) as unknown as LanguageServerClient;+});+import type { CellId } from "@/core/cells/ids";import { cellActionsState } from "../cells/state";/**@@ -42,25 +137,36 @@ export class PythonLanguageAdapter implements LanguageAdapter {}getExtension(- _cellId: CellId,+ cellId: CellId,completionConfig: CompletionConfig,_hotkeys: HotkeyProvider,placeholderType: PlaceholderType,+ lspConfig: LSPConfig,): Extension[] {return [- // 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],- }),+ 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],+ }),customPythonLanguageSupport(),placeholderType === "marimo-import"? Prec.highest(smartPlaceholderExtension("import marimo as mo"))diff --git a/frontend/src/core/codemirror/language/sql.ts b/frontend/src/core/codemirror/language/sql.tsindex b7951d2977..49d39e8416 100644--- a/frontend/src/core/codemirror/language/sql.ts+++ b/frontend/src/core/codemirror/language/sql.ts@@ -1,6 +1,7 @@/* Copyright 2024 Marimo. All rights reserved. */import type { Extension } from "@codemirror/state";import type { LanguageAdapter } from "./types";+// @ts-expect-error: no declaration fileimport dedent from "string-dedent";import type { CompletionConfig } from "@/core/config/config-schema";import type { HotkeyProvider } from "@/core/hotkeys/hotkeys";diff --git a/frontend/src/core/codemirror/language/types.ts b/frontend/src/core/codemirror/language/types.tsindex d9fdd5f00c..5c94e90d62 100644--- a/frontend/src/core/codemirror/language/types.ts+++ b/frontend/src/core/codemirror/language/types.ts@@ -1,5 +1,5 @@/* Copyright 2024 Marimo. All rights reserved. */-import type { CompletionConfig } from "@/core/config/config-schema";+import type { CompletionConfig, LSPConfig } from "@/core/config/config-schema";import type { HotkeyProvider } from "@/core/hotkeys/hotkeys";import type { Extension } from "@codemirror/state";import type { PlaceholderType } from "../config/extension";@@ -21,6 +21,7 @@ export interface LanguageAdapter {completionConfig: CompletionConfig,hotkeys: HotkeyProvider,placeholderType: PlaceholderType,+ lspConfig: LSPConfig,): Extension[];}diff --git a/frontend/src/core/codemirror/lsp/__tests__/notebook-lsp.test.ts b/frontend/src/core/codemirror/lsp/__tests__/notebook-lsp.test.tsnew file mode 100644index 0000000000..6a819f83f6--- /dev/null+++ b/frontend/src/core/codemirror/lsp/__tests__/notebook-lsp.test.ts@@ -0,0 +1,491 @@+/* Copyright 2024 Marimo. All rights reserved. */+/* eslint-disable @typescript-eslint/no-explicit-any */+import { describe, it, expect, vi, beforeEach, type Mocked } from "vitest";+import { createNotebookLens } from "../lens";+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";++const Cells = {+ cell1: "cell1" as CellId,+ cell2: "cell2" as CellId,+ cell3: "cell3" as CellId,+};++describe("createNotebookLens", () => {+ it("should calculate correct line offsets", () => {+ const cellIds: CellId[] = [Cells.cell1, Cells.cell2, Cells.cell3];+ const codes: Record<CellId, string> = {+ [Cells.cell1]: "fileA\nfileB",+ [Cells.cell2]: "line1\nline2",+ [Cells.cell3]: "fileC",+ };+ const lens = createNotebookLens(cellIds, codes);++ const pos: LSP.Position = { line: 0, character: 0 };+ const transformed = lens.transformPosition(pos, Cells.cell2);+ expect(transformed.line).toBe(2); // After fileA\nfileB+ expect(transformed.character).toBe(0);+ });++ it("should transform ranges to merged doc", () => {+ const cellIds: CellId[] = [Cells.cell1, Cells.cell2];+ const codes: Record<CellId, string> = {+ [Cells.cell1]: "before\ntext",+ [Cells.cell2]: "cell1\ncell2",+ };+ const lens = createNotebookLens(cellIds, codes);++ const range: LSP.Range = {+ start: { line: 0, character: 0 },+ end: { line: 1, character: 5 },+ };++ const transformed = lens.transformRange(range, Cells.cell2);+ expect(transformed.start.line).toBe(2);+ expect(transformed.end.line).toBe(3);+ });++ it("should reverse ranges from merged doc", () => {+ const cellIds: CellId[] = [Cells.cell1, Cells.cell2];+ const codes: Record<CellId, string> = {+ [Cells.cell1]: "header",+ [Cells.cell2]: "test\ncode",+ };+ const lens = createNotebookLens(cellIds, codes);++ const range: LSP.Range = {+ start: { line: 1, character: 0 },+ end: { line: 2, character: 4 },+ };++ const reversed = lens.reverseRange(range, Cells.cell2);+ expect(reversed.start.line).toBe(0);+ expect(reversed.end.line).toBe(1);+ });++ it("should check if range is within cell bounds", () => {+ const cellIds: CellId[] = [Cells.cell1];+ const codes: Record<CellId, string> = {+ [Cells.cell1]: "line1\nline2\nline3",+ };+ const lens = createNotebookLens(cellIds, codes);++ expect(+ lens.isInRange(+ {+ start: { line: 0, character: 0 },+ end: { line: 2, character: 5 },+ },+ Cells.cell1,+ ),+ ).toBe(true);++ expect(+ lens.isInRange(+ {+ start: { line: 0, character: 0 },+ end: { line: 3, character: 0 },+ },+ Cells.cell1,+ ),+ ).toBe(false);+ });++ it("should join all code into merged text", () => {+ const cellIds: CellId[] = [Cells.cell1, Cells.cell2, Cells.cell3];+ const codes: Record<CellId, string> = {+ [Cells.cell1]: "a",+ [Cells.cell2]: "cell",+ [Cells.cell3]: "b",+ };+ const lens = createNotebookLens(cellIds, codes);++ expect(lens.mergedText).toBe("a\ncell\nb");+ });++ it("should handle empty cells", () => {+ const cellIds: CellId[] = [Cells.cell1, Cells.cell2];+ const codes: Record<CellId, string> = {+ [Cells.cell1]: "",+ [Cells.cell2]: "code",+ };+ const lens = createNotebookLens(cellIds, codes);++ const pos: LSP.Position = { line: 0, character: 0 };+ const transformed = lens.transformPosition(pos, Cells.cell2);+ expect(transformed.line).toBe(1);+ });++ it("should handle cells with multiple lines", () => {+ const cellIds: CellId[] = [Cells.cell1, Cells.cell2];+ const codes: Record<CellId, string> = {+ [Cells.cell1]: "line1\nline2\nline3",+ [Cells.cell2]: "test",+ };+ const lens = createNotebookLens(cellIds, codes);++ const pos: LSP.Position = { line: 0, character: 0 };+ const transformed = lens.transformPosition(pos, Cells.cell2);+ expect(transformed.line).toBe(3);+ });+});++describe("NotebookLanguageServerClient", () => {+ let mockClient: Mocked<ILanguageServerClient>;+ let notebookClient: NotebookLanguageServerClient;++ beforeEach(() => {+ mockClient = {+ ready: true,+ capabilities: {},+ initializePromise: Promise.resolve(),+ initialize: vi.fn(),+ close: vi.fn(),+ detachPlugin: vi.fn(),+ attachPlugin: vi.fn(),+ textDocumentDidOpen: vi.fn(),+ textDocumentDidChange: vi.fn(),+ textDocumentHover: vi.fn(),+ textDocumentCompletion: vi.fn(),+ processNotification: vi.fn(),+ notify: vi.fn(),+ 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))",+ },+ });+ });++ describe("textDocumentHover", () => {+ it("should transform hover position and range", async () => {+ const hoverParams: LSP.HoverParams = {+ textDocument: { uri: "file:///cell1.py" },+ position: { line: 1, character: 5 },+ };++ const mockHoverResponse: LSP.Hover = {+ contents: {+ kind: "markdown",+ value: "test hover",+ },+ range: {+ start: { line: 2, character: 0 },+ end: { line: 2, character: 5 },+ },+ };++ mockClient.textDocumentHover.mockResolvedValue(mockHoverResponse);++ // Open a document first to set up the lens+ await notebookClient.textDocumentDidOpen({+ textDocument: {+ uri: "file:///cell1.py",+ languageId: "python",+ version: 1,+ text: "test\ncode",+ },+ });++ const result = await notebookClient.textDocumentHover(hoverParams);++ expect(result).toBeDefined();+ expect(result?.contents).toEqual({+ kind: "markdown",+ value:+ '<div class="docs-documentation mo-cm-tooltip">\ntest hover\n</div>',+ });+ });++ it("should return null for empty hover contents", async () => {+ const hoverParams: LSP.HoverParams = {+ textDocument: { uri: "file:///cell1.py" },+ position: { line: 0, character: 0 },+ };++ mockClient.textDocumentHover.mockResolvedValue({ contents: "" });++ await notebookClient.textDocumentDidOpen({+ textDocument: {+ uri: "file:///cell1.py",+ languageId: "python",+ version: 1,+ text: "test",+ },+ });++ const result = await notebookClient.textDocumentHover(hoverParams);+ expect(result).toBeNull();+ });+ });++ describe("textDocumentCompletion", () => {+ it("should transform completion position", async () => {+ const completionParams: LSP.CompletionParams = {+ textDocument: { uri: "file:///cell1.py" },+ position: { line: 0, character: 4 },+ };++ const mockCompletionResponse: LSP.CompletionList = {+ isIncomplete: false,+ items: [+ {+ label: "test_completion",+ kind: LSP.CompletionItemKind.Function,+ },+ ],+ };++ mockClient.textDocumentCompletion.mockResolvedValue(+ mockCompletionResponse,+ );++ await notebookClient.textDocumentDidOpen({+ textDocument: {+ uri: "file:///cell1.py",+ languageId: "python",+ version: 1,+ text: "test",+ },+ });++ const result =+ await notebookClient.textDocumentCompletion(completionParams);+ expect(result).toEqual(mockCompletionResponse);+ expect(mockClient.textDocumentCompletion).toHaveBeenCalledWith(+ expect.objectContaining({+ textDocument: { uri: "file:///__marimo_notebook__.py" },+ }),+ );+ });+ });++ describe("diagnostics handling", () => {+ it("should transform diagnostic ranges and filter out-of-bounds diagnostics", async () => {+ // Mock processNotification to capture the transformed diagnostics+ let capturedDiagnostics: LSP.PublishDiagnosticsParams | undefined;+ // @ts-expect-error: processNotification is private+ mockClient.processNotification = vi+ .fn()+ .mockImplementation((notification: any) => {+ if (notification.method === "textDocument/publishDiagnostics") {+ capturedDiagnostics = notification.params;+ }+ });++ // Call patch since we changed processNotification+ notebookClient.patchProcessNotification();+ // Start the document version at 1+ (notebookClient as any).documentVersion = 1;++ // Open a document+ await notebookClient.textDocumentDidOpen({+ textDocument: {+ uri: CellDocumentUri.of(Cells.cell1),+ languageId: "python",+ version: 1,+ text: "import math\nimport numpy",+ },+ });++ // Simulate receiving diagnostics+ const diagnosticsNotification = {+ method: "textDocument/publishDiagnostics",+ params: {+ uri: "file:///__marimo__.py",+ version: 1,+ diagnostics: [+ {+ range: {+ start: { line: 1, character: 0 },+ end: { line: 1, character: 4 },+ },+ message: "Test diagnostic",+ severity: LSP.DiagnosticSeverity.Error,+ },+ // Out of bounds diagnostic that should be filtered+ {+ range: {+ start: { line: 10, character: 0 },+ end: { line: 10, character: 4 },+ },+ message: "Out of bounds",+ severity: LSP.DiagnosticSeverity.Error,+ },+ ],+ },+ };++ // @ts-expect-error: processNotification is private+ notebookClient.client.processNotification(diagnosticsNotification);++ expect(capturedDiagnostics).toBeDefined();+ expect(capturedDiagnostics?.diagnostics).toHaveLength(1);+ expect(capturedDiagnostics?.diagnostics[0].range).toEqual({+ start: { line: 0, character: 0 },+ end: { line: 0, character: 4 },+ });+ });++ it("should clear diagnostics for all cells when receiving empty diagnostics", async () => {+ const seenNotifications: LSP.PublishDiagnosticsParams[] = [];+ (mockClient as any).processNotification = vi+ .fn()+ .mockImplementation((notification: any) => {+ if (notification.method === "textDocument/publishDiagnostics") {+ seenNotifications.push(notification.params);+ }+ });++ notebookClient.patchProcessNotification();+ // Start the document version at 1+ (notebookClient as any).documentVersion = 1;++ // Simulate receiving empty diagnostics+ const emptyDiagnosticsNotification = {+ method: "textDocument/publishDiagnostics",+ params: {+ uri: "file:///__marimo__.py",+ version: 1,+ diagnostics: [],+ },+ };++ // @ts-expect-error: processNotification is private+ notebookClient.client.processNotification(emptyDiagnosticsNotification);++ expect(seenNotifications.length).toBeGreaterThan(0);+ seenNotifications.forEach((notification) => {+ expect(notification.diagnostics).toHaveLength(0);+ });+ });++ it("should handle diagnostics across multiple cells", async () => {+ const seenNotifications = new Map<string, LSP.PublishDiagnosticsParams>();+ (mockClient as any).processNotification = vi+ .fn()+ .mockImplementation((notification: any) => {+ if (notification.method === "textDocument/publishDiagnostics") {+ seenNotifications.set(notification.params.uri, notification.params);+ }+ });++ notebookClient.patchProcessNotification();+ // Start the document version at 1+ (notebookClient as any).documentVersion = 1;++ // Open a document+ await notebookClient.textDocumentDidOpen({+ textDocument: {+ uri: CellDocumentUri.of(Cells.cell1),+ languageId: "python",+ version: 1,+ text: "import math\nimport numpy",+ },+ });++ // Simulate receiving diagnostics for multiple cells+ const multiCellDiagnosticsNotification = {+ method: "textDocument/publishDiagnostics",+ params: {+ uri: "file:///__marimo__.py",+ version: 1,+ diagnostics: [+ {+ range: {+ start: { line: 0, character: 0 },+ end: { line: 0, character: 4 },+ },+ message: "Cell 1 diagnostic",+ severity: LSP.DiagnosticSeverity.Error,+ },+ {+ range: {+ start: { line: 2, character: 0 },+ end: { line: 2, character: 4 },+ },+ message: "Cell 2 diagnostic",+ severity: LSP.DiagnosticSeverity.Warning,+ },+ ],+ },+ };++ // @ts-expect-error: processNotification is private+ notebookClient.client.processNotification(+ multiCellDiagnosticsNotification,+ );++ expect(seenNotifications.size).toBe(2);+ const cell1Uri = CellDocumentUri.of(Cells.cell1);+ const cell2Uri = CellDocumentUri.of(Cells.cell2);++ expect(seenNotifications.get(cell1Uri)?.diagnostics).toHaveLength(1);+ expect(seenNotifications.get(cell2Uri)?.diagnostics).toHaveLength(1);+ expect(seenNotifications.get(cell1Uri)?.diagnostics[0].message).toBe(+ "Cell 1 diagnostic",+ );+ expect(seenNotifications.get(cell2Uri)?.diagnostics[0].message).toBe(+ "Cell 2 diagnostic",+ );+ });++ it("should handle version updates in textDocumentDidChange", async () => {+ let capturedChange: LSP.DidChangeTextDocumentParams | undefined;+ mockClient.textDocumentDidChange = vi+ .fn()+ .mockImplementation((params) => {+ capturedChange = params;+ });++ await notebookClient.textDocumentDidChange({+ textDocument: {+ uri: CellDocumentUri.of(Cells.cell1),+ version: 5,+ },+ contentChanges: [{ text: "new code" }],+ });++ expect(capturedChange).toBeDefined();+ expect(capturedChange?.textDocument.version).toBeGreaterThan(0);+ expect(capturedChange?.contentChanges).toHaveLength(1);+ expect(capturedChange?.contentChanges[0].text).toMatchInlineSnapshot(`+ "# this is a comment+ import math+ import numpy+ print(math.sqrt(4))"+ `);+ });+ });++ describe("initialization and configuration", () => {+ it("should send configuration after initialization", async () => {+ const configNotifications: any[] = [];+ (mockClient as any).notify = vi+ .fn()+ .mockImplementation((method, params) => {+ configNotifications.push({ method, params });+ });++ // Create a new client to trigger initialization+ const client = new NotebookLanguageServerClient(mockClient, {});+ await client.initialize();++ expect(configNotifications[0]).toMatchInlineSnapshot(`+ {+ "method": "workspace/didChangeConfiguration",+ "params": {+ "settings": {},+ },+ }+ `);+ });+ });+});diff --git a/frontend/src/core/codemirror/lsp/lens.ts b/frontend/src/core/codemirror/lsp/lens.tsnew file mode 100644index 0000000000..24c284305d--- /dev/null+++ b/frontend/src/core/codemirror/lsp/lens.ts@@ -0,0 +1,85 @@+/* Copyright 2024 Marimo. All rights reserved. */+import type { CellId } from "@/core/cells/ids";+import type * as LSP from "vscode-languageserver-protocol";++export interface NotebookLens {+ /** The ids of the cells in the notebook */+ cellIds: CellId[];++ /** The merged text of all cells in the notebook */+ mergedText: string;++ /** Transform a range from cell coordinates to notebook coordinates */+ transformRange: (range: LSP.Range, cellId: CellId) => LSP.Range;+ /** Transform a range from notebook coordinates back to cell coordinates */+ reverseRange: (range: LSP.Range, cellId: CellId) => LSP.Range;+ /** Transform a position from cell coordinates to notebook coordinates */+ transformPosition: (position: LSP.Position, cellId: CellId) => LSP.Position;+ /** Transform a position from notebook coordinates back to cell coordinates */+ reversePosition: (position: LSP.Position, cellId: CellId) => LSP.Position;++ /** Check if a range falls within the given cell */+ isInRange: (range: LSP.Range, cellId: CellId) => boolean;+}++/**+ * Basic utility for "zooming" a cell into the larger notebook context+ * and then "unzooming" ranges from the merged doc back to the original cell.+ */+export function createNotebookLens(+ sortedCellIds: CellId[],+ codes: Record<CellId, string>,+): NotebookLens {+ const cellLineOffsets = new Map<CellId, number>();++ // Calculate line offsets for each cell+ let currentOffset = 0;+ sortedCellIds.forEach((cellId) => {+ cellLineOffsets.set(cellId, currentOffset);+ currentOffset += codes[cellId].split("\n").length;+ });++ function getCurrentLineOffset(cellId: CellId): number {+ return cellLineOffsets.get(cellId) || 0;+ }++ return {+ cellIds: sortedCellIds,++ mergedText: Object.values(codes).join("\n"),++ transformRange: (range: LSP.Range, cellId: CellId) =>+ shiftRange(range, getCurrentLineOffset(cellId)),++ reverseRange: (range: LSP.Range, cellId: CellId) =>+ shiftRange(range, -getCurrentLineOffset(cellId)),++ isInRange: (range: LSP.Range, cellId: CellId) => {+ const cellLines = codes[cellId].split("\n").length;+ const offset = cellLineOffsets.get(cellId) || 0;+ const startLine = range.start.line - offset;+ const endLine = range.end.line - offset;+ return startLine >= 0 && endLine < cellLines;+ },++ transformPosition: (position: LSP.Position, cellId: CellId) =>+ shiftPosition(position, getCurrentLineOffset(cellId)),++ reversePosition: (position: LSP.Position, cellId: CellId) =>+ shiftPosition(position, -getCurrentLineOffset(cellId)),+ };+}++function shiftRange(range: LSP.Range, offset: number): LSP.Range {+ return {+ start: shiftPosition(range.start, offset),+ end: shiftPosition(range.end, offset),+ };+}++function shiftPosition(position: LSP.Position, offset: number): LSP.Position {+ return {+ line: position.line + offset,+ character: position.character,+ };+}diff --git a/frontend/src/core/codemirror/lsp/notebook-lsp.ts b/frontend/src/core/codemirror/lsp/notebook-lsp.tsnew file mode 100644index 0000000000..bc7aea5406--- /dev/null+++ b/frontend/src/core/codemirror/lsp/notebook-lsp.ts@@ -0,0 +1,378 @@+/* Copyright 2024 Marimo. All rights reserved. */+import type * as LSP from "vscode-languageserver-protocol";+import { getTopologicalCodes } from "../copilot/getCodes";+import { createNotebookLens } from "./lens";+import { CellDocumentUri, type ILanguageServerClient } from "./types";+import { invariant } from "@/utils/invariant";+import { Logger } from "@/utils/Logger";+import { LRUCache } from "@/utils/lru";+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"}`;+ private documentVersion = 0;+ private readonly client: ILanguageServerClient;++ /**+ * 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>;+ }+ >(20);++ private static readonly SEEN_CELL_DOCUMENT_URIS = new Set<LSP.DocumentUri>();++ constructor(+ client: ILanguageServerClient,+ initialSettings: Record<string, unknown>,+ ) {+ this.client = client;+ this.patchProcessNotification();++ // Handle configuration after initialization+ this.initializePromise.then(() => {+ invariant(+ "notify" in this.client,+ "notify is not a method on the client",+ );++ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ (this.client as any).notify("workspace/didChangeConfiguration", {+ settings: initialSettings,+ });+ });+ }+ textDocumentDefinition(+ params: LSP.DefinitionParams,+ ): Promise<LSP.Definition | LSP.LocationLink[] | null> {+ return this.client.textDocumentDefinition(params);+ }++ textDocumentCodeAction(+ params: LSP.CodeActionParams,+ ): Promise<Array<LSP.Command | LSP.CodeAction> | null> {+ const disabledCodeAction = true;+ if (disabledCodeAction) {+ return Promise.resolve(null);+ }+ return this.client.textDocumentCodeAction(params);+ }++ textDocumentRename(+ params: LSP.RenameParams,+ ): Promise<LSP.WorkspaceEdit | null> {+ return this.client.textDocumentRename(params);+ }++ completionItemResolve(+ params: LSP.CompletionItem,+ ): Promise<LSP.CompletionItem> {+ return this.client.completionItemResolve(params);+ }++ textDocumentPrepareRename(+ params: LSP.PrepareRenameParams,+ ): Promise<LSP.PrepareRenameResult | null> {+ return this.client.textDocumentPrepareRename(params);+ }++ 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;+ }++ 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,+ });+ 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;+ const globalDocumentVersion = this.documentVersion + 1;++ 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);++ const hover = await this.client.textDocumentHover({+ ...params,+ textDocument: {+ uri: this.documentUri,+ },+ position: lens.transformPosition(params.position, cellId),+ });++ if (!hover) {+ Logger.debug("[lsp] no hover result");+ return hover;+ }++ // Change content kind to markdown and wrap in our classnames+ 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>`,+ };+ }++ // Empty+ if (hover.contents === "") {+ // Handled downstream, but the types are off+ return null as unknown as LSP.Hover;+ }++ // Convert ranges back to cell coordinates+ if (hover.range) {+ hover.range = lens.reverseRange(hover.range, cellId);+ }+ return hover;+ }++ 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);++ return this.client.textDocumentCompletion({+ ...params,+ textDocument: {+ uri: this.documentUri,+ },+ position: lens.transformPosition(params.position, cellId),+ });+ }++ /**+ * Handle diagnostics from the server. We intercept notifications for publishDiagnostics+ * and shift ranges back to the local cell coordinates.+ */+ public patchProcessNotification() {+ invariant(+ "processNotification" in this.client,+ "processNotification is not a method on the client",+ );++ // @ts-expect-error: processNotification is private+ const previousProcessNotification = this.client.processNotification.bind(+ this.client,+ );++ const processNotification = (+ notification:+ | {+ method: "textDocument/publishDiagnostics";+ params: LSP.PublishDiagnosticsParams;+ }+ | { method: "other"; params: unknown },+ ) => {+ 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 diagnostics = notification.params.diagnostics;++ // If diagnostics are empty, we can just clear them for all cells+ if (diagnostics.length === 0) {+ Logger.debug("[lsp] clearing diagnostics");++ for (const cellDocumentUri of NotebookLanguageServerClient.SEEN_CELL_DOCUMENT_URIS) {+ previousProcessNotification({+ method: "textDocument/publishDiagnostics",+ params: {+ uri: cellDocumentUri,+ diagnostics: [],+ },+ });+ }+ return;+ }++ const { lens, version: cellVersion } = payload;++ // Pre-partition diagnostics by cell+ const diagnosticsByCellId = new Map<CellId, LSP.Diagnostic[]>();++ for (const diag of diagnostics) {+ // Each diagnostic can only belong to one cell+ for (const cellId of lens.cellIds) {+ if (lens.isInRange(diag.range, cellId)) {+ if (!diagnosticsByCellId.has(cellId)) {+ diagnosticsByCellId.set(cellId, []);+ }+ const cellDiag = {+ ...diag,+ range: lens.reverseRange(diag.range, cellId),+ };+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion+ diagnosticsByCellId.get(cellId)!.push(cellDiag);+ break; // Exit inner loop once we find the matching cell+ }+ }+ }++ // Process each cell's diagnostics+ for (const [cellId, cellDiagnostics] of diagnosticsByCellId.entries()) {+ Logger.debug("[lsp] diagnostics for cell", cellId, cellDiagnostics);++ previousProcessNotification({+ ...notification,+ params: {+ ...notification.params,+ uri: CellDocumentUri.of(cellId),+ version: cellVersion,+ diagnostics: cellDiagnostics,+ },+ });+ }++ return;+ }++ return previousProcessNotification(notification);+ };++ this.client.processNotification = processNotification;+ }+}diff --git a/frontend/src/core/codemirror/lsp/types.ts b/frontend/src/core/codemirror/lsp/types.tsnew file mode 100644index 0000000000..8ad970075b--- /dev/null+++ b/frontend/src/core/codemirror/lsp/types.ts@@ -0,0 +1,23 @@+/* Copyright 2024 Marimo. All rights reserved. */+import type { CellId } from "@/core/cells/ids";+import { invariant } from "@/utils/invariant";+import type { LanguageServerClient } from "@marimo-team/codemirror-languageserver";+import type { DocumentUri } from "vscode-languageserver-protocol";++export type ILanguageServerClient = {+ [key in keyof LanguageServerClient]: LanguageServerClient[key];+};++export const CellDocumentUri = {+ PREFIX: "file:///",+ of(cellId: CellId): DocumentUri {+ return `${this.PREFIX}${cellId}`;+ },+ is(uri: string): uri is DocumentUri {+ return uri.startsWith(this.PREFIX);+ },+ parse(uri: string): CellId {+ invariant(this.is(uri), `Invalid cell document URI: ${uri}`);+ return uri.slice(this.PREFIX.length) as CellId;+ },+};diff --git a/frontend/src/core/config/config-schema.ts b/frontend/src/core/config/config-schema.tsindex f14446f984..2d775b0003 100644--- a/frontend/src/core/config/config-schema.ts+++ b/frontend/src/core/config/config-schema.ts@@ -164,6 +164,7 @@ export type UserConfig = MarimoConfig;export type SaveConfig = UserConfig["save"];export type CompletionConfig = UserConfig["completion"];export type KeymapConfig = UserConfig["keymap"];+export type LSPConfig = UserConfig["language_servers"];export const AppTitleSchema = z.string();export const AppConfigSchema = zdiff --git a/frontend/src/core/config/feature-flag.tsx b/frontend/src/core/config/feature-flag.tsxindex 98ca70b798..f8c4a7ce54 100644--- a/frontend/src/core/config/feature-flag.tsx+++ b/frontend/src/core/config/feature-flag.tsx@@ -7,6 +7,7 @@ import { getResolvedMarimoConfig } from "./config";// eslint-disable-next-line @typescript-eslint/no-empty-interfaceexport interface ExperimentalFeatures {+ lsp: boolean;markdown: boolean;inline_ai_tooltip: boolean;wasm_layouts: boolean;@@ -18,6 +19,7 @@ export interface ExperimentalFeatures {}const defaultValues: ExperimentalFeatures = {+ lsp: import.meta.env.DEV,markdown: true,inline_ai_tooltip: import.meta.env.DEV,wasm_layouts: false,diff --git a/frontend/src/utils/once.ts b/frontend/src/utils/once.tsindex bed44d5d63..8e96ea782c 100644--- a/frontend/src/utils/once.ts+++ b/frontend/src/utils/once.ts@@ -1,5 +1,7 @@/* Copyright 2024 Marimo. All rights reserved. */-export function once<T extends (...args: unknown[]) => unknown>(fn: T): T {++// eslint-disable-next-line @typescript-eslint/no-explicit-any+export function once<T extends (...args: any[]) => any>(fn: T): T {let result: ReturnType<T>;let called = false;return function (diff --git a/frontend/tsconfig.json b/frontend/tsconfig.jsonindex 437e22972a..8c419c750e 100644--- a/frontend/tsconfig.json+++ b/frontend/tsconfig.json@@ -30,7 +30,7 @@/* Modules */"module": "ESNext" /* Specify what module code is generated. */,"rootDir": "src" /* Specify the root folder within your source files. */,- "moduleResolution": "node" /* Specify how TypeScript looks up a file from a given module specifier. */,+ "moduleResolution": "Bundler" /* Specify how TypeScript looks up a file from a given module specifier. */,"baseUrl": "src" /* Specify the base directory to resolve non-relative module names. */,// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */diff --git a/marimo/_config/config.py b/marimo/_config/config.pyindex 77a5856977..52f1050b72 100644--- a/marimo/_config/config.py+++ b/marimo/_config/config.py@@ -251,6 +251,31 @@ class GoogleAiConfig(TypedDict, total=False):api_key: str+@dataclass+class PythonLanguageServerConfig(TypedDict, total=False):+ """Configuration options for Python Language Server."""++ enabled: bool+ enable_mypy: bool+ enable_ruff: bool+ enable_flake8: bool+ enable_pydocstyle: bool+ enable_pylint: bool+ enable_pyflakes: bool+++@dataclass+class LanguageServersConfig(TypedDict, total=False):+ """Configuration options for language servers.++ **Keys.**++ - `pylsp`: the pylsp config+ """++ pylsp: PythonLanguageServerConfig++@dataclassclass SnippetsConfig(TypedDict):"""Configuration for snippets.@@ -294,6 +319,7 @@ class MarimoConfig(TypedDict):server: ServerConfigpackage_management: PackageManagementConfigai: NotRequired[AiConfig]+ language_servers: NotRequired[LanguageServersConfig]experimental: NotRequired[dict[str, Any]]snippets: NotRequired[SnippetsConfig]datasources: NotRequired[DatasourcesConfig]@@ -313,6 +339,7 @@ class PartialMarimoConfig(TypedDict, total=False):server: ServerConfigpackage_management: PackageManagementConfigai: NotRequired[AiConfig]+ language_servers: NotRequired[LanguageServersConfig]experimental: NotRequired[dict[str, Any]]snippets: SnippetsConfigdatasources: NotRequired[DatasourcesConfig]@@ -352,6 +379,17 @@ DEFAULT_CONFIG: MarimoConfig = {"browser": "default","follow_symlink": False,},+ "language_servers": {+ "pylsp": {+ "enabled": True,+ "enable_mypy": True,+ "enable_ruff": True,+ "enable_flake8": False,+ "enable_pydocstyle": False,+ "enable_pylint": False,+ "enable_pyflakes": False,+ }+ },"snippets": {"custom_paths": [],"include_default_snippets": True,diff --git a/marimo/_dependencies/dependencies.py b/marimo/_dependencies/dependencies.pyindex 5a6ec6c9e5..7a73e8e9aa 100644--- a/marimo/_dependencies/dependencies.py+++ b/marimo/_dependencies/dependencies.py@@ -190,6 +190,7 @@ class DependencyManager:groq = Dependency("groq")panel = Dependency("panel")sqlalchemy = Dependency("sqlalchemy")+ pylsp = Dependency("pylsp")vegafusion = Dependency("vegafusion")vl_convert_python = Dependency("vl_convert")diff --git a/marimo/_server/api/lifespans.py b/marimo/_server/api/lifespans.pyindex 0193759713..4a4ad3a997 100644--- a/marimo/_server/api/lifespans.py+++ b/marimo/_server/api/lifespans.py@@ -7,6 +7,7 @@ import socketimport sysfrom collections.abc import AsyncIterator, Callable, Sequencefrom contextlib import AbstractAsyncContextManager+from typing import Any, castfrom starlette.applications import Starlette@@ -73,9 +74,23 @@ async def lsp(app: Starlette) -> AsyncIterator[None]:user_config = state.config_manager.get_config()session_mgr = state.session_managerrun = session_mgr.mode == SessionMode.RUN- if not run and user_config["completion"]["copilot"]:- LOGGER.debug("GitHub Copilot is enabled")- await session_mgr.start_lsp_server()++ if not run:+ # Check if any language servers or copilot are enabled+ copilot_enabled = user_config["completion"]["copilot"]+ language_servers = user_config.get("language_servers", {})+ language_servers_enabled = any(+ cast(dict[str, Any], server).get("enabled", False)+ for server in language_servers.values()+ )++ if copilot_enabled:+ LOGGER.debug("GitHub Copilot is enabled")++ if copilot_enabled or language_servers_enabled:+ LOGGER.debug("Language Servers are enabled")+ await session_mgr.start_lsp_server()+yielddiff --git a/marimo/_server/asgi.py b/marimo/_server/asgi.pyindex b3be46240a..1a43336534 100644--- a/marimo/_server/asgi.py+++ b/marimo/_server/asgi.py@@ -383,9 +383,10 @@ def create_asgi_app(import marimo._server.api.lifespans as lifespansfrom marimo._config.manager import get_default_config_managerfrom marimo._server.file_router import AppFileRouter+ from marimo._server.lsp import NoopLspServerfrom marimo._server.main import create_starlette_appfrom marimo._server.model import SessionMode- from marimo._server.sessions import NoopLspServer, SessionManager+ from marimo._server.sessions import SessionManagerfrom marimo._server.tokens import AuthTokenfrom marimo._server.utils import initialize_asynciofrom marimo._utils.marimo_path import MarimoPathdiff --git a/marimo/_server/lsp.py b/marimo/_server/lsp.pynew file mode 100644index 0000000000..a0ffcb3dca--- /dev/null+++ b/marimo/_server/lsp.py@@ -0,0 +1,263 @@+from __future__ import annotations++import os+import shutil+import subprocess+from abc import ABC, abstractmethod+from typing import Any, Optional, cast++from marimo import _loggers+from marimo._config.config import CompletionConfig, LanguageServersConfig+from marimo._config.settings import GLOBAL_SETTINGS+from marimo._dependencies.dependencies import DependencyManager+from marimo._messaging.ops import (+ Alert,+)+from marimo._runtime.complete import _get_docstring+from marimo._server.utils import find_free_port+from marimo._tracer import server_tracer+from marimo._utils.paths import import_files++LOGGER = _loggers.marimo_logger()+++class LspServer(ABC):+ port: int+ id: str++ @abstractmethod+ def start(self) -> Optional[Alert]:+ pass++ @abstractmethod+ def stop(self) -> None:+ pass++ @abstractmethod+ def is_running(self) -> bool:+ pass+++class BaseLspServer(LspServer):+ def __init__(self, port: int) -> None:+ self.port = port+ self.process: Optional[subprocess.Popen[bytes]] = None++ @server_tracer.start_as_current_span("lsp_server.start")+ def start(self) -> Optional[Alert]:+ if self.process is not None:+ LOGGER.debug("LSP server already started")+ return None++ binpath = shutil.which(self.binary_name())+ LOGGER.debug("binpath %s", binpath)+ if binpath is None:+ LOGGER.error(+ f"{self.binary_name()} not found; cannot start LSP server."+ )+ return self.missing_binary_alert()++ cmd = None+ try:+ LOGGER.debug("Starting LSP server at port %s...", self.port)+ cmd = self.get_command()++ # Empty command means the server is not enabled+ if not cmd:+ return None++ file_out = (+ None+ if GLOBAL_SETTINGS.DEVELOPMENT_MODE+ else subprocess.DEVNULL+ )+ LOGGER.debug("... running command: %s", cmd)+ self.process = subprocess.Popen(+ cmd.split(),+ stdout=file_out,+ stderr=file_out,+ stdin=None,+ )+ LOGGER.debug(+ "... process return code (`None` means success): %s",+ self.process.returncode,+ )+ LOGGER.debug("Started LSP server at port %s", self.port)+ except Exception as e:+ LOGGER.error(+ "When starting language server (%s), got error: %s",+ cmd,+ e,+ )+ self.process = None++ return None++ def is_running(self) -> bool:+ if self.process is None:+ return False+ # check if the process is still running+ self.process.poll()+ return self.process.returncode is not None++ def stop(self) -> None:+ if self.process is not None:+ self.process.terminate()+ self.process = None+ LOGGER.debug("Stopped LSP server at port %s", self.port)+ else:+ LOGGER.debug("LSP server not running")++ def binary_name(self) -> str:+ raise NotImplementedError()++ def get_command(self) -> str:+ raise NotImplementedError()++ def missing_binary_alert(self) -> Alert:+ raise NotImplementedError()+++class CopilotLspServer(BaseLspServer):+ id = "copilot"++ def binary_name(self) -> str:+ return "node"++ def _lsp_bin(self) -> str:+ lsp_bin = os.path.join(+ str(import_files("marimo").joinpath("_lsp")),+ "index.js",+ )+ return lsp_bin++ def get_command(self) -> str:+ lsp_bin = self._lsp_bin()+ # Check if the LSP binary exists+ if not os.path.exists(lsp_bin):+ # Only debug since this may not exist in conda environments+ LOGGER.debug("LSP binary not found at %s", lsp_bin)+ return ""+ return f"node {lsp_bin} --port {self.port}"++ def missing_binary_alert(self) -> Alert:+ return Alert(+ title="GitHub Copilot: Connection Error",+ description="<span><a class='hyperlink' href='https://docs.marimo.io/getting_started/index.html#github-copilot'>Install Node.js</a> to use copilot.</span>",+ variant="danger",+ )+++class PyLspServer(BaseLspServer):+ id = "pylsp"++ def binary_name(self) -> str:+ return "pylsp"++ def get_command(self) -> str:+ return f"pylsp --ws -v --port {self.port} --check-parent-process"++ def missing_binary_alert(self) -> Alert:+ return Alert(+ title="Python LSP: Connection Error",+ description="<span><a class='hyperlink' href='https://github.com/python-lsp/python-lsp-server'>Install python-lsp-server</a> for Python language support.</span>",+ variant="danger",+ )+++class NoopLspServer(LspServer):+ def start(self) -> None:+ pass++ def stop(self) -> None:+ pass++ def is_running(self) -> bool:+ return False+++class CompositeLspServer(LspServer):+ language_servers = {+ "pylsp": PyLspServer,+ "copilot": CopilotLspServer,+ }++ def __init__(+ self,+ lsp_config: LanguageServersConfig,+ completion_config: CompletionConfig,+ min_port: int,+ ) -> None:+ is_enabled: dict[str, bool] = {+ "copilot": (+ completion_config["copilot"] is True+ or completion_config["copilot"] == "github"+ ),+ **{+ server_name: cast(dict[str, bool], config)["enabled"]+ for server_name, config in lsp_config.items()+ },+ # While under development, only allow if it's installed and enabled+ "pylsp": DependencyManager.which("pylsp")+ and lsp_config.get("pylsp", {}).get("enabled", False),+ }+ self.servers: list[LspServer] = [+ constructor(find_free_port(min_port + 100 * i))+ for i, (server_name, constructor) in enumerate(+ self.language_servers.items()+ )+ if is_enabled.get(server_name, False)+ ]++ def start(self) -> None:+ for server in self.servers:+ server.start()++ def stop(self) -> None:+ for server in self.servers:+ server.stop()++ def is_running(self) -> bool:+ return any(server.is_running() for server in self.servers)+++if DependencyManager.pylsp.has():+ from pylsp import hookimpl # type: ignore[import-untyped,import-not-found]++ @hookimpl(tryfirst=True) # type: ignore[misc]+ def pylsp_hover(+ config: Any, document: Any, position: dict[str, int]+ ) -> Optional[dict[str, Any]]:+ try:+ del config+ LOGGER.debug("Hovering over %s", document.path)+ import jedi # type: ignore[import-untyped]++ # Use Jedi to get information about the symbol under cursor+ script = jedi.Script(document.source, path=document.path)++ definitions = script.goto(+ position["line"] + 1, position["character"]+ )++ if not definitions:+ return None++ definition = definitions[0]++ docstring = _get_docstring(definition)++ if not docstring:+ return None++ return {"contents": {"kind": "markdown", "value": docstring}}+ except Exception:+ return None++ @hookimpl() # type: ignore[misc]+ def pylsp_completions(+ document: Any, position: dict[str, int]+ ) -> Optional[list[dict[str, Any]]]:+ del document+ del position+ return Nonediff --git a/marimo/_server/main.py b/marimo/_server/main.pyindex f237fdde8c..7fcfa5365a 100644--- a/marimo/_server/main.py+++ b/marimo/_server/main.py@@ -1,6 +1,7 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+from dataclasses import dataclassfrom typing import TYPE_CHECKING, Optionalfrom starlette.applications import Starlette@@ -26,6 +27,7 @@ from marimo._server.api.status import (HTTPException as MarimoHTTPException,)from marimo._server.errors import handle_error+from marimo._server.lsp import LspServerif TYPE_CHECKING:from starlette.types import Lifespan@@ -33,6 +35,12 @@ if TYPE_CHECKING:LOGGER = _loggers.marimo_logger()+@dataclass+class LspPorts:+ pylsp: Optional[int]+ copilot: Optional[int]++# Create appdef create_starlette_app(*,@@ -42,7 +50,7 @@ def create_starlette_app(lifespan: Optional[Lifespan[Starlette]] = None,enable_auth: bool = True,allow_origins: Optional[tuple[str, ...]] = None,- lsp_port: Optional[int] = None,+ lsp_servers: Optional[list[LspServer]] = None,) -> Starlette:final_middlewares: list[Middleware] = []@@ -81,8 +89,10 @@ def create_starlette_app(])- if lsp_port is not None:- final_middlewares.append(_create_lsp_proxy_middleware(lsp_port))+ if lsp_servers is not None:+ final_middlewares.extend(+ _create_lsps_proxy_middleware(servers=lsp_servers)+ )if middleware:final_middlewares.extend(middleware)@@ -119,11 +129,21 @@ def _create_mpl_proxy_middleware() -> Middleware:)-def _create_lsp_proxy_middleware(lsp_port: int) -> Middleware:- return Middleware(- ProxyMiddleware,- proxy_path="/lsp",- target_url=f"http://localhost:{lsp_port}",- # Remove the /lsp prefix- path_rewrite=lambda path: path.replace("/lsp", ""),- )+def _create_lsps_proxy_middleware(+ *, servers: list[LspServer]+) -> list[Middleware]:+ middlewares: list[Middleware] = []+ for server in servers:+ to_replace = "/lsp" if server.id == "copilot" else f"/lsp/{server.id}"+ middlewares.append(+ Middleware(+ ProxyMiddleware,+ proxy_path=f"/lsp/{server.id}",+ target_url=f"http://localhost:{server.port}",+ path_rewrite=lambda path: path.replace(+ to_replace, # noqa: B023+ "",+ ),+ )+ )+ return middlewaresdiff --git a/marimo/_server/sessions.py b/marimo/_server/sessions.pyindex 5edff3a4ed..6f1f99b93c 100644--- a/marimo/_server/sessions.py+++ b/marimo/_server/sessions.py@@ -18,9 +18,7 @@ import asyncioimport multiprocessing as mpimport osimport queue-import shutilimport signal-import subprocessimport sysimport threadingimport time@@ -40,7 +38,6 @@ from marimo._config.manager import ()from marimo._config.settings import GLOBAL_SETTINGSfrom marimo._messaging.ops import (- Alert,FocusCell,MessageOperation,Reload,@@ -63,6 +60,7 @@ from marimo._runtime.requests import (from marimo._server.exceptions import InvalidSessionExceptionfrom marimo._server.file_manager import AppFileManagerfrom marimo._server.file_router import AppFileRouter, MarimoFileKey+from marimo._server.lsp import LspServerfrom marimo._server.model import ConnectionState, SessionConsumer, SessionModefrom marimo._server.models.models import InstantiateRequestfrom marimo._server.recents import RecentFilesManager@@ -73,7 +71,6 @@ from marimo._server.session.session_view import SessionViewfrom marimo._server.tokens import AuthToken, SkewProtectionTokenfrom marimo._server.types import QueueTypefrom marimo._server.utils import print_, print_tabbed-from marimo._tracer import server_tracerfrom marimo._types.ids import CellId_t, ConsumerId, SessionIdfrom marimo._utils.disposable import Disposablefrom marimo._utils.distributor import (@@ -81,7 +78,6 @@ from marimo._utils.distributor import (QueueDistributor,)from marimo._utils.file_watcher import FileWatcherManager-from marimo._utils.paths import import_filesfrom marimo._utils.repr import format_reprfrom marimo._utils.typed_connection import TypedConnection@@ -1127,86 +1123,6 @@ class SessionManager:)-class LspServer:- def __init__(self, port: int) -> None:- self.port = port- self.process: Optional[subprocess.Popen[bytes]] = None-- @server_tracer.start_as_current_span("lsp_server.start")- def start(self) -> Optional[Alert]:- if self.process is not None:- LOGGER.debug("LSP server already started")- return None-- binpath = shutil.which("node")- if binpath is None:- LOGGER.error("Node.js not found; cannot start LSP server.")- return Alert(- title="GitHub Copilot: Connection Error",- description="<span><a class='hyperlink' href='https://docs.marimo.io/getting_started/index.html#github-copilot'>Install Node.js</a> to use copilot.</span>", # noqa: E501- variant="danger",- )-- cmd = None- try:- LOGGER.debug("Starting LSP server at port %s...", self.port)- lsp_bin = os.path.join(- str(import_files("marimo").joinpath("_lsp")),- "index.js",- )-- # Check if the LSP binary exists- if not os.path.exists(lsp_bin):- # Only debug since this may not exist in conda environments- LOGGER.debug("LSP binary not found at %s", lsp_bin)- return None-- cmd = f"node {lsp_bin} --port {self.port}"- LOGGER.debug("... running command: %s", cmd)- self.process = subprocess.Popen(- cmd.split(),- stdout=subprocess.DEVNULL,- stderr=subprocess.DEVNULL,- stdin=subprocess.DEVNULL,- )- LOGGER.debug(- "... node process return code (`None` means success): %s",- self.process.returncode,- )- LOGGER.debug("Started LSP server at port %s", self.port)- except Exception as e:- LOGGER.error(- "When starting language server (%s), got error: %s",- cmd,- e,- )- self.process = None-- return None-- def is_running(self) -> bool:- return self.process is not None-- def stop(self) -> None:- if self.process is not None:- self.process.terminate()- self.process = None- LOGGER.debug("Stopped LSP server at port %s", self.port)- else:- LOGGER.debug("LSP server not running")---class NoopLspServer(LspServer):- def __init__(self) -> None:- super().__init__(0)-- def start(self) -> None:- pass-- def stop(self) -> None:- pass--def send_message_to_consumer(session: Session,operation: MessageOperation,diff --git a/marimo/_server/start.py b/marimo/_server/start.pyindex be9d26bea0..819cdf9606 100644--- a/marimo/_server/start.py+++ b/marimo/_server/start.py@@ -9,12 +9,13 @@ import uvicornimport marimo._server.api.lifespans as lifespansfrom marimo._config.manager import get_default_config_manager-from marimo._config.settings import GlobalSettings+from marimo._config.settings import GLOBAL_SETTINGSfrom marimo._runtime.requests import SerializedCLIArgsfrom marimo._server.file_router import AppFileRouter+from marimo._server.lsp import CompositeLspServerfrom marimo._server.main import create_starlette_appfrom marimo._server.model import SessionMode-from marimo._server.sessions import LspServer, SessionManager+from marimo._server.sessions import SessionManagerfrom marimo._server.tokens import AuthTokenfrom marimo._server.utils import (find_free_port,@@ -92,7 +93,6 @@ def start(# Find a free port if none is specified# if the user specifies a port, we don't try to find a free oneport = port or find_free_port(DEFAULT_PORT)- lsp_port = find_free_port(DEFAULT_PORT + 200) # Add 200 to avoid conflicts# This is the path that will be used to read the project configurationstart_path: Optional[str] = None@@ -105,6 +105,18 @@ def start(config_reader = get_default_config_manager(current_path=start_path)+ user_config = config_reader.get_config()++ lsp_composite_server = CompositeLspServer(+ lsp_config=(+ user_config["language_servers"]+ if "language_servers" in user_config+ else {}+ ),+ completion_config=user_config["completion"],+ min_port=DEFAULT_PORT + 400,+ )+# If watch is true, disable auto-save and format-on-save,# watch is enabled when they are editing in another editorif watch:@@ -119,7 +131,7 @@ def start()LOGGER.info("Watch mode enabled, auto-save is disabled")- if GlobalSettings.MANAGE_SCRIPT_METADATA:+ if GLOBAL_SETTINGS.MANAGE_SCRIPT_METADATA:config_reader = config_reader.with_overrides({# Currently, only uv is supported for managing script metadata@@ -138,7 +150,7 @@ def start(quiet=quiet,include_code=include_code,ttl_seconds=ttl_seconds,- lsp_server=LspServer(lsp_port),+ lsp_server=lsp_composite_server,config_manager=config_reader,cli_args=cli_args,auth_token=auth_token,@@ -163,11 +175,10 @@ def start(),allow_origins=allow_origins,enable_auth=not AuthToken.is_empty(session_manager.auth_token),- lsp_port=lsp_port,+ lsp_servers=lsp_composite_server.servers,)app.state.port = external_port- app.state.lsp_port = lsp_portapp.state.host = external_hostapp.state.headless = headlessdiff --git a/marimo/_smoke_tests/lsp/ruff_errors.py b/marimo/_smoke_tests/lsp/ruff_errors.pynew file mode 100644index 0000000000..be3370e1b1--- /dev/null+++ b/marimo/_smoke_tests/lsp/ruff_errors.py@@ -0,0 +1,118 @@+import marimo++__generated_with = "0.11.19"+app = marimo.App(width="medium")+++def _():+ import marimo as mo+ return (mo,)+++def _():+ # Commented out because doesn't surface other errors; uncomment to surface.++ # # mixed indentation+ # def bad_indentation():+ # print("correct")+ # print("wrong")+ return+++app._unparsable_cell(+ r"""+ # fmt: off+ import os+ import sys+ from typing import List, Dict+ import random++ # undefined variable+ result = undefined_var + 10++ # unused import+ import json++ # unused variable+ unused_variable = 42++ # missing type hints+ def add_numbers(a, b):+ return a + b++ # undefined name+ print(nonexistent_variable)++ # too many blank lines+++++ # missing docstring+ class MyClass:+ def __init__(self):+ self.value = 10++ # unused method parameter+ def process_data(data, unused_param):+ return data * 2++ # variable shadowing+ def shadow_test():+ x = 5+ for x in range(3):+ print(x)++ # mutable default argument+ def risky_function(items=[]):+ items.append(1)+ return items++ # star imports+ from os import *++ # too many arguments+ def too_many_args(a,b,c,d,e,f,g,h,i,j,k):+ return a+b++ # bare except+ try:+ risky_operation()+ except:+ pass++ # redefining built-in+ list = []+ str = \"hello\"+ def print():+ pass++ # missing final newline++ # line too long+ very_long_variable_name = \"This is an extremely long line that exceeds the recommended maximum line length and should trigger a linting warning\"++ # multiple statements on one line+ x = 5; y = 10; z = 15++ # complex boolean expression+ if x == True and y == False and z == True and zz == False:+ pass++ # wrong variable name style+ camelCaseVariable = 123++ # undefined name in type annotation+ def process_items(items: InvalidType) -> None:+ pass++ # fmt: on+ """,+ name="_"+)+++if __name__ == "__main__":+ app.run()diff --git a/openapi/api.yaml b/openapi/api.yamlindex a25855be3f..cfdb8744bf 100644--- a/openapi/api.yaml+++ b/openapi/api.yaml@@ -1355,6 +1355,26 @@ components:required:- presettype: object+ language_servers:+ properties:+ pylsp:+ properties:+ enable_flake8:+ type: boolean+ enable_mypy:+ type: boolean+ enable_pydocstyle:+ type: boolean+ enable_pyflakes:+ type: boolean+ enable_pylint:+ type: boolean+ enable_ruff:+ type: boolean+ enabled:+ type: boolean+ type: object+ type: objectpackage_management:properties:manager:@@ -2281,7 +2301,7 @@ components:type: objectinfo:title: marimo API- version: 0.11.18+ version: 0.11.19openapi: 3.1.0paths:/@file/{filename_and_length}:diff --git a/openapi/src/api.ts b/openapi/src/api.tsindex a4e5012cc4..cd89a392b4 100644--- a/openapi/src/api.ts+++ b/openapi/src/api.ts@@ -2720,6 +2720,17 @@ export interface components {/** @enum {string} */preset: "default" | "vim";};+ language_servers?: {+ pylsp?: {+ enable_flake8?: boolean;+ enable_mypy?: boolean;+ enable_pydocstyle?: boolean;+ enable_pyflakes?: boolean;+ enable_pylint?: boolean;+ enable_ruff?: boolean;+ enabled?: boolean;+ };+ };package_management: {/** @enum {string} */manager: "pip" | "rye" | "uv" | "poetry" | "pixi";diff --git a/pyproject.toml b/pyproject.tomlindex 7a9f077d35..62a91f4668 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -77,6 +77,9 @@ marimo = "marimo._cli.cli:main"[project.urls]homepage = "https://github.com/marimo-team/marimo"+[project.entry-points."pylsp"]+marimo_plugin = "marimo._server.lsp"+[project.optional-dependencies]sql = ["duckdb>=1.0.0",@@ -95,8 +98,6 @@ recommended = ["openai>=1.55.3", # AI features"ruff", # Formatting"nbformat>=5.7.0", # Export as IPYNB- "vegafusion>=2.0.0", # Performant charting- "vl-convert-python>=1.0.0", # Required by vegafusion]dev = [@@ -186,7 +187,7 @@ dependencies = ["matplotlib>=3.8.0","pyarrow-stubs>=17.0","sqlglot>=23.4",- "sqlalchemy>=2.0.38",+ "sqlalchemy>=2.0.0","pandas-stubs>=1.5.3.230321","types-Pillow~=10.2.0.20240520","types-Pygments~=2.18.0.20240506",@@ -236,6 +237,7 @@ extra-dependencies = ["pytest-timeout~=2.3.1","pytest-codecov~=0.6.1","pytest-asyncio~=0.25.2",+ "python-lsp-server>=1.10.0",# For testing mo.ui.chart, table, ..."vl-convert-python","vegafusion",@@ -501,6 +503,8 @@ format_on_save = true[tool.marimo.experimental]multi_column = truechat_sidebar = true+# Very experimental!+lsp = true[tool.marimo.display]dataframes = "rich"diff --git a/tests/_server/mocks.py b/tests/_server/mocks.pyindex 820888fdd5..4258f6c02f 100644--- a/tests/_server/mocks.py+++ b/tests/_server/mocks.py@@ -7,8 +7,9 @@ from typing import TYPE_CHECKING, Any, Callable, Optional, castfrom marimo._config.manager import get_default_config_managerfrom marimo._server.file_router import AppFileRouter+from marimo._server.lsp import NoopLspServerfrom marimo._server.model import SessionMode-from marimo._server.sessions import NoopLspServer, SessionManager+from marimo._server.sessions import SessionManagerfrom marimo._server.tokens import AuthToken, SkewProtectionTokenfrom marimo._utils.marimo_path import MarimoPathdiff --git a/tests/_server/templates/snapshots/export1.txt b/tests/_server/templates/snapshots/export1.txtindex a12df1d317..9aac1f2d18 100644--- a/tests/_server/templates/snapshots/export1.txt+++ b/tests/_server/templates/snapshots/export1.txt@@ -55,7 +55,7 @@<marimo-filename hidden>notebook.py</marimo-filename><marimo-mode data-mode='read' hidden></marimo-mode><marimo-version data-version='0.0.0' hidden></marimo-version>- <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun", "output_max_bytes": 8000000, "pythonpath": [], "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}' data-overrides='{"formatting": {"line_length": 100}}' hidden></marimo-user-config>+ <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": true}}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun", "output_max_bytes": 8000000, "pythonpath": [], "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}' data-overrides='{"formatting": {"line_length": 100}}' hidden></marimo-user-config><marimo-app-config data-config='{"width": "compact"}' hidden></marimo-app-config><marimo-server-token data-token='token' hidden></marimo-server-token><title>notebook</title>diff --git a/tests/_server/templates/snapshots/export2.txt b/tests/_server/templates/snapshots/export2.txtindex 375bf44a7a..423f520a56 100644--- a/tests/_server/templates/snapshots/export2.txt+++ b/tests/_server/templates/snapshots/export2.txt@@ -55,7 +55,7 @@<marimo-filename hidden></marimo-filename><marimo-mode data-mode='read' hidden></marimo-mode><marimo-version data-version='0.0.0' hidden></marimo-version>- <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun", "output_max_bytes": 8000000, "pythonpath": [], "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}' data-overrides='{"formatting": {"line_length": 100}}' hidden></marimo-user-config>+ <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": true}}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun", "output_max_bytes": 8000000, "pythonpath": [], "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}' data-overrides='{"formatting": {"line_length": 100}}' hidden></marimo-user-config><marimo-app-config data-config='{"width": "compact"}' hidden></marimo-app-config><marimo-server-token data-token='token' hidden></marimo-server-token><title>marimo</title>diff --git a/tests/_server/templates/snapshots/export3.txt b/tests/_server/templates/snapshots/export3.txtindex f85f9b4e73..2dbb46bf2a 100644--- a/tests/_server/templates/snapshots/export3.txt+++ b/tests/_server/templates/snapshots/export3.txt@@ -55,7 +55,7 @@<marimo-filename hidden>notebook.py</marimo-filename><marimo-mode data-mode='read' hidden></marimo-mode><marimo-version data-version='0.0.0' hidden></marimo-version>- <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun", "output_max_bytes": 8000000, "pythonpath": [], "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}' data-overrides='{"formatting": {"line_length": 100}}' hidden></marimo-user-config>+ <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": true}}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun", "output_max_bytes": 8000000, "pythonpath": [], "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}' data-overrides='{"formatting": {"line_length": 100}}' hidden></marimo-user-config><marimo-app-config data-config='{"width": "compact"}' hidden></marimo-app-config><marimo-server-token data-token='token' hidden></marimo-server-token><title>notebook</title>diff --git a/tests/_server/templates/snapshots/export4.txt b/tests/_server/templates/snapshots/export4.txtindex d1e533a52b..75e2fb6421 100644--- a/tests/_server/templates/snapshots/export4.txt+++ b/tests/_server/templates/snapshots/export4.txt@@ -55,7 +55,7 @@<marimo-filename hidden>notebook.py</marimo-filename><marimo-mode data-mode='read' hidden></marimo-mode><marimo-version data-version='0.0.0' hidden></marimo-version>- <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun", "output_max_bytes": 8000000, "pythonpath": [], "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}' data-overrides='{"formatting": {"line_length": 100}}' hidden></marimo-user-config>+ <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": true}}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun", "output_max_bytes": 8000000, "pythonpath": [], "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}' data-overrides='{"formatting": {"line_length": 100}}' hidden></marimo-user-config><marimo-app-config data-config='{"css_file": "custom.css", "width": "compact"}' hidden></marimo-app-config><marimo-server-token data-token='token' hidden></marimo-server-token><title>notebook</title>diff --git a/tests/_server/templates/snapshots/export5.txt b/tests/_server/templates/snapshots/export5.txtindex b6d9964bbf..c5d2231427 100644--- a/tests/_server/templates/snapshots/export5.txt+++ b/tests/_server/templates/snapshots/export5.txt@@ -55,7 +55,7 @@<marimo-filename hidden>notebook.py</marimo-filename><marimo-mode data-mode='read' hidden></marimo-mode><marimo-version data-version='0.0.0' hidden></marimo-version>- <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun", "output_max_bytes": 8000000, "pythonpath": [], "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}' data-overrides='{"formatting": {"line_length": 100}}' hidden></marimo-user-config>+ <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": true}}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun", "output_max_bytes": 8000000, "pythonpath": [], "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}' data-overrides='{"formatting": {"line_length": 100}}' hidden></marimo-user-config><marimo-app-config data-config='{"app_title": "My App", "html_head_file": "head.html", "width": "compact"}' hidden></marimo-app-config><marimo-server-token data-token='token' hidden></marimo-server-token><title>My App</title>diff --git a/tests/_server/test_lsp.py b/tests/_server/test_lsp.pynew file mode 100644index 0000000000..c4c8ac8cb5--- /dev/null+++ b/tests/_server/test_lsp.py@@ -0,0 +1,164 @@+from __future__ import annotations++from pathlib import Path+from typing import TYPE_CHECKING+from unittest import mock++import pytest++from marimo._config.config import CompletionConfig, LanguageServersConfig+from marimo._dependencies.dependencies import DependencyManager+from marimo._messaging.ops import Alert+from marimo._server.lsp import (+ BaseLspServer,+ CompositeLspServer,+ CopilotLspServer,+ PyLspServer,+)++if TYPE_CHECKING:+ from collections.abc import Iterator+++def mock_process():+ process = mock.MagicMock()+ process.returncode = None+ return process+++def mock_popen(mock_process: mock.MagicMock) -> Iterator[mock.MagicMock]:+ with mock.patch("subprocess.Popen", return_value=mock_process) as popen:+ yield popen+++def mock_which():+ with mock.patch("shutil.which", return_value="/mock/path") as which:+ yield which+++class MockLspServer(BaseLspServer):+ id = "mock"++ def binary_name(self) -> str:+ return "mock_binary"++ def get_command(self) -> str:+ return f"mock_binary --port {self.port}"++ def missing_binary_alert(self) -> Alert:+ return Alert(title="Mock Alert", description="Mock missing binary")+++def test_base_lsp_server_start_stop(+ mock_which: mock.MagicMock,+ mock_popen: mock.MagicMock,+ mock_process: mock.MagicMock,+):+ server = MockLspServer(port=8000)++ mock_which.return_value = None++ # Without binary install+ alert = server.start()+ assert alert is not None+ assert alert.title == "Mock Alert"+ assert alert.description == "Mock missing binary"++ # Add binary+ mock_which.return_value = "/mock/path"++ # Test start+ alert = server.start()+ assert alert is None+ mock_popen.assert_called_once()+ assert server.is_running() is False # Process exists but not running++ # Test stop+ server.stop()+ mock_process.terminate.assert_called_once()+ assert server.process is None+++def test_base_lsp_server_missing_binary(mock_which: mock.MagicMock):+ server = MockLspServer(port=8000)+ mock_which.return_value = None+ alert = server.start()+ assert alert is not None+ assert alert.title == "Mock Alert"+++def test_pylsp_server():+ server = PyLspServer(port=8000)+ assert server.binary_name() == "pylsp"+ assert (+ server.get_command()+ == "pylsp --ws -v --port 8000 --check-parent-process"+ )+ alert = server.missing_binary_alert()+ assert "Python LSP" in alert.title+++def test_copilot_server():+ server = CopilotLspServer(port=8000)+ assert server.binary_name() == "node"+ if Path(server._lsp_bin()).exists():+ assert "node" in server.get_command()+ assert str(8000) in server.get_command()+ else:+ assert server.get_command() == ""+ alert = server.missing_binary_alert()+ assert "GitHub Copilot" in alert.title+++def test_composite_server():+ config = LanguageServersConfig({"pylsp": {"enabled": True}})+ completion_config = CompletionConfig(+ {"copilot": True, "activate_on_typing": True}+ )++ with mock.patch("marimo._server.lsp.DependencyManager") as mock_dm:+ mock_dm.pylsp = mock.MagicMock()+ mock_dm.pylsp.has.return_value = True+ server = CompositeLspServer(config, completion_config, min_port=8000)+ assert len(server.servers) == 2 # Both pylsp and copilot enabled++ # Test with only pylsp+ config = LanguageServersConfig({"pylsp": {"enabled": True}})+ completion_config = CompletionConfig(+ {"copilot": False, "activate_on_typing": True}+ )+ server = CompositeLspServer(config, completion_config, min_port=8000)+ assert len(server.servers) == 1++ # Test with nothing enabled+ config = LanguageServersConfig({"pylsp": {"enabled": False}})+ completion_config = CompletionConfig(+ {"copilot": False, "activate_on_typing": True}+ )+ server = CompositeLspServer(config, completion_config, min_port=8000)+ assert len(server.servers) == 0+++ not DependencyManager.pylsp.has(),+ reason="pylsp is not installed",+)+def test_pylsp_hooks():+ from marimo._server.lsp import pylsp_completions, pylsp_hover++ # Mock document and position+ mock_doc = mock.MagicMock()+ mock_doc.source = "def test(): pass"+ mock_doc.path = "test.py"+ position = {"line": 0, "character": 4}++ # Test hover+ hover_result = pylsp_hover({}, mock_doc, position)+ assert hover_result is None or isinstance(hover_result, dict)++ # Test completions+ completion_result = pylsp_completions(mock_doc, position)+ assert completion_result is None