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
fix: better completions around function calls (#10045)
Akshay Agrawal4f01b1b720a0
diff --git a/frontend/src/core/codemirror/completion/__tests__/signature-hint.test.ts b/frontend/src/core/codemirror/completion/__tests__/signature-hint.test.tsnew file mode 100644index 0000000000..e89efaa250--- /dev/null+++ b/frontend/src/core/codemirror/completion/__tests__/signature-hint.test.ts@@ -0,0 +1,94 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { EditorState } from "@codemirror/state";+import { EditorView, type Tooltip } from "@codemirror/view";+import { describe, expect, it } from "vitest";+import {+ asSignatureHint,+ setSignatureHintEffect,+ signatureHintField,+} from "../signature-hint";++function fakeTooltip(pos: number): Tooltip {+ return {+ pos,+ above: true,+ create: () => ({ dom: document.createElement("div") }),+ };+}++function stateWithHint(doc: string, pos: number): EditorState {+ const state = EditorState.create({+ doc,+ extensions: [signatureHintField],+ });+ return state.update({ effects: setSignatureHintEffect.of(fakeTooltip(pos)) })+ .state;+}++describe("signatureHintField", () => {+ it("starts empty", () => {+ const state = EditorState.create({ extensions: [signatureHintField] });+ expect(state.field(signatureHintField)).toBeNull();+ });++ it("shows a tooltip when the effect is dispatched", () => {+ const state = stateWithHint("plt.plot(", 9);+ expect(state.field(signatureHintField)?.pos).toBe(9);+ });++ it("clears the tooltip when the effect dispatches null", () => {+ let state = stateWithHint("plt.plot(", 9);+ state = state.update({+ effects: setSignatureHintEffect.of(null),+ }).state;+ expect(state.field(signatureHintField)).toBeNull();+ });++ it("dismisses the tooltip on a selection-only change", () => {+ let state = stateWithHint("plt.plot(x)", 9);+ state = state.update({ selection: { anchor: 0 } }).state;+ expect(state.field(signatureHintField)).toBeNull();+ });++ it("keeps and re-anchors the tooltip across edits", () => {+ let state = stateWithHint("plt.plot(", 9);+ // Insert before the tooltip position; it should shift to stay anchored.+ state = state.update({ changes: { from: 0, insert: "xy" } }).state;+ expect(state.field(signatureHintField)?.pos).toBe(11);+ });+});++describe("asSignatureHint", () => {+ it("nests the content so descendant styling applies", () => {+ const content = document.createElement("span");+ content.classList.add("mo-cm-tooltip", "docs-documentation");+ const base: Tooltip = {+ pos: 0,+ create: () => ({ dom: content, resize: false }),+ };++ const view = new EditorView({ state: EditorState.create({}) });+ const { dom } = asSignatureHint(base).create(view);++ // Outer wrapper carries the tooltip sizing class...+ expect(dom.classList.contains("mo-cm-tooltip")).toBe(true);+ // ...and the documentation content is a descendant (not the same node),+ // so `.cm-tooltip .docs-documentation` padding/font rules match.+ expect(dom).not.toBe(content);+ expect(dom.querySelector(".docs-documentation")).toBe(content);++ view.destroy();+ });++ it("preserves other tooltip fields", () => {+ const base: Tooltip = {+ pos: 5,+ above: true,+ create: () => ({ dom: document.createElement("span"), resize: false }),+ };+ const wrapped = asSignatureHint(base);+ expect(wrapped.pos).toBe(5);+ expect(wrapped.above).toBe(true);+ });+});diff --git a/frontend/src/core/codemirror/completion/completer.ts b/frontend/src/core/codemirror/completion/completer.tsindex 5077224506..2affdb8f00 100644--- a/frontend/src/core/codemirror/completion/completer.ts+++ b/frontend/src/core/codemirror/completion/completer.ts@@ -9,6 +9,7 @@ import { documentationAtom } from "@/core/documentation/state";import { store } from "@/core/state/jotai";import { Logger } from "../../../utils/Logger";import { AUTOCOMPLETER, Autocompleter } from "./Autocompleter";+import { asSignatureHint, setSignatureHintEffect } from "./signature-hint";/*** Completion source for Python, using Jedi.@@ -36,10 +37,12 @@ export const pythonCompletionSource: CompletionSource = async (cellId: cellId,});if (!result) {+ context.view?.dispatch({ effects: setSignatureHintEffect.of(null) });return null;}- // If it is a tooltip, show it as a Tooltip instead of a completion+ // If it is a tooltip (e.g. a signature after `(` or `,`), show it as a+ // Tooltip instead of a completion.const tooltip = Autocompleter.asHoverTooltip({position: context.pos,message: result,@@ -50,6 +53,14 @@ export const pythonCompletionSource: CompletionSource = async (documentation: tooltip.html ?? null,});}+ // Surface the signature as a floating hint near the cursor (the LSP path has+ // its own signature help), and clear any stale hint when we instead have a+ // real completion list.+ context.view?.dispatch({+ effects: setSignatureHintEffect.of(+ tooltip ? asSignatureHint(tooltip) : null,+ ),+ });if (tooltip) {return null;}diff --git a/frontend/src/core/codemirror/completion/signature-hint.ts b/frontend/src/core/codemirror/completion/signature-hint.tsnew file mode 100644index 0000000000..c5413fbcdf--- /dev/null+++ b/frontend/src/core/codemirror/completion/signature-hint.ts@@ -0,0 +1,68 @@+/* Copyright 2026 Marimo. All rights reserved. */+import { StateEffect, StateField } from "@codemirror/state";+import { showTooltip, type Tooltip } from "@codemirror/view";++/**+ * Effect to set (or clear, with `null`) the floating signature hint.+ */+export const setSignatureHintEffect = StateEffect.define<Tooltip | null>();++/**+ * Wrap a tooltip so it renders like the completion popup's info box.+ *+ * CodeMirror adds `cm-tooltip` directly to the DOM node returned by `create`,+ * so the documentation content ends up on the same element as `cm-tooltip`.+ * Our styling for padding/font (`.cm-tooltip .docs-documentation`) is a+ * descendant selector, so we nest the content one level deeper to make it+ * apply — mirroring how CodeMirror nests completion info inside its own+ * wrapper. The outer `mo-cm-tooltip` class picks up the shared tooltip sizing.+ */+export function asSignatureHint(tooltip: Tooltip): Tooltip {+ return {+ ...tooltip,+ create: (view) => {+ const { dom: content, ...rest } = tooltip.create(view);+ const dom = document.createElement("div");+ dom.classList.add("mo-cm-tooltip");+ dom.append(content);+ return { ...rest, dom };+ },+ };+}++/**+ * Holds the floating "signature hint" shown after typing `(` or `,` inside a+ * call on the non-LSP (Jedi) completion path.+ *+ * The LSP path has its own signature help; this fills the gap for users+ * without a language server. The completion source (`pythonCompletionSource`)+ * drives it: it dispatches `setSignatureHintEffect` with the tooltip when the+ * backend returns a signature and with `null` otherwise. The hint is also+ * cleared when the cursor moves via a selection-only change (e.g. clicking+ * away or arrowing out of the call), and kept anchored across edits so it+ * doesn't flicker while a fresh result is in flight.+ */+export const signatureHintField = StateField.define<Tooltip | null>({+ create: () => null,+ update(tooltip, tr) {+ for (const effect of tr.effects) {+ if (effect.is(setSignatureHintEffect)) {+ return effect.value;+ }+ }+ if (!tooltip) {+ return null;+ }+ // Cursor moved without editing (click / arrow key): dismiss the hint.+ if (tr.selection && !tr.docChanged) {+ return null;+ }+ // Keep the hint anchored across edits; the completion source refreshes or+ // clears it as new results arrive.+ if (tr.docChanged) {+ return { ...tooltip, pos: tr.changes.mapPos(tooltip.pos) };+ }+ return tooltip;+ },+ provide: (field) => showTooltip.from(field),+});diff --git a/frontend/src/core/codemirror/language/languages/python.ts b/frontend/src/core/codemirror/language/languages/python.tsindex 9b50517e55..1366055f4d 100644--- a/frontend/src/core/codemirror/language/languages/python.ts+++ b/frontend/src/core/codemirror/language/languages/python.ts@@ -31,6 +31,7 @@ import { Logger } from "@/utils/Logger";import { once } from "@/utils/once";import { cellActionsState } from "../../cells/state";import { pythonCompletionSource } from "../../completion/completer";+import { signatureHintField } from "../../completion/signature-hint";import type { PlaceholderType } from "../../config/types";import { FederatedLanguageServerClient } from "../../lsp/federated-lsp";import { createLspMarkdownRenderer } from "../../lsp/markdown-renderer";@@ -376,10 +377,15 @@ export class PythonLanguageAdapter implements LanguageAdapter<{}> {];}- return autocompletion({- ...autocompleteOptions,- override: [pythonCompletionSource],- });+ return [+ autocompletion({+ ...autocompleteOptions,+ override: [pythonCompletionSource],+ }),+ // The Jedi path has no built-in signature help; show a floating hint+ // fed by `pythonCompletionSource` (the LSP path handles this itself).+ signatureHintField,+ ];};return [diff --git a/marimo/_runtime/complete.py b/marimo/_runtime/complete.pyindex 6d44418261..1525cf3fb2 100644--- a/marimo/_runtime/complete.py+++ b/marimo/_runtime/complete.py@@ -60,13 +60,17 @@ def _should_include_name(name: str, prefix: str) -> bool:DOC_CACHE_SIZE = 200-# Normally '.' is the trigger character for completions.+# Characters that trigger the completion list when the prefix is empty.#-# We also want to trigger completions on '(', ',' because-# we don't open the signature popup on these characters.+# `.` triggers attribute completions and `/` triggers file-path completions.#-# We also add '/' for file path completion.-COMPLETION_TRIGGER_CHARACTERS = frozenset({".", "(", ",", "/"})+# We intentionally do NOT trigger the completion list on `(` or `,`. At those+# positions Jedi has no prefix to filter on and returns the entire namespace+# (every builtin and global), producing a noisy popup and accidental+# completions (e.g. after typing `1,`). Instead, an empty prefix after these+# characters falls through to signature help below, which is the useful+# behavior inside a call's argument list (e.g. `mo.ui.slider(start=1,`).+COMPLETION_TRIGGER_CHARACTERS = frozenset({".", "/"})# Matches display bracket delimiters: \[...\]_MATH_DISPLAY_BRACKET_PATTERN = re.compile(r"\\\[(.+?)\\\]", re.DOTALL)# Matches inline paren delimiters: \(...\)@@ -303,7 +307,6 @@ def _get_completion_info(completion: jedi.api.classes.BaseName) -> str:def _get_completion_option(completion: jedi.api.classes.Completion,- script: jedi.Script,compute_completion_info: bool,compute_type: bool = True,) -> CompletionOption:@@ -319,15 +322,14 @@ def _get_completion_option(kind = completion.typeif compute_completion_info:- # Choose whether the completion info should be from the name- # or the enclosing function's signature, if any- symbol_to_lookup = completion- if kind == "param":- # Show the function/class docstring if available- signatures = script.get_signatures()- if len(signatures) == 1:- symbol_to_lookup = signatures[0]- completion_info = _get_completion_info(symbol_to_lookup)+ # Show the completion's own documentation. For a parameter this is the+ # description of that single parameter, which+ # `patch_jedi_parameter_completion` extracts from the enclosing+ # function's docstring. We deliberately do not fall back to the full+ # function docstring: repeating it for every parameter is noisy, and+ # the signature hint already provides function-level context when the+ # call is opened.+ completion_info = _get_completion_info(completion)else:completion_info = ""@@ -338,7 +340,6 @@ def _get_completion_option(def _get_completion_options(completions: list[jedi.api.classes.Completion],- script: jedi.Script,prefix: str,limit: int,timeout: float,@@ -358,7 +359,6 @@ def _get_completion_options(completion_options.append(_get_completion_option(completion,- script,compute_completion_info=compute_docstringsand under_time_budget,compute_type=under_time_budget,@@ -685,11 +685,20 @@ def complete()return- if (- prefix_length == 0- and len(request.document) >= 1- and request.document[-1] not in COMPLETION_TRIGGER_CHARACTERS- ):+ # `/` triggers file-path completion inside strings. As an arithmetic+ # operator (e.g. `1 / `) it sits at an expression position where Jedi+ # returns the entire namespace, so only honor it as a trigger when the+ # results are actually paths. Jedi tags path completions with+ # `type == "path"`, and a path context yields only path completions, so+ # checking the first is enough (and avoids inferring the whole list).+ last_char = request.document[-1:]+ is_trigger_char = last_char in COMPLETION_TRIGGER_CHARACTERS+ if is_trigger_char and last_char == "/":+ is_trigger_char = (+ bool(completions) and completions[0].type == "path"+ )++ if prefix_length == 0 and request.document and not is_trigger_char:# Empty prefix, not dot notation; don't complete ...completions = []@@ -731,7 +740,6 @@ def complete(options = _get_completion_options(completions,- script,prefix=prefix,limit=docstrings_limit,timeout=timeout,diff --git a/tests/_runtime/test_complete.py b/tests/_runtime/test_complete.pyindex e33ba7e04c..3a6514fcc7 100644--- a/tests/_runtime/test_complete.py+++ b/tests/_runtime/test_complete.py@@ -698,6 +698,113 @@ mixed_keys = {"static_key": "foo", str(random.randint(0, 10)): "bar"}assert set(options_values) == set(expected_keys)+def _run_complete(document: str, other_code: str = "") -> dict[str, Any]:+ """Run the `complete()` entrypoint and return the emitted notification."""+ current_cell_id = CellId_t("current-cell")++ mock_other_cell = mock.MagicMock()+ mock_other_cell.code = other_code+ mock_current_cell = mock.MagicMock()+ mock_current_cell.code = document++ mock_graph = mock.MagicMock()+ mock_graph.cells = {+ "other-cell": mock_other_cell,+ current_cell_id: mock_current_cell,+ }++ glbls: dict[str, Any] = {}+ if other_code:+ exec(other_code, {}, glbls)++ stream = CaptureStream()+ complete(+ request=CodeCompletionCommand(+ id="request-id", document=document, cell_id=current_cell_id+ ),+ graph=mock_graph,+ glbls=glbls,+ glbls_lock=threading.RLock(),+ stream=stream,+ )+ assert len(stream.operations) == 1+ return stream.operations[0]++[email protected]("document", ["1,", "foo(", "foo(1,", "[1, "])+def test_no_completions_after_comma_or_paren_without_signature(+ document: str,+) -> None:+ """An empty prefix after `,` or `(` must not dump the whole namespace.++ Regression test: previously `,` and `(` were treated as completion trigger+ characters, so typing e.g. `1,` opened a popup listing every builtin.+ """+ content = _run_complete(document)+ assert content["op"] == CompletionResultNotification.name+ assert content["options"] == []++[email protected]("document", ["my_func(", "my_func(1,"])+def test_signature_shown_after_comma_or_paren_in_call(document: str) -> None:+ """Inside a known call, an empty prefix falls through to signature help."""+ content = _run_complete(+ document, other_code="def my_func(a, b): return a + b"+ )+ assert content["op"] == CompletionResultNotification.name+ assert len(content["options"]) == 1+ option = content["options"][0]+ assert option["type"] == "tooltip"+ assert option["name"] == "my_func"++[email protected]("document", ["1 / ", "x = 10 /", "a = b / "])+def test_no_completions_for_division_operator(document: str) -> None:+ """`/` triggers path completion inside strings, but as a division operator+ it must not dump the whole namespace.+ """+ content = _run_complete(document)+ assert content["op"] == CompletionResultNotification.name+ assert content["options"] == []+++def test_path_completion_still_works(tmp_path: Any) -> None:+ """`/` still triggers file-path completion inside a string literal."""+ (tmp_path / "marimo_data.csv").write_text("x\n")+ content = _run_complete(f'open("{tmp_path}/')+ assert content["options"]+ assert all(option["type"] == "path" for option in content["options"])+ assert any(+ "marimo_data.csv" in option["name"] for option in content["options"]+ )+++def test_parameter_completion_omits_full_function_docstring() -> None:+ """Completing a parameter must not dump the whole function docstring.++ Regression test: `param` completions used to be swapped to the enclosing+ signature, so every parameter's info box showed the entire function+ docstring. Now we surface only the parameter's own description (empty when+ it can't be extracted, e.g. without `docstring_to_markdown`), never the+ function summary or a sibling parameter's text.+ """+ other_code = (+ "def my_func(alpha, beta):\n"+ ' """SUMMARY_MARKER.\n\n'+ " Args:\n"+ " alpha: ALPHA_MARKER.\n"+ " beta: BETA_MARKER.\n"+ ' """\n'+ " return alpha\n"+ )+ content = _run_complete("my_func(al", other_code=other_code)+ options = {o["name"]: o for o in content["options"]}+ assert "alpha=" in options+ info = options["alpha="]["completion_info"]+ assert "SUMMARY_MARKER" not in info+ assert "BETA_MARKER" not in info++@pytest.mark.parametrize(("trigger_code", "expected_key_path"),# NOTE trigger code produce by marimo must end with `['` or `["`@@ -763,11 +870,9 @@ class _FakeCompletion:def test_get_completion_option_skips_type_when_compute_type_false() -> None:completion = _FakeCompletion("foo", raise_on_type=True)- script = mock.MagicMock()option = _get_completion_option(completion,- script,compute_completion_info=False,compute_type=False,)@@ -780,11 +885,9 @@ def test_get_completion_option_skips_type_when_compute_type_false() -> None:def test_get_completion_option_computes_type_by_default() -> None:completion = _FakeCompletion("foo", completion_type="class")- script = mock.MagicMock()option = _get_completion_option(completion,- script,compute_completion_info=False,)@@ -798,11 +901,9 @@ def test_get_completion_option_skips_all_inference_when_type_skipped() -> None:further jedi inference (docstring, signature) would defeat the purpose."""completion = _FakeCompletion("foo", raise_on_type=True)- script = mock.MagicMock()option = _get_completion_option(completion,- script,compute_completion_info=True,compute_type=False,)@@ -812,15 +913,13 @@ def test_get_completion_option_skips_all_inference_when_type_skipped() -> None:assert option.completion_info == ""assert completion.type_access_count == 0assert not completion.docstring_called- script.get_signatures.assert_not_called()def test_get_completion_options_skips_docstrings_past_limit() -> None:completions = [_FakeCompletion(f"attr_{i}") for i in range(10)]- script = mock.MagicMock()options = _get_completion_options(- completions, script, prefix="", limit=5, timeout=5.0+ completions, prefix="", limit=5, timeout=5.0)assert len(options) == 10@@ -831,11 +930,8 @@ def test_get_completion_options_skips_docstrings_past_limit() -> None:def test_get_completion_options_keeps_docstrings_under_limit() -> None:completions = [_FakeCompletion(f"attr_{i}") for i in range(3)]- script = mock.MagicMock()- _get_completion_options(- completions, script, prefix="", limit=10, timeout=5.0- )+ _get_completion_options(completions, prefix="", limit=10, timeout=5.0)# All three completions should have had docstring() invokedassert all(c.docstring_called for c in completions)@@ -847,7 +943,6 @@ def test_get_completion_options_bails_out_when_timeout_elapsed() -> None:completions from taking 10+ seconds on heavy libraries."""completions = [_FakeCompletion(f"attr_{i}") for i in range(4)]- script = mock.MagicMock()# Burn time on the first call so the rest see an expired budget.original_monotonic = time.monotonic@@ -858,7 +953,7 @@ def test_get_completion_options_bails_out_when_timeout_elapsed() -> None:side_effect=lambda: next(times, original_monotonic()),):options = _get_completion_options(- completions, script, prefix="", limit=100, timeout=1.0+ completions, prefix="", limit=100, timeout=1.0)# First one completes normally, the rest should have no info or type@@ -876,10 +971,9 @@ def test_get_completion_options_respects_prefix_filter() -> None:_FakeCompletion("_private"),_FakeCompletion("__dunder__"),]- script = mock.MagicMock()options = _get_completion_options(- completions, script, prefix="", limit=100, timeout=5.0+ completions, prefix="", limit=100, timeout=5.0)assert [opt.name for opt in options] == ["public"]@@ -988,9 +1082,7 @@ def test_infer_skipped_for_statements_past_limit() -> None:for i in range(10)]- _get_completion_options(- completions, mock.MagicMock(), prefix="", limit=5, timeout=5.0- )+ _get_completion_options(completions, prefix="", limit=5, timeout=5.0)assert all(c.infer_count == 0 for c in completions)@@ -1007,7 +1099,6 @@ def test_infer_only_runs_for_statements_under_budget() -> None:_get_completion_options(statements + functions,- mock.MagicMock(),prefix="",limit=100,timeout=5.0,@@ -1031,9 +1122,7 @@ def test_infer_skipped_once_timeout_elapsed() -> None:"marimo._runtime.complete.time.monotonic",side_effect=lambda: next(times, original_monotonic()),):- _get_completion_options(- completions, mock.MagicMock(), prefix="", limit=100, timeout=1.0- )+ _get_completion_options(completions, prefix="", limit=100, timeout=1.0)# First completion is under budget and infers; the rest are skipped.assert completions[0].infer_count == 1