Skip to content

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

experimental: add LSP docs and pyproject.toml requirements (#4191)

Myles Scolnickb6843c3f3e9d
diff --git a/docs/guides/editor_features/index.md b/docs/guides/editor_features/index.md
index a2e94a3c78..0a99a33717 100644
--- a/docs/guides/editor_features/index.md
+++ b/docs/guides/editor_features/index.md
@@ -1,4 +1,3 @@
-
# Editor features
The **marimo editor** is the browser-based IDE in which you write marimo
@@ -11,6 +10,7 @@ with code and data.
| [Overview](overview.md) | An overview of editor features and configuration |
| [Package Management](package_management.md) | Using package managers in marimo |
| [AI Completion](ai_completion.md) | Code with the help of a language model |
+| [Language Server](language_server.md) | Code intelligence via LSP |
| [Hotkeys](hotkeys.md) | Our hotkeys |
Highlights include:
@@ -21,6 +21,7 @@ Highlights include:
- code completion
- GitHub Copilot
- language-model assisted coding
+- language server protocol (LSP) for diagnostics and code intelligence
- vim keybindings
- live documentation preiews as you type
diff --git a/docs/guides/editor_features/language_server.md b/docs/guides/editor_features/language_server.md
new file mode 100644
index 0000000000..fc865ff7e7
--- /dev/null
+++ b/docs/guides/editor_features/language_server.md
@@ -0,0 +1,79 @@
+# Language Server Protocol (LSP)
+
+!!! warning "Experimental Feature"
+
+ LSP support in marimo is currently an experimental feature. It may have bugs or performance issues. To enable it add the following to your `pyproject.toml` file:
+
+ ```toml title="pyproject.toml"
+ [tool.marimo.experimental]
+ lsp = true
+ ```
+
+The marimo editor supports the Language Server Protocol (LSP) to provide enhanced code intelligence features like:
+
+- Code completion
+- Hover information
+- Go to definition
+- Error checking and diagnostics
+
+## Installation
+
+LSP support requires additional dependencies. You can install them with:
+
+```bash
+pip install "marimo[lsp]"
+# or
+uv add marimo[lsp]
+# or
+conda install -c conda-forge python-lsp-server python-lsp-ruff
+```
+
+This will install the necessary packages including:
+
+- [`python-lsp-server`](https://github.com/python-lsp/python-lsp-server): The core Python language server
+- `python-lsp-ruff`: Ruff integration for fast linting
+
+You may optionally install other `pylsp` plugins.
+
+!!! note "Other Python Language Servers"
+
+ Support for other Python language servers is planned for future releases.
+
+## Configuration
+
+LSP support can be configured in your `pyproject.toml` file.
+
+```toml title="pyproject.toml"
+[tool.marimo.experimental]
+lsp = true
+```
+
+```toml title="pyproject.toml"
+
+# Language server configuration
+[tool.marimo.language_servers.pylsp]
+enabled = true # Enable/disable the Python language server
+enable_mypy = true # Type checking with mypy (enabled by default, if installed)
+enable_ruff = true # Linting with ruff (enabled by default, if installed)
+enable_flake8 = false # Linting with flake8
+enable_pydocstyle = false # Check docstring style
+enable_pylint = false # Linting with pylint
+enable_pyflakes = false # Syntax checking with pyflakes
+
+# Diagnostics configuration
+[tool.marimo.diagnostics]
+enabled = true # Show diagnostics in the editor
+```
+
+## WebAssembly
+
+Language Servers are not available when running marimo in WebAssembly.
+
+## Troubleshooting
+
+If you encounter issues with the language server:
+
+1. Make sure you've installed the required dependencies with `pip install "marimo[lsp]"`
+2. Check if the language server is enabled in your configuration
+3. Try restarting the marimo server
+4. Check the terminal for any error messages
diff --git a/frontend/package.json b/frontend/package.json
index 114fff3db0..4ba088f572 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -42,7 +42,7 @@
"@lezer/python": "^1.1.16",
"@marimo-team/codemirror-ai": "^0.1.9",
"@marimo-team/marimo-api": "file:../openapi",
- "@marimo-team/codemirror-languageserver": "^1.14.1",
+ "@marimo-team/codemirror-languageserver": "^1.15.0",
"@marimo-team/react-slotz": "^0.1.8",
"@open-rpc/client-js": "^1.8.1",
"@paralleldrive/cuid2": "^2.2.2",
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index 091426d4ca..6ebd5e0bb1 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -103,8 +103,8 @@ importers:
specifier: ^0.1.9
version: 0.1.9(@codemirror/[email protected])(@codemirror/[email protected])
'@marimo-team/codemirror-languageserver':
- specifier: ^1.14.1
- version: 1.14.1(@codemirror/[email protected])(@codemirror/[email protected])
+ specifier: ^1.15.0
+ version: 1.15.0(@codemirror/[email protected])(@codemirror/[email protected])
'@marimo-team/marimo-api':
specifier: file:../openapi
version: file:../openapi
@@ -1546,8 +1546,8 @@ packages:
'@codemirror/state': ^6
'@codemirror/view': ^6
- '@marimo-team/[email protected]':
- resolution: {integrity: sha512-Dvt06J0FdPmulsy7HPg3AORc6edBtfxqST5L3Y5TOPrgXrIpE+3kOrs9+mWKTRG5jGJ7wgxGh9+TRFgsOoTxlQ==}
+ '@marimo-team/[email protected]':
+ resolution: {integrity: sha512-wxGmoE07fev5fmaaXbBzzhy0Jh8+G//BzUwKcvO2/c5IljWpupH5sR3eICObVugG7s2UBNSSbEjaH1l+pBHL+A==}
peerDependencies:
'@codemirror/state': ^6
'@codemirror/view': ^6
@@ -10225,7 +10225,7 @@ snapshots:
'@codemirror/state': 6.5.2
'@codemirror/view': 6.36.4
- '@marimo-team/[email protected](@codemirror/[email protected])(@codemirror/[email protected])':
+ '@marimo-team/[email protected](@codemirror/[email protected])(@codemirror/[email protected])':
dependencies:
'@codemirror/autocomplete': 6.18.6
'@codemirror/lint': 6.8.4
diff --git a/frontend/src/components/editor/Cell.tsx b/frontend/src/components/editor/Cell.tsx
index 250c790187..43afcbb36c 100644
--- a/frontend/src/components/editor/Cell.tsx
+++ b/frontend/src/components/editor/Cell.tsx
@@ -1,5 +1,5 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { closeCompletion, completionStatus } from "@codemirror/autocomplete";
+import { completionStatus } from "@codemirror/autocomplete";
import type { EditorView } from "@codemirror/view";
import {
memo,
@@ -75,7 +75,7 @@ function useCellCompletion(
!cellRef.current.contains(e.relatedTarget) &&
editorView.current !== null
) {
- closeCompletion(editorView.current);
+ // closeCompletion(editorView.current);
}
});
diff --git a/frontend/src/components/editor/cell/code/cell-editor.tsx b/frontend/src/components/editor/cell/code/cell-editor.tsx
index d827103eac..cd8d2cb5ad 100644
--- a/frontend/src/components/editor/cell/code/cell-editor.tsx
+++ b/frontend/src/components/editor/cell/code/cell-editor.tsx
@@ -255,7 +255,10 @@ const CellEditorInternal = ({
editorViewRef.current,
userConfig.completion,
new OverridingHotkeyProvider(userConfig.keymap.overrides ?? {}),
- userConfig.language_servers,
+ {
+ ...userConfig.language_servers,
+ diagnostics: userConfig.diagnostics,
+ },
),
],
});
diff --git a/frontend/src/core/codemirror/__tests__/setup.test.ts b/frontend/src/core/codemirror/__tests__/setup.test.ts
index 4cc1501db5..5976f6f544 100644
--- a/frontend/src/core/codemirror/__tests__/setup.test.ts
+++ b/frontend/src/core/codemirror/__tests__/setup.test.ts
@@ -58,6 +58,9 @@ function getOpts() {
pylsp: {
enabled: false,
},
+ diagnostics: {
+ enabled: false,
+ },
},
diagnosticsConfig: {},
hotkeys: new OverridingHotkeyProvider({}),
diff --git a/frontend/src/core/codemirror/cm.ts b/frontend/src/core/codemirror/cm.ts
index d05334ed05..840e2daf05 100644
--- a/frontend/src/core/codemirror/cm.ts
+++ b/frontend/src/core/codemirror/cm.ts
@@ -156,7 +156,14 @@ const startCompletionAtEndOfLine = (cm: EditorView): boolean => {
// Based on codemirror's basicSetup extension
export const basicBundle = (opts: CodeMirrorSetupOpts): Extension[] => {
- const { theme, hotkeys, completionConfig, cellId, lspConfig } = opts;
+ const {
+ theme,
+ hotkeys,
+ completionConfig,
+ cellId,
+ lspConfig,
+ diagnosticsConfig,
+ } = opts;
const placeholderType = getPlaceholderType(opts);
return [
@@ -198,7 +205,7 @@ export const basicBundle = (opts: CodeMirrorSetupOpts): Extension[] => {
completionConfig,
hotkeys,
cellId,
- lspConfig,
+ lspConfig: { ...lspConfig, diagnostics: diagnosticsConfig },
}),
///// Editing
diff --git a/frontend/src/core/codemirror/config/extension.ts b/frontend/src/core/codemirror/config/extension.ts
index c485c702cc..537a513dc0 100644
--- a/frontend/src/core/codemirror/config/extension.ts
+++ b/frontend/src/core/codemirror/config/extension.ts
@@ -7,7 +7,6 @@ import type {
import type { HotkeyProvider } from "@/core/hotkeys/hotkeys";
import type { CellId } from "@/core/cells/ids";
import { singleFacet } from "../facet";
-import { diagnosticsEnabled } from "@marimo-team/codemirror-languageserver";
/**
* State for completion config
@@ -33,12 +32,9 @@ export const cellIdState = singleFacet<CellId>();
/**
* State for LSP config
*/
-export const lspConfigState = singleFacet<LSPConfig>();
-
-/**
- * State for diagnostics config
- */
-export const diagnosticsConfigState = singleFacet<DiagnosticsConfig>();
+export const lspConfigState = singleFacet<
+ LSPConfig & { diagnostics: DiagnosticsConfig }
+>();
/**
* Extension for cell config
@@ -55,9 +51,6 @@ export function cellConfigExtension(
completionConfigState.of(completionConfig),
hotkeysProviderState.of(hotkeys),
placeholderState.of(placeholderType),
- lspConfigState.of(lspConfig),
- diagnosticsConfigState.of(diagnosticsConfig),
- // Enable diagnostics (default to false)
- diagnosticsEnabled.of(diagnosticsConfig?.enabled ?? false),
+ lspConfigState.of({ ...lspConfig, diagnostics: diagnosticsConfig }),
];
}
diff --git a/frontend/src/core/codemirror/language/extension.ts b/frontend/src/core/codemirror/language/extension.ts
index 1c7091a4dd..5bfc9b5350 100644
--- a/frontend/src/core/codemirror/language/extension.ts
+++ b/frontend/src/core/codemirror/language/extension.ts
@@ -13,7 +13,11 @@ import {
showPanel,
} from "@codemirror/view";
import { clamp } from "@/utils/math";
-import type { CompletionConfig, LSPConfig } from "@/core/config/config-schema";
+import type {
+ CompletionConfig,
+ DiagnosticsConfig,
+ LSPConfig,
+} from "@/core/config/config-schema";
import {
cellIdState,
completionConfigState,
@@ -184,7 +188,7 @@ export function adaptiveLanguageConfiguration(opts: {
placeholderType: PlaceholderType;
completionConfig: CompletionConfig;
hotkeys: HotkeyProvider;
- lspConfig: LSPConfig;
+ lspConfig: LSPConfig & { diagnostics?: DiagnosticsConfig };
cellId: CellId;
}) {
const { placeholderType, completionConfig, hotkeys, cellId, lspConfig } =
@@ -264,7 +268,7 @@ export function reconfigureLanguageEffect(
view: EditorView,
completionConfig: CompletionConfig,
hotkeysProvider: HotkeyProvider,
- lspConfig: LSPConfig,
+ lspConfig: LSPConfig & { diagnostics?: DiagnosticsConfig },
) {
const language = view.state.field(languageAdapterState);
const placeholderType = view.state.facet(placeholderState);
diff --git a/frontend/src/core/codemirror/language/python.ts b/frontend/src/core/codemirror/language/python.ts
index 6eb9ae482f..bf4c813979 100644
--- a/frontend/src/core/codemirror/language/python.ts
+++ b/frontend/src/core/codemirror/language/python.ts
@@ -11,7 +11,11 @@ import {
foldInside,
LanguageSupport,
} from "@codemirror/language";
-import type { CompletionConfig, LSPConfig } from "@/core/config/config-schema";
+import type {
+ CompletionConfig,
+ DiagnosticsConfig,
+ LSPConfig,
+} from "@/core/config/config-schema";
import type { HotkeyProvider } from "@/core/hotkeys/hotkeys";
import type { PlaceholderType } from "../config/extension";
import {
@@ -142,7 +146,7 @@ export class PythonLanguageAdapter implements LanguageAdapter {
completionConfig: CompletionConfig,
_hotkeys: HotkeyProvider,
placeholderType: PlaceholderType,
- lspConfig: LSPConfig,
+ lspConfig: LSPConfig & { diagnostics: DiagnosticsConfig },
): Extension[] {
const getCompletionsExtension = () => {
const autocompleteOptions = {
@@ -170,6 +174,8 @@ export class PythonLanguageAdapter implements LanguageAdapter {
allowHTMLContent: true,
hoverConfig: hoverOptions,
completionConfig: autocompleteOptions,
+ // Default to false
+ diagnosticsEnabled: lspConfig.diagnostics?.enabled ?? false,
// Match completions before the cursor is at the end of a word,
// after a dot, after a slash, after a comma.
completionMatchBefore: /(\w+|\w+\.|\/|,)$/,
diff --git a/frontend/src/core/codemirror/language/types.ts b/frontend/src/core/codemirror/language/types.ts
index 5c94e90d62..0364678421 100644
--- a/frontend/src/core/codemirror/language/types.ts
+++ b/frontend/src/core/codemirror/language/types.ts
@@ -1,5 +1,9 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import type { CompletionConfig, LSPConfig } from "@/core/config/config-schema";
+import type {
+ CompletionConfig,
+ DiagnosticsConfig,
+ 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,7 +25,7 @@ export interface LanguageAdapter {
completionConfig: CompletionConfig,
hotkeys: HotkeyProvider,
placeholderType: PlaceholderType,
- lspConfig: LSPConfig,
+ lspConfig: LSPConfig & { diagnostics?: DiagnosticsConfig },
): Extension[];
}
diff --git a/marimo/_config/manager.py b/marimo/_config/manager.py
index 7b384f2034..9c62e875e2 100644
--- a/marimo/_config/manager.py
+++ b/marimo/_config/manager.py
@@ -3,12 +3,15 @@ from __future__ import annotations
import os
from abc import abstractmethod
+from functools import cached_property
from pathlib import Path
-from typing import Optional, Union, cast
+from typing import Any, Optional, Union, cast
from marimo import _loggers
from marimo._config.config import (
DEFAULT_CONFIG,
+ CompletionConfig,
+ LanguageServersConfig,
MarimoConfig,
PartialMarimoConfig,
Theme,
@@ -65,17 +68,43 @@ class MarimoConfigReader:
# Convenience methods for common access patterns
+ @cached_property
+ def _config(self) -> MarimoConfig:
+ return self.get_config()
+
@property
def default_width(self) -> WidthType:
- return self.get_config()["display"]["default_width"]
+ return self._config["display"]["default_width"]
@property
def theme(self) -> Theme:
- return self.get_config()["display"]["theme"]
+ return self._config["display"]["theme"]
@property
def package_manager(self) -> PackageManagerKind:
- return self.get_config()["package_management"]["manager"]
+ return self._config["package_management"]["manager"]
+
+ @property
+ def completion(self) -> CompletionConfig:
+ return self._config["completion"]
+
+ @property
+ def language_servers(self) -> LanguageServersConfig:
+ # LSP is behind an experimental flag,
+ # if it's not enabled, return an empty config
+ lsp_enabled = self.experimental.get("lsp", False)
+ if not lsp_enabled:
+ return {}
+
+ if "language_servers" in self._config:
+ return self._config["language_servers"]
+ return {}
+
+ @property
+ def experimental(self) -> dict[str, Any]:
+ if "experimental" in self._config:
+ return self._config["experimental"]
+ return {}
class MarimoConfigManager(MarimoConfigReader):
diff --git a/marimo/_server/api/middleware.py b/marimo/_server/api/middleware.py
index 332102b8cc..a1ea462e60 100644
--- a/marimo/_server/api/middleware.py
+++ b/marimo/_server/api/middleware.py
@@ -347,7 +347,10 @@ class ProxyMiddleware:
ws_url = ws_url.replace("https", "wss", 1)
LOGGER.debug(f"Creating websocket proxy for {ws_url}")
- await self._proxy_websocket(scope, receive, send, ws_url)
+ try:
+ await self._proxy_websocket(scope, receive, send, ws_url)
+ except Exception as e:
+ LOGGER.error(f"Error proxying websocket: {e}")
LOGGER.debug(f"Done with websocket proxy for {ws_url}")
return
diff --git a/marimo/_server/lsp.py b/marimo/_server/lsp.py
index 43b279cdea..a815bdf146 100644
--- a/marimo/_server/lsp.py
+++ b/marimo/_server/lsp.py
@@ -2,18 +2,15 @@
from __future__ import annotations
import os
-import shutil
import subprocess
from abc import ABC, abstractmethod
-from typing import Any, Optional, cast
+from typing import Any, Literal, Optional, Union, 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._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
@@ -50,11 +47,10 @@ class BaseLspServer(LspServer):
LOGGER.debug("LSP server already started")
return None
- binpath = shutil.which(self.binary_name())
- LOGGER.debug("binpath %s", binpath)
- if binpath is None:
+ validation_msg = self.validate_requirements()
+ if validation_msg is not True:
LOGGER.error(
- f"{self.binary_name()} not found; cannot start LSP server."
+ f"Cannot start {self.id} LSP server: {validation_msg}"
)
return self.missing_binary_alert()
@@ -109,7 +105,7 @@ class BaseLspServer(LspServer):
else:
LOGGER.debug("LSP server not running")
- def binary_name(self) -> str:
+ def validate_requirements(self) -> Union[str, Literal[True]]:
raise NotImplementedError()
def get_command(self) -> list[str]:
@@ -122,8 +118,12 @@ class BaseLspServer(LspServer):
class CopilotLspServer(BaseLspServer):
id = "copilot"
- def binary_name(self) -> str:
- return "node"
+ def validate_requirements(self) -> Union[str, Literal[True]]:
+ if DependencyManager.which("node"):
+ return True
+ return (
+ "node.js binary is missing. Install node at https://nodejs.org/."
+ )
def _lsp_bin(self) -> str:
lsp_bin = os.path.join(
@@ -157,8 +157,10 @@ class CopilotLspServer(BaseLspServer):
class PyLspServer(BaseLspServer):
id = "pylsp"
- def binary_name(self) -> str:
- return "pylsp"
+ def validate_requirements(self) -> Union[str, Literal[True]]:
+ if DependencyManager.pylsp.has():
+ return True
+ return "pylsp is missing. Install it with `pip install python-lsp-server`."
def get_command(self) -> list[str]:
import sys
@@ -214,9 +216,6 @@ class CompositeLspServer(LspServer):
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))
diff --git a/marimo/_server/start.py b/marimo/_server/start.py
index 819cdf9606..acde5af34e 100644
--- a/marimo/_server/start.py
+++ b/marimo/_server/start.py
@@ -105,15 +105,9 @@ 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"],
+ lsp_config=config_reader.language_servers,
+ completion_config=config_reader.completion,
min_port=DEFAULT_PORT + 400,
)
diff --git a/pyproject.toml b/pyproject.toml
index a031603dd6..a760822574 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -115,6 +115,11 @@ dev = [
"openai>=1.55.3",
]
+lsp = [
+ "python-lsp-server>=1.10.0",
+ "python-lsp-ruff>=2.0.0",
+]
+
docs = [
"mkdocs>=1.6.1",
"mkdocs-material>=9.5.49",
diff --git a/tests/_server/test_lsp.py b/tests/_server/test_lsp.py
index 5f7817b0c3..bed9c4788d 100644
--- a/tests/_server/test_lsp.py
+++ b/tests/_server/test_lsp.py
@@ -1,7 +1,7 @@
from __future__ import annotations
from pathlib import Path
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Literal, Union
from unittest import mock
import pytest
@@ -42,24 +42,22 @@ def mock_which():
class MockLspServer(BaseLspServer):
id = "mock"
- def binary_name(self) -> str:
- return "mock_binary"
+ def validate_requirements(self) -> Union[str, Literal[True]]:
+ return True
- def get_command(self) -> str:
- return f"mock_binary --port {self.port}"
+ def get_command(self) -> list[str]:
+ return ["mock_binary", "--port", str(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
+ server.validate_requirements = mock.MagicMock(return_value=False)
# Without binary install
alert = server.start()
@@ -67,8 +65,7 @@ def test_base_lsp_server_start_stop(
assert alert.title == "Mock Alert"
assert alert.description == "Mock missing binary"
- # Add binary
- mock_which.return_value = "/mock/path"
+ server.validate_requirements = mock.MagicMock(return_value=True)
# Test start
alert = server.start()
@@ -85,6 +82,7 @@ def test_base_lsp_server_start_stop(
def test_base_lsp_server_missing_binary(mock_which: mock.MagicMock):
server = MockLspServer(port=8000)
mock_which.return_value = None
+ server.validate_requirements = mock.MagicMock(return_value=False)
alert = server.start()
assert alert is not None
assert alert.title == "Mock Alert"
@@ -95,7 +93,7 @@ def test_pylsp_server():
server = PyLspServer(port=8000)
- assert server.binary_name() == "pylsp"
+ assert isinstance(server.validate_requirements(), (str, bool))
assert server.get_command() == [
sys.executable,
"-m",
@@ -112,7 +110,7 @@ def test_pylsp_server():
def test_copilot_server():
server = CopilotLspServer(port=8000)
- assert server.binary_name() == "node"
+ assert isinstance(server.validate_requirements(), (str, bool))
if Path(server._lsp_bin()).exists():
assert "node" in server.get_command()
assert str(8000) in server.get_command()