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.

fix: don't autorun markdown on f-string. use jedi for python completion (#4672)

Myles Scolnickf2a1ef2477f1
diff --git a/frontend/src/core/codemirror/cells/extensions.ts b/frontend/src/core/codemirror/cells/extensions.ts
index abe04cb456..c3efd1c896 100644
--- a/frontend/src/core/codemirror/cells/extensions.ts
+++ b/frontend/src/core/codemirror/cells/extensions.ts
@@ -301,7 +301,11 @@ function cellCodeEditing(hotkeys: HotkeyProvider): Extension[] {
/**
* Extension for auto-running markdown cells
*/
-export function markdownAutoRunExtension(): Extension {
+export function markdownAutoRunExtension({
+ predicate,
+}: {
+ predicate: () => boolean;
+}): Extension {
return EditorView.updateListener.of((update) => {
// If the doc didn't change, ignore
if (!update.docChanged) {
@@ -314,6 +318,10 @@ export function markdownAutoRunExtension(): Extension {
return;
}
+ if (!predicate()) {
+ return;
+ }
+
// This happens on mount when we start in markdown mode
const isFormattingChange = update.transactions.some((tr) =>
tr.effects.some((effect) => effect.is(formattingChangeEffect)),
diff --git a/frontend/src/core/codemirror/completion/completer.ts b/frontend/src/core/codemirror/completion/completer.ts
index a61701d9e7..45353c7156 100644
--- a/frontend/src/core/codemirror/completion/completer.ts
+++ b/frontend/src/core/codemirror/completion/completer.ts
@@ -2,6 +2,7 @@
import type {
CompletionContext,
CompletionResult,
+ CompletionSource,
} from "@codemirror/autocomplete";
import { AUTOCOMPLETER, Autocompleter } from "./Autocompleter";
@@ -10,9 +11,12 @@ import { type CellId, HTMLCellId } from "@/core/cells/ids";
import { store } from "@/core/state/jotai";
import { documentationAtom } from "@/core/documentation/state";
-export async function completer(
+/**
+ * Completion source for Python, using Jedi.
+ */
+export const pythonCompletionSource: CompletionSource = async (
context: CompletionContext,
-): Promise<CompletionResult | null> {
+): Promise<CompletionResult | null> => {
const query = context.state.doc.sliceString(0, context.pos);
const element = document.activeElement;
let cellId: CellId | null = null;
@@ -52,4 +56,4 @@ export async function completer(
}
return Autocompleter.asCompletionResult(context.pos, result);
-}
+};
diff --git a/frontend/src/core/codemirror/completion/utils.ts b/frontend/src/core/codemirror/completion/utils.ts
new file mode 100644
index 0000000000..6a809de0e4
--- /dev/null
+++ b/frontend/src/core/codemirror/completion/utils.ts
@@ -0,0 +1,16 @@
+import type { CompletionSource } from "@codemirror/autocomplete";
+
+/**
+ * Condition CompletionSource
+ */
+export function conditionalCompletion(opts: {
+ completion: CompletionSource;
+ predicate: () => boolean;
+}): CompletionSource {
+ return (ctx) => {
+ if (!opts.predicate()) {
+ return null;
+ }
+ return opts.completion(ctx);
+ };
+}
diff --git a/frontend/src/core/codemirror/language/__tests__/embedded-python.test.ts b/frontend/src/core/codemirror/language/__tests__/embedded-python.test.ts
index 916c951e4e..e5c7813cb6 100644
--- a/frontend/src/core/codemirror/language/__tests__/embedded-python.test.ts
+++ b/frontend/src/core/codemirror/language/__tests__/embedded-python.test.ts
@@ -1,30 +1,15 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { describe, it, expect, beforeEach } from "vitest";
-import {
- parsePython,
- embeddedPythonCompletions,
- variableCompletionSource,
-} from "../embedded-python";
+import { parsePython, variableCompletionSource } from "../embedded-python";
import { EditorState } from "@codemirror/state";
import { python } from "@codemirror/lang-python";
import { store } from "@/core/state/jotai";
import { variablesAtom } from "@/core/variables/state";
import type { Variables, VariableName } from "@/core/variables/types";
import type { CellId } from "@/core/cells/ids";
-import type {
- CompletionContext,
- CompletionResult,
-} from "@codemirror/autocomplete";
+import type { CompletionContext } from "@codemirror/autocomplete";
import type { InlineContext } from "@lezer/markdown";
-interface LanguageDataValue {
- autocomplete: (context: CompletionContext) => CompletionResult | null;
-}
-
-interface LanguageDataExtension {
- value: LanguageDataValue;
-}
-
const IS_ACTIVE = () => true;
describe("parsePython", () => {
@@ -63,116 +48,6 @@ describe("parsePython", () => {
});
});
-describe("embeddedPythonCompletions", () => {
- beforeEach(() => {
- const mockCellId = "cell-1" as CellId;
- const mockVariables: Variables = {
- ["var1" as VariableName]: {
- name: "var1" as VariableName,
- dataType: "int",
- declaredBy: [mockCellId],
- usedBy: [mockCellId],
- },
- ["var2" as VariableName]: {
- name: "var2" as VariableName,
- dataType: "str",
- declaredBy: [mockCellId],
- usedBy: [mockCellId],
- },
- };
- store.set(variablesAtom, mockVariables);
- });
-
- it("should provide autocomplete for variables", () => {
- const extensions = embeddedPythonCompletions(IS_ACTIVE);
- const state = EditorState.create({
- doc: "print(",
- extensions: extensions,
- });
-
- const context: Partial<CompletionContext> = {
- pos: 6,
- explicit: true,
- matchBefore: (expr: RegExp) => ({ from: 0, to: 6, text: "" }),
- state,
- aborted: false,
- tokenBefore: (types: readonly string[]) => null,
- };
-
- const extension = (extensions as unknown as LanguageDataExtension[])[0];
- const result = extension.value.autocomplete(context as CompletionContext);
- expect(result).toBeDefined();
- expect(result?.options).toHaveLength(2);
- expect(result?.options[0].label).toBe("var1");
- expect(result?.options[0].detail).toBe("int");
- });
-
- it("should filter autocomplete options based on input", () => {
- const extensions = embeddedPythonCompletions(IS_ACTIVE);
- const state = EditorState.create({
- doc: "print(v",
- extensions: extensions,
- });
-
- const context: Partial<CompletionContext> = {
- pos: 7,
- explicit: true,
- matchBefore: (expr: RegExp) => ({ from: 6, to: 7, text: "v" }),
- state,
- aborted: false,
- tokenBefore: (types: readonly string[]) => null,
- };
-
- const extension = (extensions as unknown as LanguageDataExtension[])[0];
- const result = extension.value.autocomplete(context as CompletionContext);
- expect(result).toBeDefined();
- expect(result?.options).toHaveLength(2);
- expect(result?.from).toBe(6);
- });
-
- it("should not provide autocomplete when not activated", () => {
- const extensions = embeddedPythonCompletions(() => false);
- const state = EditorState.create({
- doc: "print(",
- extensions: extensions,
- });
-
- const context: Partial<CompletionContext> = {
- pos: 6,
- explicit: true,
- matchBefore: (expr: RegExp) => ({ from: 0, to: 6, text: "" }),
- state,
- aborted: false,
- tokenBefore: (types: readonly string[]) => null,
- };
-
- const extension = (extensions as unknown as LanguageDataExtension[])[0];
- const result = extension.value.autocomplete(context as CompletionContext);
- expect(result).toBeNull();
- });
-
- it("should not provide autocomplete for non-word characters", () => {
- const extensions = embeddedPythonCompletions(IS_ACTIVE);
- const state = EditorState.create({
- doc: "print(+",
- extensions: extensions,
- });
-
- const context: Partial<CompletionContext> = {
- pos: 7,
- explicit: false,
- matchBefore: () => null,
- state,
- aborted: false,
- tokenBefore: (types: readonly string[]) => null,
- };
-
- const extension = (extensions as unknown as LanguageDataExtension[])[0];
- const result = extension.value.autocomplete(context as CompletionContext);
- expect(result).toBeNull();
- });
-});
-
describe("variableCompletionSource", () => {
beforeEach(() => {
const mockCellId = "cell-1" as CellId;
diff --git a/frontend/src/core/codemirror/language/embedded-python.ts b/frontend/src/core/codemirror/language/embedded-python.ts
index 343cef64bd..ea211e770b 100644
--- a/frontend/src/core/codemirror/language/embedded-python.ts
+++ b/frontend/src/core/codemirror/language/embedded-python.ts
@@ -11,7 +11,6 @@ import type {
CompletionResult,
} from "@codemirror/autocomplete";
import { variablesAtom } from "@/core/variables/state";
-import type { Extension } from "@codemirror/state";
import { getVariableCompletions } from "../completion/variable-completions";
// Python code block delimiters
@@ -92,46 +91,6 @@ export function parsePython(
};
}
-const languageData = python().language.data;
-
-/**
- * Embedded Python completions
- *
- * @param isActivated Function that returns whether the extension should be activated
- */
-export function embeddedPythonCompletions(
- isActivated: () => boolean,
-): Extension {
- return [
- languageData.of({
- autocomplete: (context: CompletionContext): CompletionResult | null => {
- if (!isActivated()) {
- return null;
- }
-
- // Check if the cursor is at a position where a variable can be inserted
- const wordMatch = context.matchBefore(/\w*$/);
- if (!context.explicit && !wordMatch) {
- return null;
- }
-
- const filter = wordMatch?.text ?? "";
-
- const options = getVariableCompletions(
- store.get(variablesAtom),
- new Set(),
- );
-
- return {
- from: context.pos - filter.length,
- options,
- validFor: /^\w*$/,
- };
- },
- }),
- ];
-}
-
/**
* Cheap variable completion source without having to go through the
* backend.
diff --git a/frontend/src/core/codemirror/language/markdown.ts b/frontend/src/core/codemirror/language/markdown.ts
index f9214d894c..a09a18273b 100644
--- a/frontend/src/core/codemirror/language/markdown.ts
+++ b/frontend/src/core/codemirror/language/markdown.ts
@@ -2,7 +2,7 @@
import type { Extension } from "@codemirror/state";
import type { LanguageAdapter } from "./types";
import { markdown, markdownLanguage } from "@codemirror/lang-markdown";
-import { pythonLanguage } from "@codemirror/lang-python";
+import { python, pythonLanguage } from "@codemirror/lang-python";
import { languages } from "@codemirror/language-data";
import { stexMath } from "@codemirror/legacy-modes/mode/stex";
// @ts-expect-error: no declaration file
@@ -29,7 +29,9 @@ import type { PlaceholderType } from "../config/extension";
import type { CellId } from "@/core/cells/ids";
import { parseLatex } from "./latex";
import { StreamLanguage } from "@codemirror/language";
-import { embeddedPythonCompletions, parsePython } from "./embedded-python";
+import { parsePython } from "./embedded-python";
+import { conditionalCompletion } from "../completion/utils";
+import { pythonCompletionSource } from "../completion/completer";
const quoteKinds = [
['"""', '"""'],
@@ -187,7 +189,13 @@ export class MarkdownLanguageAdapter implements LanguageAdapter {
markdownLanguageData.of({ autocomplete: lucideIconCompletionSource }),
markdownLanguageData.of({ autocomplete: latexSymbolCompletionSource }),
// Completions for embedded Python
- embeddedPythonCompletions(isFStringActive),
+ python().language.data.of({
+ autocomplete: conditionalCompletion({
+ completion: pythonCompletionSource,
+ predicate: isFStringActive,
+ }),
+ }),
+
autocompletion({
// We remove the default keymap because we use our own which
// handles the Escape key correctly in Vim
@@ -195,7 +203,7 @@ export class MarkdownLanguageAdapter implements LanguageAdapter {
activateOnTyping: true,
}),
// Markdown autorun
- markdownAutoRunExtension(),
+ markdownAutoRunExtension({ predicate: () => !isFStringActive() }),
];
}
diff --git a/frontend/src/core/codemirror/language/python.ts b/frontend/src/core/codemirror/language/python.ts
index defc33db38..9f24555d12 100644
--- a/frontend/src/core/codemirror/language/python.ts
+++ b/frontend/src/core/codemirror/language/python.ts
@@ -32,7 +32,7 @@ import { WebSocketTransport } from "@open-rpc/client-js";
import { NotebookLanguageServerClient } from "../lsp/notebook-lsp";
import { once } from "@/utils/once";
import { autocompletion } from "@codemirror/autocomplete";
-import { completer } from "../completion/completer";
+import { pythonCompletionSource } from "../completion/completer";
import { getFilenameFromDOM } from "@/core/dom/htmlUtils";
import { Paths } from "@/utils/paths";
import type { CellId } from "@/core/cells/ids";
@@ -214,7 +214,7 @@ export class PythonLanguageAdapter implements LanguageAdapter {
return autocompletion({
...autocompleteOptions,
- override: [completer],
+ override: [pythonCompletionSource],
});
};