Skip to content

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

improvement: Add custom docstring-to-markdown convert for Google Docs (#4252)

Myles Scolnickd8d397c820f0
diff --git a/frontend/src/components/app-config/user-config-form.tsx b/frontend/src/components/app-config/user-config-form.tsx
index b6b3a476f1..0534aecae1 100644
--- a/frontend/src/components/app-config/user-config-form.tsx
+++ b/frontend/src/components/app-config/user-config-form.tsx
@@ -467,6 +467,18 @@ export const UserConfigForm: React.FC = () => {
</FormItem>
)}
/>
+ <FormDescription>
+ See the{" "}
+ <a
+ className="text-link hover:underline"
+ href="https://docs.marimo.io/guides/editor_features/language_server/"
+ target="_blank"
+ rel="noreferrer"
+ >
+ docs
+ </a>{" "}
+ for more information about language server support.
+ </FormDescription>
<FormField
control={form.control}
@@ -1227,6 +1239,40 @@ export const UserConfigForm: React.FC = () => {
⚠️ These features are experimental and may require restarting your
notebook to take effect.
</p>
+ <FormField
+ control={form.control}
+ name="experimental.lsp"
+ render={({ field }) => (
+ <div className="flex flex-col gap-y-1">
+ <FormItem className={formItemClasses}>
+ <FormLabel className="font-normal">
+ LSP (Language Server Protocol)
+ </FormLabel>
+ <FormControl>
+ <Checkbox
+ data-testid="inline-ai-checkbox"
+ checked={field.value === true}
+ onCheckedChange={field.onChange}
+ />
+ </FormControl>
+ </FormItem>
+ <FormDescription>
+ Enable experimental LSP support. You will need to have
+ <Kbd className="inline">marimo[lsp]</Kbd> installed in your
+ environment to use this. See{" "}
+ <a
+ className="text-link hover:underline"
+ href="https://docs.marimo.io/guides/editor_features/language_server/"
+ target="_blank"
+ rel="noreferrer"
+ >
+ docs
+ </a>{" "}
+ for more info.
+ </FormDescription>
+ </div>
+ )}
+ />
<FormField
control={form.control}
name="experimental.inline_ai_tooltip"
diff --git a/frontend/src/components/editor/documentation.css b/frontend/src/components/editor/documentation.css
index 39bc24e460..04d807fbf6 100644
--- a/frontend/src/components/editor/documentation.css
+++ b/frontend/src/components/editor/documentation.css
@@ -1,3 +1,4 @@
+.cm-tooltip .documentation,
.docs-documentation {
line-height: normal;
@@ -56,7 +57,8 @@
@apply border px-1 rounded font-mono bg-[var(--slate-1)] text-sm mb-4 mt-2;
}
- h1 {
+ h1,
+ h2 {
font-weight: 600;
@apply text-xl border-b pb-1 mb-1 text-primary;
}
@@ -108,7 +110,8 @@
}
/* Custom overrides when in a tooltip */
-.mo-cm-tooltip.docs-documentation {
+.cm-tooltip .documentation,
+.cm-tooltip .docs-documentation {
@apply text-sm;
h1 {
diff --git a/marimo/_output/mime.py b/marimo/_output/mime.py
index b943da9f15..f93ecd4c6d 100644
--- a/marimo/_output/mime.py
+++ b/marimo/_output/mime.py
@@ -2,13 +2,12 @@
from __future__ import annotations
from dataclasses import dataclass
-from typing import Protocol
from marimo._messaging.mimetypes import KnownMimeType
@dataclass
-class MIME(Protocol):
+class MIME:
"""Protocol for instantiating objects using marimo's media viewer.
To implement this protocol, a class needs to define
diff --git a/marimo/_output/rich_help.py b/marimo/_output/rich_help.py
index b161f248d4..943a80c9b3 100644
--- a/marimo/_output/rich_help.py
+++ b/marimo/_output/rich_help.py
@@ -19,20 +19,22 @@ _WRAP_WIDTH = 72
def _format_parameter(parameter: inspect.Parameter) -> str:
- annotation = (
- ""
- if parameter.annotation == inspect.Parameter.empty
- else ": " + cast(str, parameter.annotation)
- )
- default = (
- ""
- if parameter.default == inspect.Parameter.empty
- else (
- f" = '{str(parameter.default)}'"
- if isinstance(parameter.default, str)
- else f" = {str(parameter.default)}"
- )
- )
+ # Handle annotation
+ if parameter.annotation == inspect.Parameter.empty:
+ annotation = ""
+ elif isinstance(parameter.annotation, str):
+ annotation = f": {parameter.annotation}"
+ else:
+ annotation = f": {parameter.annotation.__name__}"
+
+ # Handle default value
+ if parameter.default == inspect.Parameter.empty:
+ default = ""
+ elif isinstance(parameter.default, str):
+ default = f" = '{parameter.default}'"
+ else:
+ default = f" = {parameter.default}"
+
return parameter.name + annotation + default
diff --git a/marimo/_server/lsp.py b/marimo/_server/lsp.py
index 29f7d010d9..fb03544a0e 100644
--- a/marimo/_server/lsp.py
+++ b/marimo/_server/lsp.py
@@ -4,14 +4,13 @@ from __future__ import annotations
import os
import subprocess
from abc import ABC, abstractmethod
-from typing import Any, Literal, Optional, Union, cast
+from typing import 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._runtime.complete import _get_docstring
from marimo._server.utils import find_free_port
from marimo._tracer import server_tracer
from marimo._utils.paths import marimo_package_path
@@ -232,45 +231,3 @@ class CompositeLspServer(LspServer):
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 None
diff --git a/marimo/_utils/docs.py b/marimo/_utils/docs.py
index f4070cec20..9ff6e69faa 100644
--- a/marimo/_utils/docs.py
+++ b/marimo/_utils/docs.py
@@ -1,4 +1,6 @@
# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
import re
from textwrap import dedent
@@ -193,3 +195,20 @@ def google_docstring_to_markdown(docstring: str) -> str:
output.append(f"- **{err_type}**: {explanation.strip()}")
return "\n".join(output)
+
+
+# See https://github.com/python-lsp/docstring-to-markdown?tab=readme-ov-file#extensibility
+class MarimoConverter:
+ priority = 100
+
+ SECTION_HEADERS = ["Args", "Returns", "Raises"]
+
+ def convert(self, docstring: str) -> str:
+ return google_docstring_to_markdown(docstring)
+
+ def can_convert(self, docstring: str) -> bool:
+ for section in self.SECTION_HEADERS:
+ if re.search(rf"{section}:\n", docstring):
+ return True
+
+ return False
diff --git a/pyproject.toml b/pyproject.toml
index a5fe3e5a57..cbf87db3ae 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -78,8 +78,8 @@ marimo = "marimo._cli.cli:main"
[project.urls]
homepage = "https://github.com/marimo-team/marimo"
-[project.entry-points."pylsp"]
-marimo_plugin = "marimo._server.lsp"
+[project.entry-points."docstring_to_markdown"]
+marimo_converter = "marimo._utils.docs:MarimoConverter"
[project.optional-dependencies]
sql = [
diff --git a/tests/_output/test_rich_help.py b/tests/_output/test_rich_help.py
new file mode 100644
index 0000000000..b3b46513d8
--- /dev/null
+++ b/tests/_output/test_rich_help.py
@@ -0,0 +1,198 @@
+from __future__ import annotations
+
+import inspect
+from dataclasses import dataclass
+from typing import Any, Optional
+
+from marimo._output.rich_help import (
+ RichHelp,
+ _doc_with_signature,
+ _format_parameter,
+ _get_signature,
+ mddoc,
+)
+
+
+def test_format_parameter() -> None:
+ """Test the _format_parameter function with different parameter types."""
+ # Parameter with no annotation or default
+ param = inspect.Parameter(
+ "simple_param", inspect.Parameter.POSITIONAL_OR_KEYWORD
+ )
+ assert _format_parameter(param) == "simple_param"
+
+ # Parameter with annotation but no default
+ param = inspect.Parameter(
+ "typed_param",
+ inspect.Parameter.POSITIONAL_OR_KEYWORD,
+ annotation=str,
+ )
+ assert _format_parameter(param) == "typed_param: str"
+
+ # Parameter with default but no annotation
+ param = inspect.Parameter(
+ "default_param",
+ inspect.Parameter.POSITIONAL_OR_KEYWORD,
+ default=42,
+ )
+ assert _format_parameter(param) == "default_param = 42"
+
+ # Parameter with string default
+ param = inspect.Parameter(
+ "string_default",
+ inspect.Parameter.POSITIONAL_OR_KEYWORD,
+ default="default",
+ )
+ assert _format_parameter(param) == "string_default = 'default'"
+
+ # Parameter with annotation and default
+ param = inspect.Parameter(
+ "full_param",
+ inspect.Parameter.POSITIONAL_OR_KEYWORD,
+ annotation=int,
+ default=100,
+ )
+ assert _format_parameter(param) == "full_param: int = 100"
+
+
+def test_get_signature_function() -> None:
+ """Test _get_signature with a function."""
+
+ def example_func(arg1: str, arg2: int = 42) -> bool:
+ """Example function for testing."""
+ del arg1, arg2
+ return True
+
+ signature = _get_signature(example_func)
+ assert "def example_func(arg1: str, arg2: int = 42) -> bool:" in signature
+
+
+def test_get_signature_class() -> None:
+ """Test _get_signature with a class."""
+
+ @dataclass
+ class ExampleClass:
+ name: str
+ value: int = 0
+
+ signature = _get_signature(ExampleClass)
+ assert "class ExampleClass(name: str, value: int = 0)" in signature
+
+
+def test_get_signature_class_with_exception() -> None:
+ """Test _get_signature with a class that raises an exception during signature inspection."""
+
+ # Create a mock class that raises an exception when inspect.signature is called
+ class ComplicatedClass:
+ def __init__(self):
+ pass
+
+ # Make __name__ a property to simulate inspect.signature raising an exception
+ @property
+ def __name__(self):
+ return "ComplicatedClass"
+
+ # Create an instance and patch it to throw an exception on inspect.signature
+ obj = ComplicatedClass()
+
+ # Monkey patch __signature__ to raise an exception
+ def raise_exception(*args: Any, **kwargs: Any) -> Any:
+ del args, kwargs
+ raise ValueError("Cannot get signature")
+
+ original_signature = inspect.signature
+ try:
+ inspect.signature = raise_exception
+ result = _get_signature(obj)
+ assert "ComplicatedClass" in result
+ finally:
+ inspect.signature = original_signature
+
+
+def test_doc_with_signature() -> None:
+ """Test the _doc_with_signature function."""
+
+ def example_func(arg: str) -> None:
+ """This is a docstring."""
+ pass
+
+ result = _doc_with_signature(example_func)
+ assert "```python" in result
+ assert "def example_func(arg: str) -> None:" in result
+ assert "This is a docstring." in result
+
+ # Test with no docstring
+ def no_doc(arg: str) -> None:
+ pass
+
+ result = _doc_with_signature(no_doc)
+ assert "```python" in result
+ assert "def no_doc(arg: str) -> None:" in result
+ assert "\n\n" not in result # No docstring section
+
+
+def test_richhelp_protocol() -> None:
+ """Test the RichHelp protocol implementation."""
+
+ # Test that the default _rich_help_ implementation works
+ assert RichHelp._rich_help_() is not None
+ assert (
+ "Protocol to provide a class or function docstring"
+ in RichHelp._rich_help_()
+ )
+
+ # Test with a class implementing the protocol
+ class MyClass:
+ """My class docstring."""
+
+ @staticmethod
+ def _rich_help_() -> Optional[str]:
+ return "Custom rich help for MyClass"
+
+ # Check if MyClass is recognized as implementing RichHelp protocol
+ assert isinstance(MyClass, RichHelp)
+ assert MyClass._rich_help_() == "Custom rich help for MyClass"
+
+
+def test_mddoc_decorator() -> None:
+ """Test the mddoc decorator."""
+
+ @mddoc
+ def decorated_func(arg1: str, arg2: int = 10) -> bool:
+ """Example function with Google style docstring.
+
+ Args:
+ arg1: First argument
+ arg2: Second argument with default
+
+ Returns:
+ A boolean value
+ """
+ del arg1, arg2
+ return True
+
+ # Test that _rich_help_ method was added
+ assert hasattr(decorated_func, "_rich_help_")
+ rich_help_output = decorated_func._rich_help_()
+ assert rich_help_output is not None
+ assert "```python" in rich_help_output
+ assert (
+ "def decorated_func(arg1: str, arg2: int = 10) -> bool:"
+ in rich_help_output
+ )
+
+ # Test that the docstring was wrapped with MarkdownDocstring
+ # assert isinstance(decorated_func.__doc__, MarkdownDocstring)
+ assert isinstance(decorated_func.__doc__, str)
+
+ # Test with a class
+ @mddoc
+ class DecoratedClass:
+ """A class with docstring."""
+
+ def __init__(self, name: str):
+ self.name = name
+
+ assert hasattr(DecoratedClass, "_rich_help_")
+ rich_help_output = DecoratedClass._rich_help_()
+ assert "class DecoratedClass(name: str)" in rich_help_output
diff --git a/tests/_server/test_lsp.py b/tests/_server/test_lsp.py
index bed9c4788d..57afd2578c 100644
--- a/tests/_server/test_lsp.py
+++ b/tests/_server/test_lsp.py
@@ -7,7 +7,6 @@ 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,
@@ -147,25 +146,3 @@ def test_composite_server():
)
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