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
feat(frontend): Highlight reactive references (#5415)
Trevor Manz7f97b04bce7e
diff --git a/frontend/src/components/app-config/user-config-form.tsx b/frontend/src/components/app-config/user-config-form.tsxindex 1376ea85c7..394b0eac45 100644--- a/frontend/src/components/app-config/user-config-form.tsx+++ b/frontend/src/components/app-config/user-config-form.tsx@@ -659,6 +659,34 @@ export const UserConfigForm: React.FC = () => {</FormItem>)}/>+ <FormField+ control={form.control}+ name="display.reference_highlighting"+ render={({ field }) => (+ <div className="flex flex-col space-y-1">+ <FormItem className={formItemClasses}>+ <FormLabel>Reference highlighting</FormLabel>+ <FormControl>+ <Checkbox+ data-testid="reference-highlighting-checkbox"+ checked={field.value}+ onCheckedChange={field.onChange}+ />+ </FormControl>+ <FormMessage />+ <IsOverridden+ userConfig={config}+ name="display.reference_highlighting"+ />+ </FormItem>++ <FormDescription>+ Visually emphasizes variables in a cell that are defined+ elsewhere in the notebook.+ </FormDescription>+ </div>+ )}+ /></SettingGroup><SettingGroup title="Outputs"><FormFielddiff --git a/frontend/src/components/editor/__tests__/data-attributes.test.tsx b/frontend/src/components/editor/__tests__/data-attributes.test.tsxindex f1a5362492..014ac0471f 100644--- a/frontend/src/components/editor/__tests__/data-attributes.test.tsx+++ b/frontend/src/components/editor/__tests__/data-attributes.test.tsx@@ -43,6 +43,7 @@ describe("Cell data attributes", () => {default_table_page_size: 10,default_width: "normal",theme: "light",+ reference_highlighting: false,},keymap: { preset: "default" },completion: {diff --git a/frontend/src/components/editor/actions/useConfigActions.tsx b/frontend/src/components/editor/actions/useConfigActions.tsxindex 8596f2af5a..acc0c2195b 100644--- a/frontend/src/components/editor/actions/useConfigActions.tsx+++ b/frontend/src/components/editor/actions/useConfigActions.tsx@@ -51,7 +51,7 @@ export function useConfigActions() {},},{- label: "Config > Switch keymap to VIM",+ label: "Config > Switch keymap to VIM",hidden: config.keymap.preset === "vim",handle: () => {handleUserConfig({@@ -103,6 +103,32 @@ export function useConfigActions() {},hidden: config.completion.copilot === "github",},+ {+ label: "Config > Disable reference highlighting",+ hidden: !config.display.reference_highlighting,+ handle: () => {+ handleUserConfig({+ ...config,+ display: {+ ...config.display,+ reference_highlighting: false,+ },+ });+ },+ },+ {+ label: "Config > Enable reference highlighting",+ hidden: config.display.reference_highlighting,+ handle: () => {+ handleUserConfig({+ ...config,+ display: {+ ...config.display,+ reference_highlighting: true,+ },+ });+ },+ },];return actions.filter((a) => !a.hidden);diff --git a/frontend/src/components/editor/cell/code/cell-editor.tsx b/frontend/src/components/editor/cell/code/cell-editor.tsxindex 94b9f7cb2d..3c83f1e99b 100644--- a/frontend/src/components/editor/cell/code/cell-editor.tsx+++ b/frontend/src/components/editor/cell/code/cell-editor.tsx@@ -176,6 +176,7 @@ const CellEditorInternal = ({theme,hotkeys: new OverridingHotkeyProvider(userConfig.keymap.overrides ?? {}),diagnosticsConfig: userConfig.diagnostics,+ displayConfig: userConfig.display,});extensions.push(diff --git a/frontend/src/components/icons/loading-ellipsis.tsx b/frontend/src/components/icons/loading-ellipsis.tsxindex ac41ca18fc..d4cae21cc1 100644--- a/frontend/src/components/icons/loading-ellipsis.tsx+++ b/frontend/src/components/icons/loading-ellipsis.tsx@@ -1,4 +1,4 @@-/* Copyright 2025 Marimo. All rights reserved. */+/* Copyright 2024 Marimo. All rights reserved. */import clsx from "clsx";import { Circle } from "lucide-react";diff --git a/frontend/src/core/codemirror/__tests__/setup.test.ts b/frontend/src/core/codemirror/__tests__/setup.test.tsindex dc39adca3b..ceed7f3e04 100644--- a/frontend/src/core/codemirror/__tests__/setup.test.ts+++ b/frontend/src/core/codemirror/__tests__/setup.test.ts@@ -66,6 +66,7 @@ function getOpts() {diagnosticsConfig: {},hotkeys: new OverridingHotkeyProvider({}),theme: "light",+ displayConfig: { reference_highlighting: false },} as const;}diff --git a/frontend/src/core/codemirror/cm.ts b/frontend/src/core/codemirror/cm.tsindex 017dd2e0d6..2138fd4e99 100644--- a/frontend/src/core/codemirror/cm.ts+++ b/frontend/src/core/codemirror/cm.ts@@ -42,6 +42,7 @@ import type { CellId } from "../cells/ids";import type {CompletionConfig,DiagnosticsConfig,+ DisplayConfig,KeymapConfig,LSPConfig,} from "../config/config-schema";@@ -65,6 +66,7 @@ import { getCurrentLanguageAdapter } from "./language/commands";import { adaptiveLanguageConfiguration } from "./language/extension";import { dndBundle } from "./misc/dnd";import { pasteBundle } from "./misc/paste";+import { reactiveReferencesBundle } from "./reactive-references/extension";import { dynamicReadonly } from "./readonly/extension";import { darkTheme } from "./theme/dark";import { lightTheme } from "./theme/light";@@ -80,6 +82,7 @@ export interface CodeMirrorSetupOpts {hotkeys: HotkeyProvider;lspConfig: LSPConfig;diagnosticsConfig: DiagnosticsConfig;+ displayConfig: Pick<DisplayConfig, "reference_highlighting">;}function getPlaceholderType(opts: CodeMirrorSetupOpts) {@@ -100,6 +103,7 @@ export const setupCodeMirror = (opts: CodeMirrorSetupOpts): Extension[] => {completionConfig,lspConfig,diagnosticsConfig,+ displayConfig,} = opts;const placeholderType = getPlaceholderType(opts);@@ -139,6 +143,11 @@ export const setupCodeMirror = (opts: CodeMirrorSetupOpts): Extension[] => {: [],// Readonly extensiondynamicReadonly(store),+ // Reactive references highlighting+ reactiveReferencesBundle(+ cellId,+ displayConfig.reference_highlighting ?? false,+ ),];};diff --git a/frontend/src/core/codemirror/completion/Autocompleter.ts b/frontend/src/core/codemirror/completion/Autocompleter.tsindex c295f78ff4..3890907d57 100644--- a/frontend/src/core/codemirror/completion/Autocompleter.ts+++ b/frontend/src/core/codemirror/completion/Autocompleter.ts@@ -4,6 +4,7 @@ import type { Tooltip } from "@codemirror/view";import { DeferredRequestRegistry } from "@/core/network/DeferredRequestRegistry";import { sendCodeCompletionRequest } from "@/core/network/requests";import type { CodeCompletionRequest } from "@/core/network/types";+import { isPlatformMac } from "../../hotkeys/shortcuts";import type {CompletionOption,CompletionResultMessage,@@ -12,6 +13,7 @@ import "../../../components/editor/documentation.css";function constructCompletionInfoNode(innerHtml?: string | null,+ showGoToDefinitionHint = false,): HTMLElement | null {if (!innerHtml) {return null;@@ -19,10 +21,40 @@ function constructCompletionInfoNode(const container = document.createElement("span");container.classList.add("mo-cm-tooltip");container.classList.add("docs-documentation");+ if (showGoToDefinitionHint) {+ container.classList.add("cm-tooltip-section");+ }container.style.display = "flex";container.style.flexDirection = "column";container.style.gap = ".8rem";container.innerHTML = innerHtml;++ if (showGoToDefinitionHint) {+ const instructionDiv = document.createElement("div");+ instructionDiv.classList.add(+ "text-xs",+ "text-muted-foreground",+ "font-medium",+ "pt-1",+ "-mt-2",+ "border-t",+ "border-border",+ );++ // Create kbd element for the key symbol+ const kbd = document.createElement("kbd");+ kbd.className =+ "ml-1 rounded-md bg-muted/40 px-2 text-[0.75rem] font-prose center border border-foreground/20 text-muted-foreground inline whitespace-nowrap";+ kbd.textContent = isPlatformMac() ? "⌘" : "Ctrl";++ // Add the instruction text+ instructionDiv.append(document.createTextNode("Jump to defining cell "));+ instructionDiv.append(kbd);+ instructionDiv.append(document.createTextNode(" + Click"));++ container.append(instructionDiv);+ }+return container;}@@ -79,12 +111,14 @@ export const Autocompleter = {limitToType,excludeTypes,exactName,+ showGoToDefinitionHint = false,}: {position: number;message: CompletionResultMessage;limitToType?: "tooltip";excludeTypes?: string[];exactName?: string;+ showGoToDefinitionHint?: boolean;}): (Tooltip & { html?: string | null }) | undefined {const firstOption = getFirstOption(message.options, exactName);if (!firstOption) {@@ -92,7 +126,10 @@ export const Autocompleter = {}const from = position - message.prefix_length;- const dom = constructCompletionInfoNode(firstOption.completion_info);+ const dom = constructCompletionInfoNode(+ firstOption.completion_info,+ showGoToDefinitionHint,+ );if (!dom) {return;}diff --git a/frontend/src/core/codemirror/completion/hints.ts b/frontend/src/core/codemirror/completion/hints.tsindex 3878098e8e..2a779a72b7 100644--- a/frontend/src/core/codemirror/completion/hints.ts+++ b/frontend/src/core/codemirror/completion/hints.ts@@ -10,6 +10,7 @@ import type { LSPConfig } from "@/core/config/config-schema";import { documentationAtom } from "@/core/documentation/state";import { store } from "@/core/state/jotai";import { Logger } from "@/utils/Logger";+import { reactiveReferencesField } from "../reactive-references/extension";import { AUTOCOMPLETER, Autocompleter } from "./Autocompleter";export function hintTooltip(lspConfig: LSPConfig) {@@ -46,6 +47,12 @@ async function requestDocumentation(const { startToken, endToken } = getPositionAtWordBounds(view.state.doc, pos);+ // Check if this position is on a reactive variable+ const isReactiveVariable =+ view.state+ .field(reactiveReferencesField, false)+ ?.ranges.some((range) => pos >= range.from && pos <= range.to) ?? false;+const result = await AUTOCOMPLETER.request({document: view.state.doc.slice(0, endToken).toString(), // convert Text to stringcellId: cellId,@@ -60,6 +67,7 @@ async function requestDocumentation(message: result,exactName: fullWord,excludeTypes: excludeTypes,+ showGoToDefinitionHint: isReactiveVariable,});return tooltip ?? null;}diff --git a/frontend/src/core/codemirror/go-to-definition/commands.ts b/frontend/src/core/codemirror/go-to-definition/commands.tsindex 878ede847d..dd4eff74a8 100644--- a/frontend/src/core/codemirror/go-to-definition/commands.ts+++ b/frontend/src/core/codemirror/go-to-definition/commands.ts@@ -44,6 +44,14 @@ export function goToVariableDefinition(return false;} // Stop traversal if found+ // Skip function/lambda bodies entirely+ if (+ node.name === "LambdaExpression" ||+ node.name === "FunctionDefinition"+ ) {+ return false;+ }+// Check if the node is an identifier and matches the variable nameif (node.name === "VariableName" &&diff --git a/frontend/src/core/codemirror/go-to-definition/underline.ts b/frontend/src/core/codemirror/go-to-definition/underline.tsindex 73d348d4cc..bc7cfd9b35 100644--- a/frontend/src/core/codemirror/go-to-definition/underline.ts+++ b/frontend/src/core/codemirror/go-to-definition/underline.ts@@ -10,12 +10,17 @@ import {type ViewUpdate,} from "@codemirror/view";import type { TreeCursor } from "@lezer/common";+import {+ reactiveHoverDecoration,+ reactiveReferencesField,+} from "../reactive-references/extension";-// Decoration+// Decorationsconst underlineDecoration = Decoration.mark({ class: "underline" });// State Effectsconst addUnderline = StateEffect.define<{ from: number; to: number }>();+const addReactiveHover = StateEffect.define<{ from: number; to: number }>();const removeUnderlines = StateEffect.define();// Underline Field@@ -30,6 +35,12 @@ export const underlineField = StateField.define<DecorationSet>({newUnderlines = underlines.update({add: [underlineDecoration.range(effect.value.from, effect.value.to)],});+ } else if (effect.is(addReactiveHover)) {+ newUnderlines = underlines.update({+ add: [+ reactiveHoverDecoration.range(effect.value.from, effect.value.to),+ ],+ });} else if (effect.is(removeUnderlines)) {newUnderlines = Decoration.none;}@@ -61,7 +72,7 @@ class MetaUnderlineVariablePlugin {window.addEventListener("mouseleave", this.windowBlur);}- update(update: ViewUpdate) {+ update(_update: ViewUpdate) {// We cannot add any transactions here (e.g. clearing underlines),// otherwise CM fails with// "Calls to EditorView.update are not allowed while an update is in progress"@@ -129,6 +140,32 @@ class MetaUnderlineVariablePlugin {return;}+ // First, check if this position is a reactive variable (high-confidence navigable)+ // Use cached analysis from reactive variables StateField for fast lookup+ const reactiveState = this.view.state.field(reactiveReferencesField, false);+ const reactiveRange = reactiveState?.ranges.find(+ (range) => pos >= range.from && pos <= range.to,+ );++ if (reactiveRange) {+ // This is a reactive variable - add subtle hover enhancement+ const { from, to } = reactiveRange;+ if (+ this.hoveredRange &&+ this.hoveredRange.from === from &&+ this.hoveredRange.to === to+ ) {+ return;+ }+ // Clear existing decorations+ this.clearUnderline();+ // Add subtle hover enhancement for reactive variables+ this.hoveredRange = { from, to, position: pos };+ this.view.dispatch({ effects: addReactiveHover.of(this.hoveredRange) });+ return;+ }++ // Fallback: Use existing basic AST check for other variablesconst tree = syntaxTree(this.view.state);const cursor: TreeCursor = tree.cursorAt(pos);diff --git a/frontend/src/core/codemirror/reactive-references/__tests__/analyzer.test.ts b/frontend/src/core/codemirror/reactive-references/__tests__/analyzer.test.tsnew file mode 100644index 0000000000..f159785d05--- /dev/null+++ b/frontend/src/core/codemirror/reactive-references/__tests__/analyzer.test.ts@@ -0,0 +1,1067 @@+/* Copyright 2024 Marimo. All rights reserved. */++import { python } from "@codemirror/lang-python";+import { EditorState } from "@codemirror/state";+import { describe, expect, test } from "vitest";+import type { CellId } from "@/core/cells/ids";+import type { VariableName, Variables } from "@/core/variables/types";+import { findReactiveVariables, type ReactiveVariableRange } from "../analyzer";++describe("findReactiveVariables - Lexical Scoping", () => {+ test("should highlight global variable but not function parameter", () => {+ expect(+ runHighlight(+ ["a", "b"],+ `+def foo(a):+ return a + b+`,+ ),+ ).toMatchInlineSnapshot(`+ "+ def foo(a):+ return a + b+ ^+ "+ `);+ });++ test("should highlight both variables when no shadowing", () => {+ expect(+ runHighlight(+ ["a", "b"],+ `+def foo(x):+ return a + b+`,+ ),+ ).toMatchInlineSnapshot(`+ "+ def foo(x):+ return a + b+ ^ ^+ "+ `);+ });++ test("should handle lambda parameters", () => {+ expect(+ runHighlight(["a", "b"], "result = lambda a: a + b"),+ ).toMatchInlineSnapshot(`+ "+ result = lambda a: a + b+ ^+ "+ `);+ });++ test("should handle comprehension variables", () => {+ expect(+ runHighlight(["a", "data"], "result = [a for a in data]"),+ ).toMatchInlineSnapshot(`+ "+ result = [a for a in data]+ ^^^^+ "+ `);+ });++ test("should handle nested scopes", () => {+ expect(+ runHighlight(+ ["a", "b", "c"],+ `+def outer(a):+ def inner(b):+ return a + b + c+ return inner+`,+ ),+ ).toMatchInlineSnapshot(`+ "+ def outer(a):+ def inner(b):+ return a + b + c+ ^+ return inner+ "+ `);+ });++ test("should return no highlight for syntax errors", () => {+ expect(+ runHighlight(+ ["a", "b"],+ `+def foo(a:+ return a + b+`,+ ),+ ).toMatchInlineSnapshot(`+ "+ def foo(a:+ return a + b+ "+ `);+ });++ test("should handle multiple parameters", () => {+ expect(+ runHighlight(+ ["a", "b", "c", "d"],+ `+def foo(a, b, c):+ return a + b + c + d+`,+ ),+ ).toMatchInlineSnapshot(`+ "+ def foo(a, b, c):+ return a + b + c + d+ ^+ "+ `);+ });++ test("should handle recursive function", () => {+ expect(+ runHighlight(+ ["n", "base"],+ `+def factorial(n):+ if n <= 1:+ return base+ return n * factorial(n - 1)+`,+ ),+ ).toMatchInlineSnapshot(`+ "+ def factorial(n):+ if n <= 1:+ return base+ ^^^^+ return n * factorial(n - 1)+ "+ `);+ });++ test("function param vs global", () => {+ expect(+ runHighlight(["a", "b"], "def foo(a): return a + b"),+ ).toMatchInlineSnapshot(`+ "+ def foo(a): return a + b+ ^+ "+ `);+ });++ test("lambda param vs global", () => {+ expect(+ runHighlight(["x", "b"], "func = lambda x: x + b"),+ ).toMatchInlineSnapshot(`+ "+ func = lambda x: x + b+ ^+ "+ `);+ });++ test("lambda with multiple params", () => {+ expect(+ runHighlight(["x", "y", "z"], "f = lambda x, y: x + y + z"),+ ).toMatchInlineSnapshot(`+ "+ f = lambda x, y: x + y + z+ ^+ "+ `);+ });++ test("comprehension shadows global", () => {+ expect(runHighlight(["a"], "[a for a in range(5)]")).toMatchInlineSnapshot(`+ "+ [a for a in range(5)]+ "+ `);+ });++ test("nested comprehension", () => {+ expect(+ runHighlight(["a", "b"], "[(a + b) for a, b in [(1,2), (3,4)]]"),+ ).toMatchInlineSnapshot(`+ "+ [(a + b) for a, b in [(1,2), (3,4)]]+ "+ `);+ });++ test("dict comprehension using global", () => {+ expect(+ runHighlight(+ ["k", "v", "offset"],+ `{k: v + offset for k, v in [("a", 1), ("b", 2)]}`,+ ),+ ).toMatchInlineSnapshot(`+ "+ {k: v + offset for k, v in [("a", 1), ("b", 2)]}+ ^^^^^^+ "+ `);+ });++ test("generator expression", () => {+ expect(+ runHighlight(+ ["x", "threshold", "global_list"],+ "(x + threshold for x in global_list)",+ ),+ ).toMatchInlineSnapshot(`+ "+ (x + threshold for x in global_list)+ ^^^^^^^^^ ^^^^^^^^^^^+ "+ `);+ });++ test("class body using globals", () => {+ expect(+ runHighlight(["a", "b"], "class MyClass:\n value = a + b"),+ ).toMatchInlineSnapshot(`+ "+ class MyClass:+ value = a + b+ ^ ^+ "+ `);+ });++ test("decorator using global", () => {+ expect(+ runHighlight(["logger"], "@logger\ndef decorated(): pass"),+ ).toMatchInlineSnapshot(`+ "+ @logger+ ^^^^^^+ def decorated(): pass+ "+ `);+ });++ test("try/except block using global", () => {+ expect(+ runHighlight(+ ["e", "logger"],+ `try:\n 1 / 0\nexcept Exception as e:\n print("Error", logger)`,+ ),+ ).toMatchInlineSnapshot(`+ "+ try:+ 1 / 0+ except Exception as e:+ print("Error", logger)+ ^^^^^^+ "+ `);+ });++ test("with statement using global", () => {+ expect(+ runHighlight(["path", "f"], "with open(path) as f:\n print(f.read())"),+ ).toMatchInlineSnapshot(`+ "+ with open(path) as f:+ ^^^^+ print(f.read())+ "+ `);+ });++ test("function reusing global name as param", () => {+ expect(+ runHighlight(["logger"], "def shadow_logger(logger): return logger + 1"),+ ).toMatchInlineSnapshot(`+ "+ def shadow_logger(logger): return logger + 1+ "+ `);+ });++ test("shadowed global in inner function", () => {+ expect(+ runHighlight(+ ["a", "b", "x", "z"],+ `+def outer():+ z = 10+ x = 20+ def inner():+ a = 2+ return a + b + z # highlight: b+ return inner()+ `,+ ),+ ).toMatchInlineSnapshot(`+ "+ def outer():+ z = 10+ x = 20+ def inner():+ a = 2+ return a + b + z # highlight: b+ ^+ return inner()++ "+ `);+ });++ test("multiple assignment", () => {+ expect(+ runHighlight(["x", "y", "z", "a"], "x = y = z + a"),+ ).toMatchInlineSnapshot(`+ "+ x = y = z + a+ ^ ^+ "+ `);+ });++ test("nested lambdas", () => {+ expect(+ runHighlight(+ ["x", "y", "b"],+ "nested_lambda = lambda x: (lambda y: x + y + b)",+ ),+ ).toMatchInlineSnapshot(`+ "+ nested_lambda = lambda x: (lambda y: x + y + b)+ ^+ "+ `);+ });++ test("function using builtin and global", () => {+ expect(+ runHighlight(["offset", "len"], "def use_len(x): return len(x) + offset"),+ ).toMatchInlineSnapshot(`+ "+ def use_len(x): return len(x) + offset+ ^^^ ^^^^^^+ "+ `);+ });++ test("global in return", () => {+ expect(+ runHighlight(["config"], "def get_config(): return config"),+ ).toMatchInlineSnapshot(`+ "+ def get_config(): return config+ ^^^^^^+ "+ `);+ });++ test("shadowed global in inner function 2", () => {+ expect(+ runHighlight(+ ["a", "b", "x", "z"],+ `+def outer2():+ z = 10+ x = 20+ def inner():+ a = 2+ return a + b + z # b should be highlighted+ return inner()+`,+ ),+ ).toMatchInlineSnapshot(`+ "+ def outer2():+ z = 10+ x = 20+ def inner():+ a = 2+ return a + b + z # b should be highlighted+ ^+ return inner()+ "+ `);+ });++ test("global used inside class", () => {+ expect(+ runHighlight(+ ["config"],+ `+class Configurable:+ value = config+`,+ ),+ ).toMatchInlineSnapshot(`+ "+ class Configurable:+ value = config+ ^^^^^^+ "+ `);+ });++ test("comprehension shadows global 2", () => {+ expect(+ runHighlight(["i"], "squares = [i**2 for i in range(10)]"),+ ).toMatchInlineSnapshot(`+ "+ squares = [i**2 for i in range(10)]+ "+ `);+ });++ test("comprehension with global in condition", () => {+ expect(+ runHighlight(["x", "z"], "filtered = [x for x in [] if x > z]"),+ ).toMatchInlineSnapshot(`+ "+ filtered = [x for x in [] if x > z]+ ^+ "+ `);+ });++ test("dict comprehension with local destructuring", () => {+ expect(+ runHighlight(["k", "v"], `kv_map = {k: v for (k, v) in [("a", "b")]}`),+ ).toMatchInlineSnapshot(`+ "+ kv_map = {k: v for (k, v) in [("a", "b")]}+ "+ `);+ });++ test("lambda inside function accessing global", () => {+ expect(+ runHighlight(+ ["x", "g"],+ `+def make_adder(x):+ return lambda y: x + y + g+`,+ ),+ ).toMatchInlineSnapshot(`+ "+ def make_adder(x):+ return lambda y: x + y + g+ ^+ "+ `);+ });++ test("rebinding in list comprehension", () => {+ expect(+ runHighlight(["x"], "rebinding = [x for x in range(5)]"),+ ).toMatchInlineSnapshot(`+ "+ rebinding = [x for x in range(5)]+ "+ `);+ });++ test("global used inside nested def in comprehension", () => {+ expect(+ runHighlight(+ ["x", "z"],+ "nested_comp = [lambda: x + z for x in range(5)]",+ ),+ ).toMatchInlineSnapshot(`+ "+ nested_comp = [lambda: x + z for x in range(5)]+ ^+ "+ `);+ });++ test("async function using global", () => {+ expect(+ runHighlight(+ ["client", "x"],+ `+async def fetch():+ return await client.get(x)+`,+ ),+ ).toMatchInlineSnapshot(`+ "+ async def fetch():+ return await client.get(x)+ ^^^^^^ ^+ "+ `);+ });++ test("class method using global", () => {+ expect(+ runHighlight(+ ["x"],+ `+class Thing:+ def compute(self):+ return self.factor * x+`,+ ),+ ).toMatchInlineSnapshot(`+ "+ class Thing:+ def compute(self):+ return self.factor * x+ ^+ "+ `);+ });++ test("function with multiple local scopes", () => {+ expect(+ runHighlight(+ ["external", "y", "x"],+ `+def complex(x):+ if x > 0:+ y = x * 2+ else:+ y = external+ return y+`,+ ),+ ).toMatchInlineSnapshot(`+ "+ def complex(x):+ if x > 0:+ y = x * 2+ else:+ y = external+ ^^^^^^^^+ return y+ "+ `);+ });++ test("nested import with alias", () => {+ expect(+ runHighlight(+ ["mo", "x", "polars"],+ `+def nested_import():+ import marimo as mo+ import polars+ print(mo, x, polars)`,+ ),+ ).toMatchInlineSnapshot(`+ "+ def nested_import():+ import marimo as mo+ import polars+ print(mo, x, polars)+ ^+ "+ `);+ });++ test("from-import with shadowing", () => {+ expect(+ runHighlight(+ ["my_sin", "x", "my_func"],+ `+def inner():+ from math import sin as my_sin+ return my_sin(x) + my_func(x)`,+ ),+ ).toMatchInlineSnapshot(`+ "+ def inner():+ from math import sin as my_sin+ return my_sin(x) + my_func(x)+ ^ ^^^^^^^ ^+ "+ `);+ });++ test("shadowed global via assignment", () => {+ expect(+ runHighlight(+ ["polars", "x"],+ `+def myfunc():+ polars = "not a module"+ return x + polars`,+ ),+ ).toMatchInlineSnapshot(`+ "+ def myfunc():+ polars = "not a module"+ return x + polars+ ^+ "+ `);+ });++ test("multiple imports and local names", () => {+ expect(+ runHighlight(+ ["np", "pd", "x", "y"],+ `+def analyze():+ import numpy as np+ import pandas as pd+ result = x + y + np.array([1, 2])`,+ ),+ ).toMatchInlineSnapshot(`+ "+ def analyze():+ import numpy as np+ import pandas as pd+ result = x + y + np.array([1, 2])+ ^ ^+ "+ `);+ });++ test("import shadowed by parameter", () => {+ expect(+ runHighlight(+ ["polars", "x"],+ `+def run(polars):+ return polars + x`,+ ),+ ).toMatchInlineSnapshot(`+ "+ def run(polars):+ return polars + x+ ^+ "+ `);+ });++ test("mixed comprehension and outer globals", () => {+ expect(+ runHighlight(["y", "z"], "values = [y + z for y in range(5)]"),+ ).toMatchInlineSnapshot(`+ "+ values = [y + z for y in range(5)]+ ^+ "+ `);+ });++ test("lambda inside function with outer global", () => {+ expect(+ runHighlight(+ ["x", "a", "offset"],+ `+def wrapper():+ return lambda x: x + a + offset`,+ ),+ ).toMatchInlineSnapshot(`+ "+ def wrapper():+ return lambda x: x + a + offset+ ^ ^^^^^^+ "+ `);+ });++ test("with statement inside function with global", () => {+ expect(+ runHighlight(+ ["path", "a"],+ `+def func():+ with open(path) as a:+ print(a.read())`,+ ),+ ).toMatchInlineSnapshot(`+ "+ def func():+ with open(path) as a:+ ^^^^+ print(a.read())+ "+ `);+ });++ test("redeclaration at top-level", () => {+ // These variables are redeclared locally, so they should not be highlighted+ // even though marimo may reject the redeclaration at runtime.+ expect(+ runHighlight(+ ["a", "b", "f", "i", "y"],+ `+a = 10+b = 20++with open("/test.txt") as f:+ print(f.read())++for i in range(10):+ print(i)++print(y)`,+ ),+ ).toMatchInlineSnapshot(`+ "+ a = 10+ b = 20++ with open("/test.txt") as f:+ print(f.read())++ for i in range(10):+ print(i)++ print(y)+ ^+ "+ `);+ });++ test("shadowed global method in inner function", () => {+ // These variables are redeclared locally, so they should not be highlighted+ // even though marimo may reject the redeclaration at runtime.+ expect(+ runHighlight(+ ["z", "x", "a", "b", "inner"],+ `+def outer2():+ z = 10+ x = 20++ def inner():+ a = 2+ return a + b + z # b should be highlighted++ return inner()+`,+ ),+ ).toMatchInlineSnapshot(`+ "+ def outer2():+ z = 10+ x = 20++ def inner():+ a = 2+ return a + b + z # b should be highlighted+ ^++ return inner()+ "+ `);+ });++ // Pathological test cases for edge cases+ test("global statement overrides local scoping", () => {+ expect(+ runHighlight(+ ["x", "y"],+ `+def outer():+ x = 1+ def inner():+ global x # This refers to global x, not outer's x+ return x + y+ return inner()+`,+ ),+ ).toMatchInlineSnapshot(`+ "+ def outer():+ x = 1+ def inner():+ global x # This refers to global x, not outer's x+ return x + y+ ^+ return inner()+ "+ `);+ });++ test("nonlocal statement accesses enclosing scope", () => {+ expect(+ runHighlight(+ ["z", "global_var"],+ `+def outer():+ z = 10+ def inner():+ nonlocal z # This refers to outer's z, not global z+ return z + global_var+ return inner()+`,+ ),+ ).toMatchInlineSnapshot(`+ "+ def outer():+ z = 10+ def inner():+ nonlocal z # This refers to outer's z, not global z+ return z + global_var+ ^^^^^^^^^^+ return inner()+ "+ `);+ });++ test("star unpacking in assignment", () => {+ expect(+ runHighlight(+ ["values", "a", "b", "c"],+ `+def func():+ a, *b, c = values+ return a + len(b) + c+`,+ ),+ ).toMatchInlineSnapshot(`+ "+ def func():+ a, *b, c = values+ ^^^^^^+ return a + len(b) + c+ "+ `);+ });++ test("nested tuple unpacking", () => {+ expect(+ runHighlight(+ ["nested_data", "x", "y", "z"],+ `+def func():+ (x, (y, z)) = nested_data+ return x + y + z+`,+ ),+ ).toMatchInlineSnapshot(`+ "+ def func():+ (x, (y, z)) = nested_data+ ^^^^^^^^^^^+ return x + y + z+ "+ `);+ });++ test("walrus operator in comprehension", () => {+ expect(+ runHighlight(+ ["data", "threshold", "process"],+ `+result = [y for x in data if (y := process(x)) > threshold]+`,+ ),+ ).toMatchInlineSnapshot(`+ "+ result = [y for x in data if (y := process(x)) > threshold]+ ^^^^ ^^^^^^^ ^^^^^^^^^+ "+ `);+ });++ test("exception variable scoping", () => {+ expect(+ runHighlight(+ ["e", "logger", "risky_operation"],+ `+def func():+ try:+ risky_operation()+ except Exception as e: # e is local to except block+ return str(e) + logger+`,+ ),+ ).toMatchInlineSnapshot(`+ "+ def func():+ try:+ risky_operation()+ ^^^^^^^^^^^^^^^+ except Exception as e: # e is local to except block+ return str(e) + logger+ ^^^^^^+ "+ `);+ });++ test("star import potential shadowing", () => {+ expect(+ runHighlight(+ ["x", "y", "unknown_func"],+ `+def func():+ from math import * # Could import anything, including x+ return x + y + unknown_func()+`,+ ),+ ).toMatchInlineSnapshot(`+ "+ def func():+ from math import * # Could import anything, including x+ return x + y + unknown_func()+ ^ ^ ^^^^^^^^^^^^+ "+ `);+ });++ test("class variable vs instance variable", () => {+ expect(+ runHighlight(+ ["class_global", "instance_global"],+ `+class MyClass:+ class_var = class_global # Should highlight class_global++ def __init__(self):+ self.instance_var = instance_global # Should highlight instance_global++ def method(self):+ return self.class_var + self.instance_var+`,+ ),+ ).toMatchInlineSnapshot(`+ "+ class MyClass:+ class_var = class_global # Should highlight class_global+ ^^^^^^^^^^^^++ def __init__(self):+ self.instance_var = instance_global # Should highlight instance_global+ ^^^^^^^^^^^^^^^++ def method(self):+ return self.class_var + self.instance_var+ "+ `);+ });++ test("nested class with outer scope access", () => {+ expect(+ runHighlight(+ ["outer_var", "global_var"],+ `+def outer_func():+ outer_var = 1++ class InnerClass:+ # Classes can't access enclosing function scope directly+ value = global_var # Should highlight global_var, not outer_var+ value2 = outer_var++ def method(self):+ return self.value + global_var++ return InnerClass()+`,+ ),+ ).toMatchInlineSnapshot(`+ "+ def outer_func():+ outer_var = 1++ class InnerClass:+ # Classes can't access enclosing function scope directly+ value = global_var # Should highlight global_var, not outer_var+ ^^^^^^^^^^+ value2 = outer_var++ def method(self):+ return self.value + global_var+ ^^^^^^^^^^++ return InnerClass()+ "+ `);+ });+});++/**+ * Convenient helper for testing reactive variable highlighting+ */+function runHighlight(variableNames: string[], code: string): string {+ const variables: Variables = {};+ for (const name of variableNames) {+ variables[name as VariableName] = {+ name: name as VariableName,+ declaredBy: ["other-cell" as CellId],+ usedBy: [],+ value: "test-value",+ dataType: "str",+ };+ }+ const ranges = findReactiveVariables({+ cellId: "current-cell" as CellId,+ state: EditorState.create({+ doc: code,+ extensions: [python()],+ }),+ variables,+ });+ return formatCodeWithHighlights(code, ranges);+}++/**+ * Helper function to format code with highlighted ranges for snapshot testing+ * Simple format with carets pointing to reactive variables+ */+function formatCodeWithHighlights(+ code: string,+ ranges: ReactiveVariableRange[],+): string {+ const lines = code.split("\n");+ const result: string[] = [];++ for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {+ const line = lines[lineIndex];++ // Start position of this line in the original code+ const lineStart =+ lines.slice(0, lineIndex).join("\n").length + (lineIndex > 0 ? 1 : 0);+ const lineEnd = lineStart + line.length;++ // Intersecting ranges+ const lineRanges = ranges.filter(+ (range) => range.from < lineEnd && range.to > lineStart,+ );++ result.push(line);++ if (lineRanges.length > 0) {+ // Create underline+ const underline = Array.from({ length: line.length }).fill(" ");++ for (const range of lineRanges) {+ const startInLine = Math.max(0, range.from - lineStart);+ const endInLine = Math.min(line.length, range.to - lineStart);++ for (let i = startInLine; i < endInLine; i++) {+ underline[i] = "^";+ }+ }++ // Add the underline if it has any markers+ if (underline.includes("^")) {+ result.push(underline.join("").trimEnd());+ }+ }+ }++ // Ensure result starts and ends with empty lines for nicer snapshot view+ const out = [...result];+ if (out[0] !== "") {+ out.unshift("");+ }+ if (out[out.length - 1] !== "") {+ out.push("");+ }+ return out.join("\n");+}diff --git a/frontend/src/core/codemirror/reactive-references/analyzer.ts b/frontend/src/core/codemirror/reactive-references/analyzer.tsnew file mode 100644index 0000000000..81168b9923--- /dev/null+++ b/frontend/src/core/codemirror/reactive-references/analyzer.ts@@ -0,0 +1,498 @@+/* Copyright 2024 Marimo. All rights reserved. */++import { syntaxTree } from "@codemirror/language";+import type { EditorState } from "@codemirror/state";+import type { SyntaxNode, Tree, TreeCursor } from "@lezer/common";+import type { CellId } from "@/core/cells/ids";+import type { VariableName, Variables } from "@/core/variables/types";++export interface ReactiveVariableRange {+ from: number;+ to: number;+ variableName: string;+}++/**+ * Analyzes the given editor state to find variable names that represent+ * reactive dependencies from other cells (similar to ObservableHQ's approach).+ */+export function findReactiveVariables(options: {+ state: EditorState;+ cellId: CellId;+ variables: Variables;+}): ReactiveVariableRange[] {+ const tree = syntaxTree(options.state);++ if (!tree) {+ // No AST available yet - this can happen during initial editor setup+ // or when the language parser hasn't processed the code+ return [];+ }++ if (hasSyntaxErrors(tree)) {+ return [];+ }++ // Collect variable names that are:+ // - Not from in the current cell+ // - Not from a "setup" cell+ // - Not of type "module"+ const allVariableNames = new Set(+ Object.keys(options.variables).filter((name) => {+ const variable = options.variables[name as VariableName];+ return (+ variable.dataType !== "module" &&+ !variable.declaredBy.includes("setup" as CellId) &&+ !variable.declaredBy.includes(options.cellId)+ );+ }),+ );++ if (allVariableNames.size === 0) {+ return [];+ }++ const ranges: ReactiveVariableRange[] = [];++ // Map from node position to declared variables in that scope+ const allDeclarations = new Map<number, Set<string>>();+ // Map from node position to scope type+ const scopeTypes = new Map<number, string>();++ // First pass: all variable declarations in their respective scopes+ function collectDeclarations(node: SyntaxNode | Tree, scopeStack: number[]) {+ const cursor = node.cursor();+ const nodeName = cursor.name;+ const nodeStart = cursor.from;++ const isNewScope = [+ "FunctionDefinition",+ "LambdaExpression",+ "ArrayComprehensionExpression",+ "SetComprehension",+ "DictionaryComprehensionExpression",+ "ComprehensionExpression",+ "ClassDefinition",+ ].includes(nodeName);++ let currentScopeStack = scopeStack;+ if (isNewScope) {+ currentScopeStack = [...scopeStack, nodeStart];+ allDeclarations.set(nodeStart, new Set());+ scopeTypes.set(nodeStart, nodeName);+ }++ switch (nodeName) {+ case "FunctionDefinition": {+ const subCursor = node.cursor();+ subCursor.firstChild();+ do {+ if (subCursor.name === "VariableName") {+ const functionName = options.state.doc.sliceString(+ subCursor.from,+ subCursor.to,+ );+ // Add function name to the parent scope (not the function's own scope)+ const parentScope = scopeStack[scopeStack.length - 1] ?? -1;+ if (!allDeclarations.has(parentScope)) {+ allDeclarations.set(parentScope, new Set());+ }+ allDeclarations.get(parentScope)?.add(functionName);+ break; // Function name is the first VariableName, so we can break here+ }+ } while (subCursor.nextSibling());++ // Function params+ const paramCursor = node.cursor();+ paramCursor.firstChild();+ do {+ if (paramCursor.name === "ParamList") {+ const paramListCursor = paramCursor.node.cursor();+ paramListCursor.firstChild();+ do {+ if (paramListCursor.name === "VariableName") {+ const paramName = options.state.doc.sliceString(+ paramListCursor.from,+ paramListCursor.to,+ );+ allDeclarations.get(nodeStart)?.add(paramName);+ }+ } while (paramListCursor.nextSibling());+ }+ } while (paramCursor.nextSibling());++ break;+ }+ case "LambdaExpression": {+ // Lambda params+ const subCursor = node.cursor();+ subCursor.firstChild();+ do {+ if (subCursor.name === "ParamList") {+ const paramCursor = subCursor.node.cursor();+ paramCursor.firstChild();+ do {+ if (paramCursor.name === "VariableName") {+ const paramName = options.state.doc.sliceString(+ paramCursor.from,+ paramCursor.to,+ );+ allDeclarations.get(nodeStart)?.add(paramName);+ }+ } while (paramCursor.nextSibling());+ }+ } while (subCursor.nextSibling());++ break;+ }+ case "ArrayComprehensionExpression":+ case "DictionaryComprehensionExpression":+ case "SetComprehension":+ case "ComprehensionExpression": {+ // Domprehension variables - look for VariableName or TupleExpression after 'for'+ const subCursor = node.cursor();+ subCursor.firstChild();+ let foundFor = false;+ do {+ if (subCursor.name === "for") {+ foundFor = true;+ } else if (foundFor && subCursor.name === "VariableName") {+ const varName = options.state.doc.sliceString(+ subCursor.from,+ subCursor.to,+ );+ allDeclarations.get(nodeStart)?.add(varName);+ } else if (foundFor && subCursor.name === "TupleExpression") {+ // Handle tuple destructuring like (k, v)+ const tupleCursor = subCursor.node.cursor();+ tupleCursor.firstChild();+ do {+ if (tupleCursor.name === "VariableName") {+ const varName = options.state.doc.sliceString(+ tupleCursor.from,+ tupleCursor.to,+ );+ allDeclarations.get(nodeStart)?.add(varName);+ }+ } while (tupleCursor.nextSibling());+ } else if (foundFor && subCursor.name === "in") {+ foundFor = false; // Stop collecting variables after 'in'+ }+ } while (subCursor.nextSibling());++ break;+ }+ case "ClassDefinition": {+ const subCursor = node.cursor();+ subCursor.firstChild();+ do {+ if (subCursor.name === "VariableName") {+ const className = options.state.doc.sliceString(+ subCursor.from,+ subCursor.to,+ );+ // Add class name to the parent scope (not the class's own scope)+ const parentScope = scopeStack[scopeStack.length - 1] ?? -1;+ if (!allDeclarations.has(parentScope)) {+ allDeclarations.set(parentScope, new Set());+ }+ allDeclarations.get(parentScope)?.add(className);+ break; // Class name is the first VariableName, so we can break here+ }+ } while (subCursor.nextSibling());++ break;+ }+ case "AssignStatement": {+ // Assignments - capture all variables being assigned to (variables that come before the last AssignOp)+ const subCursor = node.cursor();++ // First pass: all AssignOp positions to know where assignment targets end+ const assignOpPositions: number[] = [];+ subCursor.firstChild();+ do {+ if (subCursor.name === "AssignOp") {+ assignOpPositions.push(subCursor.from);+ }+ } while (subCursor.nextSibling());++ // Second pass: all VariableNames and TupleExpressions that come before the last AssignOp+ const lastAssignOpPosition =+ assignOpPositions[assignOpPositions.length - 1];++ const secondPassCursor = node.cursor();+ secondPassCursor.firstChild();+ const currentScope =+ currentScopeStack[currentScopeStack.length - 1] ?? -1;++ do {+ if (secondPassCursor.from < lastAssignOpPosition) {+ extractAssignmentTargets(secondPassCursor, {+ currentScope,+ state: options.state,+ allDeclarations,+ scopeTypes,+ });+ }+ } while (secondPassCursor.nextSibling());++ break;+ }+ case "ForStatement": {+ // For loop variables+ const subCursor = node.cursor();+ subCursor.firstChild();+ let foundFor = false;+ do {+ if (subCursor.name === "for") {+ foundFor = true;+ } else if (foundFor && subCursor.name === "VariableName") {+ const varName = options.state.doc.sliceString(+ subCursor.from,+ subCursor.to,+ );+ // Add to the current innermost scope (or global if no scopes)+ const currentScope =+ currentScopeStack[currentScopeStack.length - 1] ?? -1;+ if (!allDeclarations.has(currentScope)) {+ allDeclarations.set(currentScope, new Set());+ }+ allDeclarations.get(currentScope)?.add(varName);+ } else if (foundFor && subCursor.name === "in") {+ foundFor = false; // Stop collecting variables after 'in'+ }+ } while (subCursor.nextSibling());++ break;+ }+ case "ImportStatement": {+ // Handle import x+ const subCursor = node.cursor();+ subCursor.firstChild();+ do {+ if (subCursor.name === "VariableName") {+ const varName = options.state.doc.sliceString(+ subCursor.from,+ subCursor.to,+ );++ const currentScope =+ currentScopeStack[currentScopeStack.length - 1] ?? -1;+ if (!allDeclarations.has(currentScope)) {+ allDeclarations.set(currentScope, new Set());+ }+ allDeclarations.get(currentScope)?.add(varName);+ }+ } while (subCursor.nextSibling());++ break;+ }+ case "ImportFromStatement": {+ // Handle from x import y as z+ const subCursor = node.cursor();+ subCursor.firstChild();+ let foundImport = false;+ do {+ if (subCursor.name === "import") {+ foundImport = true;+ } else if (foundImport && subCursor.name === "VariableName") {+ const varName = options.state.doc.sliceString(+ subCursor.from,+ subCursor.to,+ );+ // Add to the current innermost scope+ const currentScope =+ currentScopeStack[currentScopeStack.length - 1] ?? -1;+ if (!allDeclarations.has(currentScope)) {+ allDeclarations.set(currentScope, new Set());+ }+ allDeclarations.get(currentScope)?.add(varName);+ }+ } while (subCursor.nextSibling());++ break;+ }+ case "TryStatement": {+ // Exception variable binding - look for 'as' followed by VariableName+ const subCursor = node.cursor();+ subCursor.firstChild();+ let foundAs = false;+ do {+ if (subCursor.name === "as") {+ foundAs = true;+ } else if (foundAs && subCursor.name === "VariableName") {+ const varName = options.state.doc.sliceString(+ subCursor.from,+ subCursor.to,+ );+ const currentScope =+ currentScopeStack[currentScopeStack.length - 1] ?? -1;+ if (!allDeclarations.has(currentScope)) {+ allDeclarations.set(currentScope, new Set());+ }+ allDeclarations.get(currentScope)?.add(varName);+ foundAs = false;+ }+ } while (subCursor.nextSibling());++ break;+ }+ case "WithStatement": {+ const subCursor = node.cursor();+ subCursor.firstChild();+ let foundAs = false;+ do {+ if (subCursor.name === "as") {+ foundAs = true;+ } else if (foundAs && subCursor.name === "VariableName") {+ const varName = options.state.doc.sliceString(+ subCursor.from,+ subCursor.to,+ );+ const currentScope =+ currentScopeStack[currentScopeStack.length - 1] ?? -1;+ if (!allDeclarations.has(currentScope)) {+ allDeclarations.set(currentScope, new Set());+ }+ allDeclarations.get(currentScope)?.add(varName);+ foundAs = false;+ }+ } while (subCursor.nextSibling());++ break;+ }+ // No default+ }++ if (cursor.firstChild()) {+ do {+ collectDeclarations(cursor.node, currentScopeStack);+ } while (cursor.nextSibling());+ }+ }++ // Second pass: find variable usages and check if they should be highlighted+ function findUsages(node: SyntaxNode | Tree, scopeStack: number[]) {+ const cursor = node.cursor();+ const nodeName = cursor.name;+ const nodeStart = cursor.from;++ const isNewScope = [+ "FunctionDefinition",+ "LambdaExpression",+ "ArrayComprehensionExpression",+ "SetComprehension",+ "DictionaryComprehensionExpression",+ "ComprehensionExpression",+ "ClassDefinition",+ ].includes(nodeName);++ let currentScopeStack = scopeStack;+ if (isNewScope) {+ currentScopeStack = [...scopeStack, nodeStart];+ }++ if (nodeName === "VariableName") {+ const varName = options.state.doc.sliceString(cursor.from, cursor.to);++ if (allVariableNames.has(varName)) {+ let isDeclaredLocally = false;+ for (const scope of currentScopeStack) {+ if (allDeclarations.get(scope)?.has(varName)) {+ isDeclaredLocally = true;+ break;+ }+ }+ if (allDeclarations.get(-1)?.has(varName)) {+ isDeclaredLocally = true;+ }++ if (!isDeclaredLocally) {+ ranges.push({+ from: cursor.from,+ to: cursor.to,+ variableName: varName,+ });+ }+ }+ }++ if (cursor.firstChild()) {+ do {+ findUsages(cursor.node, currentScopeStack);+ } while (cursor.nextSibling());+ }+ }++ collectDeclarations(tree, []);+ findUsages(tree, []);++ return ranges;+}++/**+ * Checks if the syntax tree contains any syntax errors.+ * If there are errors, we shouldn't show reactive variable highlighting.+ */+function hasSyntaxErrors(tree: Tree): boolean {+ const cursor = tree.cursor();+ do {+ // Lezer uses "⚠" as the error node name for syntax errors+ if (cursor.name === "⚠" || cursor.type.isError) {+ return true;+ }+ } while (cursor.next());+ return false;+}++/**+ * Helper function to extract variable names from assignment targets (including tuples)+ */+function extractAssignmentTargets(+ cursor: TreeCursor,+ options: {+ currentScope: number;+ state: EditorState;+ allDeclarations: Map<number, Set<string>>;+ scopeTypes: Map<number, string>;+ },+) {+ switch (cursor.name) {+ case "VariableName": {+ const varName = options.state.doc.sliceString(cursor.from, cursor.to);+ const isInClassScope =+ options.currentScope !== -1 &&+ options.scopeTypes.get(options.currentScope) === "ClassDefinition";++ if (!isInClassScope) {+ if (!options.allDeclarations.has(options.currentScope)) {+ options.allDeclarations.set(options.currentScope, new Set());+ }+ options.allDeclarations.get(options.currentScope)?.add(varName);+ }++ break;+ }+ case "TupleExpression": {+ // Handle tuple unpacking like (x, (y, z)) = ...+ const tupleCursor = cursor.node.cursor();+ tupleCursor.firstChild();+ do {+ extractAssignmentTargets(tupleCursor, options);+ } while (tupleCursor.nextSibling());++ break;+ }+ case "ArrayExpression": {+ // Handle list unpacking like [a, b, c] = ...+ const arrayCursor = cursor.node.cursor();+ arrayCursor.firstChild();+ do {+ extractAssignmentTargets(arrayCursor, options);+ } while (arrayCursor.nextSibling());++ break;+ }+ // No default+ }+}diff --git a/frontend/src/core/codemirror/reactive-references/extension.ts b/frontend/src/core/codemirror/reactive-references/extension.tsnew file mode 100644index 0000000000..ee0f22f702--- /dev/null+++ b/frontend/src/core/codemirror/reactive-references/extension.ts@@ -0,0 +1,154 @@+/* Copyright 2024 Marimo. All rights reserved. */++import { StateEffect, StateField } from "@codemirror/state";+import {+ Decoration,+ type DecorationSet,+ EditorView,+ ViewPlugin,+ type ViewUpdate,+} from "@codemirror/view";+import { type DebouncedFunc, debounce } from "lodash-es";++import type { CellId } from "@/core/cells/ids";+import { store } from "@/core/state/jotai";+import { variablesAtom } from "@/core/variables/state";+import { Logger } from "@/utils/Logger";++import { findReactiveVariables, type ReactiveVariableRange } from "./analyzer";++const reactiveVariableDecoration = Decoration.mark({+ class: "mo-cm-reactive-reference",+});++export const reactiveHoverDecoration = Decoration.mark({+ class: "mo-cm-reactive-reference-hover",+});++const updateReactiveVariables = StateEffect.define<ReactiveVariableRange[]>();++/**+ * Enhanced state that stores both visual decorations and analysis ranges+ * for efficient access by other extensions (e.g., goto definition)+ */+interface ReactiveReferencesState {+ decorations: DecorationSet;+ ranges: ReactiveVariableRange[];+}++/**+ * Plugin that manages highlighting marimo's reactive variables+ */+class ReactiveReferencesPlugin {+ private view: EditorView;+ private cellId: CellId;+ private variablesUnsubscribe: () => void;++ // Delay (in ms) before highlighting reactive variables after user changes or store updates+ private readonly highlightDebounceMs = 300;++ // Debounced function to trigger highlighting+ private readonly scheduleHighlighting: DebouncedFunc<() => void>;++ constructor(view: EditorView, cellId: CellId) {+ this.view = view;+ this.cellId = cellId;++ this.scheduleHighlighting = debounce(() => {+ this.runHighlighting();+ }, this.highlightDebounceMs);++ // React to variable store changes+ this.variablesUnsubscribe = store.sub(variablesAtom, () => {+ this.scheduleHighlighting();+ });++ // Initial run+ this.scheduleHighlighting();+ }++ update(update: ViewUpdate) {+ if (update.docChanged || update.focusChanged) {+ this.scheduleHighlighting();+ }+ }++ destroy() {+ this.scheduleHighlighting.cancel();+ this.variablesUnsubscribe();+ }++ private runHighlighting() {+ const ranges = findReactiveVariables({+ state: this.view.state,+ cellId: this.cellId,+ variables: store.get(variablesAtom),+ });++ if (ranges.length > 0) {+ Logger.debug(+ `Found ${ranges.length} reactive variables in cell ${this.cellId}`,+ );+ }++ // Defer dispatch to avoid triggering during an editor update cycle+ queueMicrotask(() => {+ this.view.dispatch({+ effects: updateReactiveVariables.of(ranges),+ });+ });+ }+}++/**+ * Creates the reactive variables extension+ */+/**+ * StateField that stores both decorations and analysis ranges+ */+export const reactiveReferencesField =+ StateField.define<ReactiveReferencesState>({+ create() {+ return {+ decorations: Decoration.none,+ ranges: [],+ };+ },+ update(state, tr) {+ let newState = {+ decorations: state.decorations.map(tr.changes),+ ranges: state.ranges,+ };++ for (const effect of tr.effects) {+ if (effect.is(updateReactiveVariables)) {+ // Update both decorations and cached ranges+ newState = {+ decorations: Decoration.set(+ effect.value.map((range) =>+ reactiveVariableDecoration.range(range.from, range.to),+ ),+ ),+ ranges: effect.value,+ };+ }+ }+ return newState;+ },+ provide: (f) =>+ EditorView.decorations.from(f, (state) => state.decorations),+ });++function reactiveReferencesExtension(cellId: CellId) {+ return [+ reactiveReferencesField,+ ViewPlugin.define((view) => new ReactiveReferencesPlugin(view, cellId)),+ ];+}++/**+ * Bundle function to conditionally include reactive references highlighting+ */+export function reactiveReferencesBundle(cellId: CellId, enabled: boolean) {+ return enabled ? reactiveReferencesExtension(cellId) : [];+}diff --git a/frontend/src/core/codemirror/theme/dark.ts b/frontend/src/core/codemirror/theme/dark.tsindex 3a8fdce6c8..4ad4fc6f70 100644--- a/frontend/src/core/codemirror/theme/dark.ts+++ b/frontend/src/core/codemirror/theme/dark.ts@@ -1,35 +1,50 @@/* Copyright 2024 Marimo. All rights reserved. */+import { EditorView } from "@codemirror/view";import { tags as t } from "@lezer/highlight";import { createTheme } from "thememirror";-export const darkTheme = createTheme({- variant: "dark",- settings: {- background: "#282c34",- foreground: "#abb2bf",- caret: "#528bff",- selection: "#3E4451",- lineHighlight: "#2c313c",- gutterBackground: "var(--color-background)",- gutterForeground: "var(--gray-10)",- },- styles: [- { tag: t.comment, color: "#5c6370" },- { tag: t.variableName, color: "#abb2bf" },- { tag: [t.string, t.special(t.brace)], color: "#98c379" },- { tag: t.number, color: "#d19a66" },- { tag: t.bool, color: "#d19a66" },- { tag: t.null, color: "#d19a66" },- { tag: t.keyword, color: "#c678dd", fontWeight: 500 },- { tag: t.className, color: "#61afef" },- { tag: t.definition(t.typeName), color: "#61afef" },- { tag: t.typeName, color: "#56b6c2" },- { tag: t.angleBracket, color: "#abb2bf" },- { tag: t.tagName, color: "#e06c75" },- { tag: t.attributeName, color: "#d19a66" },- { tag: t.operator, color: "#56b6c2", fontWeight: 500 },- { tag: [t.function(t.variableName)], color: "#61afef" },- { tag: [t.propertyName], color: "#e5c07b" },- ],-});+export const darkTheme = [+ createTheme({+ variant: "dark",+ settings: {+ background: "#282c34",+ foreground: "#abb2bf",+ caret: "#528bff",+ selection: "#3E4451",+ lineHighlight: "#2c313c",+ gutterBackground: "var(--color-background)",+ gutterForeground: "var(--gray-10)",+ },+ styles: [+ { tag: t.comment, color: "#5c6370" },+ { tag: t.variableName, color: "#abb2bf" },+ { tag: [t.string, t.special(t.brace)], color: "#98c379" },+ { tag: t.number, color: "#d19a66" },+ { tag: t.bool, color: "#d19a66" },+ { tag: t.null, color: "#d19a66" },+ { tag: t.keyword, color: "#c678dd", fontWeight: 500 },+ { tag: t.className, color: "#61afef" },+ { tag: t.definition(t.typeName), color: "#61afef" },+ { tag: t.typeName, color: "#56b6c2" },+ { tag: t.angleBracket, color: "#abb2bf" },+ { tag: t.tagName, color: "#e06c75" },+ { tag: t.attributeName, color: "#d19a66" },+ { tag: t.operator, color: "#56b6c2", fontWeight: 500 },+ { tag: [t.function(t.variableName)], color: "#61afef" },+ { tag: [t.propertyName], color: "#e5c07b" },+ ],+ }),+ EditorView.theme({+ ".mo-cm-reactive-reference": {+ fontWeight: "400",+ color: "#2a7aa5",+ borderBottom: "2px solid #bad3de",+ },+ ".mo-cm-reactive-reference-hover": {+ cursor: "pointer",+ borderBottomWidth: "3px",+ borderBottomColor: "#4a90a5",+ },+ }),+];diff --git a/frontend/src/core/codemirror/theme/light.ts b/frontend/src/core/codemirror/theme/light.tsindex 740d8b881d..6ae0272436 100644--- a/frontend/src/core/codemirror/theme/light.ts+++ b/frontend/src/core/codemirror/theme/light.ts@@ -1,44 +1,58 @@/* Copyright 2024 Marimo. All rights reserved. */+import { EditorView } from "@codemirror/view";import { tags as t } from "@lezer/highlight";import { createTheme } from "thememirror";-export const lightTheme = createTheme({- variant: "light",- settings: {- background: "#ffffff",- foreground: "#000000",- caret: "#000000",- selection: "#d7d4f0",- lineHighlight: "#cceeff44",- gutterBackground: "var(--color-background)",- gutterForeground: "var(--gray-10)",- },- styles: [- // Default codemirror light theme- { tag: t.comment, color: "#708090" },- { tag: t.variableName, color: "#000000" },- { tag: [t.string, t.special(t.brace)], color: "#a11" },- { tag: t.number, color: "#164" },- { tag: t.bool, color: "#219" },- { tag: t.null, color: "#219" },- { tag: t.keyword, color: "#708", fontWeight: 500 },- // { tag: t.operator, color: '#000' },- { tag: t.className, color: "#00f" },- { tag: t.definition(t.typeName), color: "#00f" },- { tag: t.typeName, color: "#085" },- { tag: t.angleBracket, color: "#000000" },- { tag: t.tagName, color: "#170" },- { tag: t.attributeName, color: "#00c" },- // Adjustments- { tag: t.operator, color: "#a2f", fontWeight: 500 },- {- tag: [t.function(t.variableName)],- color: "#00c",+export const lightTheme = [+ createTheme({+ variant: "light",+ settings: {+ background: "#ffffff",+ foreground: "#000000",+ caret: "#000000",+ selection: "#d7d4f0",+ lineHighlight: "#cceeff44",+ gutterBackground: "var(--color-background)",+ gutterForeground: "var(--gray-10)",},- {- tag: [t.propertyName],- color: "#05a",+ styles: [+ // Default codemirror light theme+ { tag: t.comment, color: "#708090" },+ { tag: t.variableName, color: "#000000" },+ { tag: [t.string, t.special(t.brace)], color: "#a11" },+ { tag: t.number, color: "#164" },+ { tag: t.bool, color: "#219" },+ { tag: t.null, color: "#219" },+ { tag: t.keyword, color: "#708", fontWeight: 500 },+ // { tag: t.operator, color: '#000' },+ { tag: t.className, color: "#00f" },+ { tag: t.definition(t.typeName), color: "#00f" },+ { tag: t.typeName, color: "#085" },+ { tag: t.angleBracket, color: "#000000" },+ { tag: t.tagName, color: "#170" },+ { tag: t.attributeName, color: "#00c" },+ // Adjustments+ { tag: t.operator, color: "#a2f", fontWeight: 500 },+ {+ tag: [t.function(t.variableName)],+ color: "#00c",+ },+ {+ tag: [t.propertyName],+ color: "#05a",+ },+ ],+ }),+ EditorView.theme({+ ".mo-cm-reactive-reference": {+ fontWeight: "400",+ color: "#005f87",+ borderBottom: "2px solid #bad3de",},- ],-});+ ".mo-cm-reactive-reference-hover": {+ cursor: "pointer",+ borderBottomWidth: "3px",+ },+ }),+];diff --git a/frontend/src/core/config/__tests__/config-schema.test.ts b/frontend/src/core/config/__tests__/config-schema.test.tsindex 382b28e127..5afcf2f629 100644--- a/frontend/src/core/config/__tests__/config-schema.test.ts+++ b/frontend/src/core/config/__tests__/config-schema.test.ts@@ -57,6 +57,7 @@ test("default UserConfig - empty", () => {"dataframes": "rich","default_table_page_size": 10,"default_width": "medium",+ "reference_highlighting": false,"theme": "light",},"experimental": {},@@ -113,6 +114,7 @@ test("default UserConfig - one level", () => {"dataframes": "rich","default_table_page_size": 10,"default_width": "medium",+ "reference_highlighting": false,"theme": "light",},"experimental": {},diff --git a/frontend/src/core/config/config-schema.ts b/frontend/src/core/config/config-schema.tsindex 75d6fc7e8f..85668926c4 100644--- a/frontend/src/core/config/config-schema.ts+++ b/frontend/src/core/config/config-schema.ts@@ -111,6 +111,7 @@ export const UserConfigSchema = z}return width;}),+ reference_highlighting: z.boolean().default(false),}).passthrough().default({}),@@ -186,6 +187,7 @@ export type CompletionConfig = UserConfig["completion"];export type KeymapConfig = UserConfig["keymap"];export type LSPConfig = UserConfig["language_servers"];export type DiagnosticsConfig = UserConfig["diagnostics"];+export type DisplayConfig = UserConfig["display"];export const AppTitleSchema = z.string();export const SqlOutputSchema = z.enum(VALID_SQL_OUTPUT_FORMATS).default("auto");diff --git a/frontend/src/core/runtime/runtime.ts b/frontend/src/core/runtime/runtime.tsindex 644328c96e..715c0a2088 100644--- a/frontend/src/core/runtime/runtime.ts+++ b/frontend/src/core/runtime/runtime.ts@@ -41,7 +41,7 @@ export class RuntimeManager {formatHttpURL(path?: string,searchParams?: URLSearchParams,- restrictToKnownQueryParams: boolean = true,+ restrictToKnownQueryParams = true,): URL {if (!path) {path = "";diff --git a/marimo/_config/config.py b/marimo/_config/config.pyindex e03c226dd8..9d9584551e 100644--- a/marimo/_config/config.py+++ b/marimo/_config/config.py@@ -167,6 +167,7 @@ class DisplayConfig(TypedDict):- `dataframes`: `"rich"` or `"plain"`- `custom_css`: list of paths to custom CSS files- `default_table_page_size`: default number of rows to display in tables+ - `reference_highlighting`: if `True`, highlight reactive variable references"""theme: Theme@@ -176,6 +177,7 @@ class DisplayConfig(TypedDict):dataframes: Literal["rich", "plain"]custom_css: NotRequired[list[str]]default_table_page_size: int+ reference_highlighting: NotRequired[bool]@mddoc@@ -432,6 +434,7 @@ DEFAULT_CONFIG: MarimoConfig = {"default_width": "medium","dataframes": "rich","default_table_page_size": 10,+ "reference_highlighting": False,},"formatting": {"line_length": 79},"keymap": {"preset": "default", "overrides": {}},diff --git a/openapi/api.yaml b/openapi/api.yamlindex ac4cd5ef81..4d72cee2d9 100644--- a/openapi/api.yaml+++ b/openapi/api.yaml@@ -1567,6 +1567,8 @@ components:- full- columnstype: string+ reference_highlighting:+ type: booleantheme:enum:- light@@ -2692,7 +2694,7 @@ components:type: objectinfo:title: marimo API- version: 0.14.0+ version: 0.14.7openapi: 3.1.0paths:/@file/{filename_and_length}:diff --git a/openapi/src/api.ts b/openapi/src/api.tsindex f44f3b68c2..7a880d5597 100644--- a/openapi/src/api.ts+++ b/openapi/src/api.ts@@ -3191,6 +3191,7 @@ export interface components {default_table_page_size: number;/** @enum {string} */default_width: "normal" | "compact" | "medium" | "full" | "columns";+ reference_highlighting?: boolean;/** @enum {string} */theme: "light" | "dark" | "system";};