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: customize hotkeys (#1564)
Myles Scolnick663880b8499a
diff --git a/docs/guides/hotkeys.md b/docs/guides/hotkeys.mdnew file mode 100644index 0000000000..b120bad83f--- /dev/null+++ b/docs/guides/hotkeys.md@@ -0,0 +1,56 @@+# Hotkeys++If you'd like to override the default hotkeys, you can do so in the hotkeys menu (`Mod-Shift-h`), or modifying your `~/.marimo.toml`.++You can find a list of available hotkeys below:++| Hotkey |+|---------------------------|+| `cell.aiCompletion` |+| `cell.cellActions` |+| `cell.complete` |+| `cell.createAbove` |+| `cell.createBelow` |+| `cell.delete` |+| `cell.findAndReplace` |+| `cell.focusDown` |+| `cell.focusUp` |+| `cell.fold` |+| `cell.foldAll` |+| `cell.format` |+| `cell.goToDefinition` |+| `cell.hideCode` |+| `cell.moveDown` |+| `cell.moveUp` |+| `cell.redo` |+| `cell.run` |+| `cell.runAndNewAbove` |+| `cell.runAndNewBelow` |+| `cell.selectNextOccurrence` |+| `cell.sendToBottom` |+| `cell.sendToTop` |+| `cell.splitCell` |+| `cell.undo` |+| `cell.unfold` |+| `cell.unfoldAll` |+| `cell.viewAsMarkdown` |+| `global.commandPalette` |+| `global.focusBottom` |+| `global.focusTop` |+| `global.foldCode` |+| `global.formatAll` |+| `global.hideCode` |+| `global.interrupt` |+| `global.runStale` |+| `global.save` |+| `global.showHelp` |+| `global.toggleLanguage` |+| `global.toggleSidebar` |+| `global.unfoldCode` |+| `markdown.blockquote` |+| `markdown.bold` |+| `markdown.code` |+| `markdown.italic` |+| `markdown.link` |+| `markdown.orderedList` |+| `markdown.unorderedList` |diff --git a/docs/guides/index.md b/docs/guides/index.mdindex ccabf75da0..ea8b3ef121 100644--- a/docs/guides/index.md+++ b/docs/guides/index.md@@ -12,6 +12,7 @@coming_from_jupyteroutputseditor_features+ hotkeysdataframesplottingstate@@ -38,6 +39,7 @@ These guides cover marimo's core concepts.| {doc}`runtime_configuration` | Configure how and when cells are run || {doc}`outputs` | Markdown, plots, and other visual outputs || {doc}`editor_features` | View variables, cell dependencies, errors, and more |+| {doc}`hotkeys` | Keyboard shortcuts || {doc}`dataframes` | Working with dataframes || {doc}`plotting` | Interactive and reactive plots || {doc}`state` | Mutable, reactive state |diff --git a/frontend/src/components/app-config/user-config-form.tsx b/frontend/src/components/app-config/user-config-form.tsxindex 0819d45d24..1012479476 100644--- a/frontend/src/components/app-config/user-config-form.tsx+++ b/frontend/src/components/app-config/user-config-form.tsx@@ -26,10 +26,14 @@ import { PackageManagerNames } from "../../core/config/config-schema";import { Kbd } from "../ui/kbd";import { NumberField } from "@/components/ui/number-field";import { useRef } from "react";+import { useSetAtom } from "jotai";+import { keyboardShortcutsAtom } from "../editor/controls/keyboard-shortcuts";+import { Button } from "../ui/button";export const UserConfigForm: React.FC = () => {const [config, setConfig] = useUserConfig();const formElement = useRef<HTMLFormElement>(null);+ const setKeyboardShortcutsOpen = useSetAtom(keyboardShortcutsAtom);// Create formconst form = useForm<UserConfig>({@@ -206,6 +210,21 @@ export const UserConfigForm: React.FC = () => {</NativeSelect></FormControl><FormMessage />+ <div>+ <Button+ variant="link"+ size="xs"+ className="mb-0 px-0"+ type="button"+ onClick={(evt) => {+ evt.preventDefault();+ evt.stopPropagation();+ setKeyboardShortcutsOpen(true);+ }}+ >+ Edit Keyboard Shortcuts+ </Button>+ </div></FormItem>)}/>diff --git a/frontend/src/components/editor/cell/code/cell-editor.tsx b/frontend/src/components/editor/cell/code/cell-editor.tsxindex b984142741..dfcff9d2bc 100644--- a/frontend/src/components/editor/cell/code/cell-editor.tsx+++ b/frontend/src/components/editor/cell/code/cell-editor.tsx@@ -40,6 +40,7 @@ import { lastFocusedCellIdAtom } from "@/core/cells/focus";import type { LanguageAdapter } from "@/core/codemirror/language/types";import { autoInstantiateAtom } from "@/core/config/config";import { maybeAddMarimoImport } from "@/core/cells/add-missing-import";+import { OverridingHotkeyProvider } from "@/core/hotkeys/hotkeys";export interface CellEditorPropsextends Pick<CellRuntimeState, "status">,@@ -186,6 +187,7 @@ const CellEditorInternal = ({completionConfig: userConfig.completion,keymapConfig: userConfig.keymap,theme,+ hotkeys: new OverridingHotkeyProvider(userConfig.keymap.overrides),});extensions.push(@@ -265,6 +267,7 @@ const CellEditorInternal = ({reconfigureLanguageEffect(editorViewRef.current,userConfig.completion,+ new OverridingHotkeyProvider(userConfig.keymap.overrides),),],});@@ -318,6 +321,7 @@ const CellEditorInternal = ({editorViewRef,extensions,userConfig.completion,+ userConfig.keymap,clearSerializedEditorState,cellId,serializedEditorState,diff --git a/frontend/src/components/editor/controls/command-palette.tsx b/frontend/src/components/editor/controls/command-palette.tsxindex 54ef2601ea..b56ab062ce 100644--- a/frontend/src/components/editor/controls/command-palette.tsx+++ b/frontend/src/components/editor/controls/command-palette.tsx@@ -1,5 +1,4 @@/* Copyright 2024 Marimo. All rights reserved. */-import React from "react";import {CommandDialog,CommandEmpty,@@ -13,7 +12,7 @@ import {import { useRegisteredActions } from "../../../core/hotkeys/actions";import { useRecentCommands } from "../../../hooks/useRecentCommands";import { KeyboardHotkeys } from "../../shortcuts/renderShortcut";-import { HOTKEYS, HotkeyAction, isHotkeyAction } from "@/core/hotkeys/hotkeys";+import { HotkeyAction, isHotkeyAction } from "@/core/hotkeys/hotkeys";import { atom, useAtom, useAtomValue } from "jotai";import { useNotebookActions } from "../actions/useNotebookActions";import { Objects } from "@/utils/objects";@@ -22,6 +21,8 @@ import { isParentAction, flattenActions } from "../actions/types";import { useCellActionButtons } from "../actions/useCellActionButton";import { lastFocusedCellAtom } from "@/core/cells/focus";import { useConfigActions } from "../actions/useConfigActions";+import { hotkeysAtom } from "@/core/config/config";+import { useEventListener } from "@/hooks/useEventListener";export const commandPaletteAtom = atom(false);@@ -29,6 +30,7 @@ export const CommandPalette = () => {const [open, setOpen] = useAtom(commandPaletteAtom);const registeredActions = useRegisteredActions();const lastFocusedCell = useAtomValue(lastFocusedCellAtom);+ const hotkeys = useAtomValue(hotkeysAtom);// Cell actionslet cellActions = useCellActionButtons({ cell: lastFocusedCell }).flat();cellActions = flattenActions(cellActions);@@ -51,23 +53,19 @@ export const CommandPalette = () => {const { recentCommands, addRecentCommand } = useRecentCommands();const recentCommandsSet = new Set(recentCommands);- React.useEffect(() => {- const down = (e: KeyboardEvent) => {- if (parseShortcut(HOTKEYS.getHotkey("global.commandPalette").key)(e)) {- e.preventDefault();- setOpen((open) => !open);- }- };- document.addEventListener("keydown", down);- return () => document.removeEventListener("keydown", down);- }, [setOpen]);+ useEventListener(document, "keydown", (e) => {+ if (parseShortcut(hotkeys.getHotkey("global.commandPalette").key)(e)) {+ e.preventDefault();+ setOpen((open) => !open);+ }+ });const renderShortcutCommandItem = (shortcut: HotkeyAction) => {const action = registeredActions[shortcut];if (!action) {return null;}- const hotkey = HOTKEYS.getHotkey(shortcut);+ const hotkey = hotkeys.getHotkey(shortcut);return (<CommandItem@@ -110,7 +108,7 @@ export const CommandPalette = () => {<span>{label}</span>{hotkey && (<CommandShortcut>- <KeyboardHotkeys shortcut={HOTKEYS.getHotkey(hotkey).key} />+ <KeyboardHotkeys shortcut={hotkeys.getHotkey(hotkey).key} /></CommandShortcut>)}</CommandItem>@@ -145,7 +143,7 @@ export const CommandPalette = () => {</>)}<CommandGroup heading="Commands">- {HOTKEYS.iterate().map((shortcut) => {+ {hotkeys.iterate().map((shortcut) => {if (recentCommandsSet.has(shortcut)) {return null; // Don't show recent commands in the main list}diff --git a/frontend/src/components/editor/controls/keyboard-shortcuts.tsx b/frontend/src/components/editor/controls/keyboard-shortcuts.tsxindex 90a14e3955..a5f780360e 100644--- a/frontend/src/components/editor/controls/keyboard-shortcuts.tsx+++ b/frontend/src/components/editor/controls/keyboard-shortcuts.tsx@@ -9,31 +9,227 @@ import {DialogTitle,} from "../../ui/dialog";import { KeyboardHotkeys } from "../../shortcuts/renderShortcut";-import { HOTKEYS, HotkeyAction, HotkeyGroup } from "@/core/hotkeys/hotkeys";-import { atom, useAtom } from "jotai";+import {+ HotkeyAction,+ HotkeyGroup,+ getDefaultHotkey,+} from "@/core/hotkeys/hotkeys";+import { atom, useAtom, useAtomValue } from "jotai";+import { useState } from "react";+import { EditIcon, XIcon } from "lucide-react";+import { Input } from "@/components/ui/input";+import { hotkeysAtom, useUserConfig } from "@/core/config/config";+import { saveUserConfig } from "@/core/network/requests";+import { isPlatformMac } from "@/core/hotkeys/shortcuts";+import { Button } from "@/components/ui/button";+import { UserConfig } from "@/core/config/config-schema";export const keyboardShortcutsAtom = atom(false);export const KeyboardShortcuts: React.FC = () => {const [isOpen, setIsOpen] = useAtom(keyboardShortcutsAtom);+ const [editingShortcut, setEditingShortcut] = useState<HotkeyAction | null>(+ null,+ );+ const [newShortcut, setNewShortcut] = useState<string[]>([]);+ const [config, setConfig] = useUserConfig();+ const hotkeys = useAtomValue(hotkeysAtom);useHotkey("global.showHelp", () => setIsOpen((v) => !v));+ const saveConfigOptimistic = async (newConfig: UserConfig) => {+ const prevConfig = { ...config };+ setConfig(newConfig);+ await saveUserConfig({ config: newConfig }).catch((error) => {+ setConfig(prevConfig);+ throw error;+ });+ };++ const handleNewShortcut = async (shortcut: string[]) => {+ if (!editingShortcut) {+ return;+ }++ const shortcutString = shortcut.join("-");+ const newConfig = {+ ...config,+ keymap: {+ ...config.keymap,+ overrides: {+ ...config.keymap.overrides,+ [editingShortcut]: shortcutString,+ },+ },+ };++ setEditingShortcut(null);+ setNewShortcut([]);+ await saveConfigOptimistic(newConfig);+ };++ const handleResetShortcut = async () => {+ if (!editingShortcut) {+ return;+ }++ const newConfig = {+ ...config,+ keymap: {+ ...config.keymap,+ overrides: {+ ...config.keymap.overrides,+ },+ },+ };++ // eslint-disable-next-line @typescript-eslint/no-dynamic-delete+ delete newConfig.keymap.overrides[editingShortcut];++ setEditingShortcut(null);+ setNewShortcut([]);+ await saveConfigOptimistic(newConfig);+ };++ const handleResetAllShortcuts = async () => {+ if (+ !window.confirm(+ "Are you sure you want to reset all shortcuts to their default values?",+ )+ ) {+ return;+ }++ const newConfig = {+ ...config,+ keymap: {+ ...config.keymap,+ overrides: {},+ },+ };++ setEditingShortcut(null);+ setNewShortcut([]);+ await saveConfigOptimistic(newConfig);+ };+if (!isOpen) {return null;}const renderItem = (action: HotkeyAction) => {- const hotkey = HOTKEYS.getHotkey(action);+ const hotkey = hotkeys.getHotkey(action);++ if (editingShortcut === action) {+ const defaultHotkey = getDefaultHotkey(action);+ return (+ <div key={action}>+ <Input+ defaultValue={newShortcut.join("+")}+ placeholder={hotkey.name}+ onKeyDown={(e) => {+ e.preventDefault();+ const next: string[] = [];++ // Skip if the key is a modifier key+ if (+ e.key === "Meta" ||+ e.key === "Control" ||+ e.key === "Alt" ||+ e.key === "Shift"+ ) {+ return;+ }++ if (e.metaKey) {+ next.push(isPlatformMac() ? "Cmd" : "Meta");+ }+ if (e.ctrlKey) {+ next.push("Ctrl");+ }+ if (e.altKey) {+ next.push("Alt");+ }+ if (e.shiftKey) {+ next.push("Shift");+ }++ // We don't allow `-` to be a shortcut key, since it's used to+ // separate keys in the shortcut string+ if (e.key === "-") {+ return;+ }+ // If escape is pressed, without any modifier keys, cancel editing+ // We don't allow escape to be a shortcut key along, since it's used to+ // remove focus from many elements+ if (e.key === "Escape" && next.length === 0) {+ setEditingShortcut(null);+ setNewShortcut([]);+ return;+ }++ let key = e.key.toLowerCase();+ // Handle edge cases+ if (e.key === " ") {+ key = "Space";+ }++ next.push(key);++ handleNewShortcut(next);+ }}+ autoFocus={true}+ endAdornment={+ <Button+ variant="text"+ size="xs"+ className="mb-0"+ onClick={() => {+ setEditingShortcut(null);+ setNewShortcut([]);+ }}+ >+ <XIcon className="w-4 h-4" />+ </Button>+ }+ />+ <div className="flex items-center justify-between w-full">+ <span className="text-muted-foreground text-xs">+ Press a key combination+ </span>+ {defaultHotkey.key !== hotkey.key && (+ <span+ className="text-xs cursor-pointer text-primary"+ onClick={handleResetShortcut}+ >+ Reset to default:{" "}+ <span className="font-mono">{defaultHotkey.key}</span>+ </span>+ )}+ </div>+ </div>+ );+ }+return (- <div className="keyboard-shortcut flex flex-col" key={action}>- <KeyboardHotkeys shortcut={hotkey.key} />+ <div+ key={action}+ className="grid grid-cols-[auto,2fr,3fr] gap-2 items-center"+ >+ <EditIcon+ className="cursor-pointer opacity-60 hover:opacity-100 text-muted-foreground w-3 h-3"+ onClick={() => {+ setNewShortcut([]);+ setEditingShortcut(action);+ }}+ />+ <KeyboardHotkeys className="justify-end" shortcut={hotkey.key} /><span>{hotkey.name.toLowerCase()}</span></div>);};- const groups = HOTKEYS.getHotkeyGroups();+ const groups = hotkeys.getHotkeyGroups();const renderGroup = (group: HotkeyGroup) => {const items = groups[group];return (@@ -68,6 +264,15 @@ export const KeyboardShortcuts: React.FC = () => {{renderGroup("Running Cells")}{renderGroup("Creation and Ordering")}{renderGroup("Other")}+ <Button+ className="mt-4 hover:bg-destructive/10 hover:border-destructive"+ variant="outline"+ size="xs"+ onClick={handleResetAllShortcuts}+ tabIndex={-1}+ >+ <span className="text-destructive">Reset all to default</span>+ </Button></div></div></DialogContent>diff --git a/frontend/src/components/editor/file-tree/file-viewer.tsx b/frontend/src/components/editor/file-tree/file-viewer.tsxindex ecfbb98528..66b90507bb 100644--- a/frontend/src/components/editor/file-tree/file-viewer.tsx+++ b/frontend/src/components/editor/file-tree/file-viewer.tsx@@ -15,9 +15,10 @@ import { Button } from "../inputs/Inputs";import { CopyIcon, DownloadIcon, SaveIcon } from "lucide-react";import { renderShortcut } from "@/components/shortcuts/renderShortcut";import { Tooltip } from "@/components/ui/tooltip";-import { HOTKEYS } from "@/core/hotkeys/hotkeys";import { downloadBlob, downloadByURL } from "@/utils/download";import { Base64String, base64ToDataURL } from "@/utils/json/base64";+import { hotkeysAtom } from "@/core/config/config";+import { useAtomValue } from "jotai";interface Props {file: FileInfo;@@ -27,6 +28,7 @@ const unsavedContentsForFile = new Map<string, string>();export const FileViewer: React.FC<Props> = ({ file }) => {const { theme } = useTheme();+ const hotkeys = useAtomValue(hotkeysAtom);// undefined value means not modified yetconst [internalValue, setInternalValue] = useState<string>("");@@ -200,7 +202,7 @@ export const FileViewer: React.FC<Props> = ({ file }) => {// Command S for savekeymap.of([{- key: HOTKEYS.getHotkey("global.save").key,+ key: hotkeys.getHotkey("global.save").key,stopPropagation: true,run: () => {if (internalValue !== data.contents) {diff --git a/frontend/src/components/find-replace/find-replace.tsx b/frontend/src/components/find-replace/find-replace.tsxindex 05d2e2a1d1..f5de271ddb 100644--- a/frontend/src/components/find-replace/find-replace.tsx+++ b/frontend/src/components/find-replace/find-replace.tsx@@ -3,7 +3,7 @@ import {findReplaceAtom,openFindReplacePanel,} from "@/core/codemirror/find-replace/state";-import { useAtom } from "jotai";+import { useAtom, useAtomValue } from "jotai";import React, { useEffect, useState, useRef } from "react";import { Input } from "../ui/input";import { Button } from "../ui/button";@@ -33,7 +33,7 @@ import {setGlobalSearchQuery,} from "@/core/codemirror/find-replace/search-highlight";import { KeyboardHotkeys } from "../shortcuts/renderShortcut";-import { HOTKEYS } from "@/core/hotkeys/hotkeys";+import { hotkeysAtom } from "@/core/config/config";export const FindReplace: React.FC = () => {const [isFocused, setIsFocused] = useState(false);@@ -43,6 +43,7 @@ export const FindReplace: React.FC = () => {position: Map<EditorView, Map<string, number>>;}>();const findInputRef = useRef<HTMLInputElement>(null);+ const hotkeys = useAtomValue(hotkeysAtom);useHotkey("cell.findAndReplace", () => {// if already open and focused, fallback to default behavior@@ -276,7 +277,7 @@ export const FindReplace: React.FC = () => {<div className="text-xs text-muted-foreground flex gap-1 mt-2">Press{" "}<KeyboardHotkeys- shortcut={HOTKEYS.getHotkey("cell.findAndReplace").key}+ shortcut={hotkeys.getHotkey("cell.findAndReplace").key}/>{" "}again to open the native browser search.</div>diff --git a/frontend/src/components/shortcuts/renderShortcut.tsx b/frontend/src/components/shortcuts/renderShortcut.tsxindex bdb02c26d3..9f3e283c21 100644--- a/frontend/src/components/shortcuts/renderShortcut.tsx+++ b/frontend/src/components/shortcuts/renderShortcut.tsx@@ -1,12 +1,20 @@/* Copyright 2024 Marimo. All rights reserved. */-import { HotkeyAction, HOTKEYS } from "@/core/hotkeys/hotkeys";+import { HotkeyAction } from "@/core/hotkeys/hotkeys";import { isPlatformMac } from "@/core/hotkeys/shortcuts";import { Kbd } from "../ui/kbd";import { DropdownMenuShortcut } from "../ui/dropdown-menu";import { Tooltip } from "../ui/tooltip";+import { hotkeysAtom } from "@/core/config/config";+import { useAtomValue } from "jotai";+import { cn } from "@/utils/cn";export function renderShortcut(shortcut: HotkeyAction) {- const hotkey = HOTKEYS.getHotkey(shortcut);+ return <Shortcut shortcut={shortcut} />;+}++const Shortcut: React.FC<{ shortcut: HotkeyAction }> = ({ shortcut }) => {+ const hotkeys = useAtomValue(hotkeysAtom);+ const hotkey = hotkeys.getHotkey(shortcut);return (<span className="flex">@@ -14,15 +22,16 @@ export function renderShortcut(shortcut: HotkeyAction) {<KeyboardHotkeys shortcut={hotkey.key} /></span>);-}+};-export const KeyboardHotkeys: React.FC<{ shortcut: string }> = ({- shortcut,-}) => {+export const KeyboardHotkeys: React.FC<{+ className?: string;+ shortcut: string;+}> = ({ shortcut, className }) => {const keys = shortcut.split("-");return (- <div className="flex gap-1">+ <div className={cn("flex gap-1", className)}>{keys.map(prettyPrintHotkey).map(([label, symbol]) => {if (symbol) {return (@@ -44,7 +53,14 @@ export const KeyboardHotkeys: React.FC<{ shortcut: string }> = ({};export function renderMinimalShortcut(shortcut: HotkeyAction) {- const hotkey = HOTKEYS.getHotkey(shortcut);+ return <MinimalShortcut shortcut={shortcut} />;+}++const MinimalShortcut: React.FC<{ shortcut: HotkeyAction }> = ({+ shortcut,+}) => {+ const hotkeys = useAtomValue(hotkeysAtom);+ const hotkey = hotkeys.getHotkey(shortcut);const keys = hotkey.key.split("-");return (@@ -66,7 +82,7 @@ export function renderMinimalShortcut(shortcut: HotkeyAction) {})}</DropdownMenuShortcut>);-}+};function prettyPrintHotkey(key: string): [label: string, symbol?: string] {const platform = isPlatformMac() ? "mac" : "default";diff --git a/frontend/src/components/ui/input.tsx b/frontend/src/components/ui/input.tsxindex e0aa3e2d41..63dc59edaf 100644--- a/frontend/src/components/ui/input.tsx+++ b/frontend/src/components/ui/input.tsx@@ -41,7 +41,7 @@ const Input = React.forwardRef<HTMLInputElement, InputProps>({...props}/>{endAdornment && (- <div className="absolute inset-y-0 right-0 flex items-center pr-[6px] pointer-events-none text-muted-foreground h-6">+ <div className="absolute inset-y-0 right-0 flex items-center pr-[6px] text-muted-foreground h-6">{endAdornment}</div>)}diff --git a/frontend/src/core/codemirror/__tests__/setup.test.ts b/frontend/src/core/codemirror/__tests__/setup.test.tsindex e4385e73ac..065b43c53a 100644--- a/frontend/src/core/codemirror/__tests__/setup.test.ts+++ b/frontend/src/core/codemirror/__tests__/setup.test.ts@@ -5,6 +5,7 @@ import { EditorState, type Extension } from "@codemirror/state";import { keymap } from "@codemirror/view";import type { CellId } from "@/core/cells/ids";import { Objects } from "@/utils/objects";+import { OverridingHotkeyProvider } from "@/core/hotkeys/hotkeys";vi.mock("@/core/config/config", () => ({parseAppConfig: () => ({}),@@ -48,7 +49,9 @@ function setup(config: Partial<CodeMirrorSetupOpts> = {}): Extension[] {},keymapConfig: {preset: "default",+ overrides: {},},+ hotkeys: new OverridingHotkeyProvider({}),theme: "light",...config,});@@ -99,7 +102,7 @@ describe("snapshot all duplicate keymaps", () => {test("vim keymaps", () => {const extensions = setup({- keymapConfig: { preset: "vim" },+ keymapConfig: { preset: "vim", overrides: {} },});const duplicates = getDuplicateKeymaps(EditorState.create({ extensions: extensions }),diff --git a/frontend/src/core/codemirror/cells/extensions.ts b/frontend/src/core/codemirror/cells/extensions.tsindex daeb01e5e6..a79b0ded6d 100644--- a/frontend/src/core/codemirror/cells/extensions.ts+++ b/frontend/src/core/codemirror/cells/extensions.ts@@ -1,5 +1,5 @@/* Copyright 2024 Marimo. All rights reserved. */-import { HOTKEYS } from "@/core/hotkeys/hotkeys";+import { HotkeyProvider } from "@/core/hotkeys/hotkeys";import { EditorView, type KeyBinding, keymap } from "@codemirror/view";import { type CellId, HTMLCellId } from "@/core/cells/ids";import { type Extension, Prec } from "@codemirror/state";@@ -34,6 +34,7 @@ export interface MovementCallbacksexport function cellMovementBundle(cellId: CellId,callbacks: MovementCallbacks,+ hotkeys: HotkeyProvider,): Extension[] {const {onRun,@@ -52,9 +53,9 @@ export function cellMovementBundle(aiCellCompletion,} = callbacks;- const hotkeys: KeyBinding[] = [+ const keybindings: KeyBinding[] = [{- key: HOTKEYS.getHotkey("cell.run").key,+ key: hotkeys.getHotkey("cell.run").key,preventDefault: true,stopPropagation: true,run: () => {@@ -63,7 +64,7 @@ export function cellMovementBundle(},},{- key: HOTKEYS.getHotkey("cell.runAndNewBelow").key,+ key: hotkeys.getHotkey("cell.runAndNewBelow").key,preventDefault: true,stopPropagation: true,run: (ev) => {@@ -74,7 +75,7 @@ export function cellMovementBundle(},},{- key: HOTKEYS.getHotkey("cell.runAndNewAbove").key,+ key: hotkeys.getHotkey("cell.runAndNewAbove").key,preventDefault: true,stopPropagation: true,run: (ev) => {@@ -85,7 +86,7 @@ export function cellMovementBundle(},},{- key: HOTKEYS.getHotkey("cell.delete").key,+ key: hotkeys.getHotkey("cell.delete").key,preventDefault: true,stopPropagation: true,run: (cm) => {@@ -102,7 +103,7 @@ export function cellMovementBundle(},},{- key: HOTKEYS.getHotkey("cell.moveDown").key,+ key: hotkeys.getHotkey("cell.moveDown").key,preventDefault: true,stopPropagation: true,run: () => {@@ -111,7 +112,7 @@ export function cellMovementBundle(},},{- key: HOTKEYS.getHotkey("cell.moveUp").key,+ key: hotkeys.getHotkey("cell.moveUp").key,preventDefault: true,stopPropagation: true,run: () => {@@ -156,7 +157,7 @@ export function cellMovementBundle(},},{- key: HOTKEYS.getHotkey("cell.focusDown").key,+ key: hotkeys.getHotkey("cell.focusDown").key,preventDefault: true,stopPropagation: true,run: () => {@@ -165,7 +166,7 @@ export function cellMovementBundle(},},{- key: HOTKEYS.getHotkey("cell.focusUp").key,+ key: hotkeys.getHotkey("cell.focusUp").key,preventDefault: true,stopPropagation: true,run: () => {@@ -174,7 +175,7 @@ export function cellMovementBundle(},},{- key: HOTKEYS.getHotkey("cell.sendToBottom").key,+ key: hotkeys.getHotkey("cell.sendToBottom").key,preventDefault: true,stopPropagation: true,run: () => {@@ -183,7 +184,7 @@ export function cellMovementBundle(},},{- key: HOTKEYS.getHotkey("cell.sendToTop").key,+ key: hotkeys.getHotkey("cell.sendToTop").key,preventDefault: true,stopPropagation: true,run: () => {@@ -192,7 +193,7 @@ export function cellMovementBundle(},},{- key: HOTKEYS.getHotkey("cell.createAbove").key,+ key: hotkeys.getHotkey("cell.createAbove").key,preventDefault: true,stopPropagation: true,run: (ev) => {@@ -202,7 +203,7 @@ export function cellMovementBundle(},},{- key: HOTKEYS.getHotkey("cell.createBelow").key,+ key: hotkeys.getHotkey("cell.createBelow").key,preventDefault: true,stopPropagation: true,run: (ev) => {@@ -212,7 +213,7 @@ export function cellMovementBundle(},},{- key: HOTKEYS.getHotkey("cell.hideCode").key,+ key: hotkeys.getHotkey("cell.hideCode").key,preventDefault: true,stopPropagation: true,run: (ev) => {@@ -230,7 +231,7 @@ export function cellMovementBundle(},},{- key: HOTKEYS.getHotkey("cell.aiCompletion").key,+ key: hotkeys.getHotkey("cell.aiCompletion").key,preventDefault: true,stopPropagation: true,run: (ev) => {@@ -242,7 +243,7 @@ export function cellMovementBundle(},},{- key: HOTKEYS.getHotkey("cell.goToDefinition").key,+ key: hotkeys.getHotkey("cell.goToDefinition").key,preventDefault: true,stopPropagation: true,run: (ev) => {@@ -251,7 +252,7 @@ export function cellMovementBundle(},},{- key: HOTKEYS.getHotkey("cell.splitCell").key,+ key: hotkeys.getHotkey("cell.splitCell").key,preventDefault: true,stopPropagation: true,run: (ev) => {@@ -266,7 +267,7 @@ export function cellMovementBundle(];// Highest priority so that we can override the default keymap- return [Prec.high(keymap.of(hotkeys))];+ return [Prec.high(keymap.of(keybindings))];}export interface CodeCallbacks {@@ -280,6 +281,7 @@ export interface CodeCallbacks {export function cellCodeEditingBundle(cellId: CellId,callbacks: CodeCallbacks,+ hotkeys: HotkeyProvider,): Extension[] {const { updateCellCode } = callbacks;@@ -299,5 +301,5 @@ export function cellCodeEditingBundle(}});- return [onChangePlugin, formatKeymapExtension(cellId, callbacks)];+ return [onChangePlugin, formatKeymapExtension(cellId, callbacks, hotkeys)];}diff --git a/frontend/src/core/codemirror/cm.ts b/frontend/src/core/codemirror/cm.tsindex b48ada3bae..4fb22312cc 100644--- a/frontend/src/core/codemirror/cm.ts+++ b/frontend/src/core/codemirror/cm.ts@@ -59,6 +59,7 @@ import {smartPlaceholderExtension,} from "./placeholder/extensions";import { goToDefinitionBundle } from "./go-to-definition/extension";+import { HotkeyProvider } from "../hotkeys/hotkeys";export interface CodeMirrorSetupOpts {cellId: CellId;@@ -69,6 +70,7 @@ export interface CodeMirrorSetupOpts {completionConfig: CompletionConfig;keymapConfig: KeymapConfig;theme: Theme;+ hotkeys: HotkeyProvider;}/**@@ -83,15 +85,16 @@ export const setupCodeMirror = ({completionConfig,keymapConfig,theme,+ hotkeys,}: CodeMirrorSetupOpts): Extension[] => {return [// Editor keymaps (vim or defaults) based on user configkeymapBundle(keymapConfig, cellMovementCallbacks),// Cell editing- cellMovementBundle(cellId, cellMovementCallbacks),- cellCodeEditingBundle(cellId, cellCodeCallbacks),+ cellMovementBundle(cellId, cellMovementCallbacks, hotkeys),+ cellCodeEditingBundle(cellId, cellCodeCallbacks, hotkeys),// Comes last so that it can be overridden- basicBundle(completionConfig, theme),+ basicBundle(completionConfig, theme, hotkeys),// Underline cmd+clickable placeholdergoToDefinitionBundle(),showPlaceholder@@ -125,6 +128,7 @@ const startCompletionAtEndOfLine = (cm: EditorView): boolean => {export const basicBundle = (completionConfig: CompletionConfig,theme: Theme,+ hotkeys: HotkeyProvider,): Extension[] => {return [///// View@@ -160,12 +164,12 @@ export const basicBundle = (keymap.of([...foldKeymap, ...lintKeymap]),///// Language Support- adaptiveLanguageConfiguration(completionConfig),+ adaptiveLanguageConfiguration(completionConfig, hotkeys),///// EditinghistoryCompartment.of(history()),EditorState.allowMultipleSelections.of(true),- findReplaceBundle(),+ findReplaceBundle(hotkeys),keymap.of([{key: "Tab",diff --git a/frontend/src/core/codemirror/config/extension.ts b/frontend/src/core/codemirror/config/extension.tsindex eb2aaf0d28..892f14045b 100644--- a/frontend/src/core/codemirror/config/extension.ts+++ b/frontend/src/core/codemirror/config/extension.ts@@ -1,5 +1,6 @@/* Copyright 2024 Marimo. All rights reserved. */import { CompletionConfig } from "@/core/config/config-schema";+import { HotkeyProvider } from "@/core/hotkeys/hotkeys";import { Facet } from "@codemirror/state";export const completionConfigState = Facet.define<@@ -8,3 +9,10 @@ export const completionConfigState = Facet.define<>({combine: (values) => values[0],});++export const hotkeysProviderState = Facet.define<+ HotkeyProvider,+ HotkeyProvider+>({+ combine: (values) => values[0],+});diff --git a/frontend/src/core/codemirror/extensions.ts b/frontend/src/core/codemirror/extensions.tsindex fb8d23598a..bb8de0d251 100644--- a/frontend/src/core/codemirror/extensions.ts+++ b/frontend/src/core/codemirror/extensions.ts@@ -3,7 +3,7 @@ import { EditorView, keymap } from "@codemirror/view";import type { CellId } from "../cells/ids";import { formatEditorViews, toggleMarkdown } from "./format";import { smartScrollIntoView } from "../../utils/scroll";-import { HOTKEYS } from "@/core/hotkeys/hotkeys";+import { HotkeyProvider } from "@/core/hotkeys/hotkeys";import { invariant } from "@/utils/invariant";import type { CodeCallbacks } from "./cells/extensions";@@ -13,11 +13,12 @@ import type { CodeCallbacks } from "./cells/extensions";export function formatKeymapExtension(cellId: CellId,callbacks: CodeCallbacks,+ hotkeys: HotkeyProvider,) {const { updateCellCode, afterToggleMarkdown } = callbacks;return keymap.of([{- key: HOTKEYS.getHotkey("cell.format").key,+ key: hotkeys.getHotkey("cell.format").key,preventDefault: true,run: (ev) => {formatEditorViews({ [cellId]: ev }, updateCellCode);@@ -25,7 +26,7 @@ export function formatKeymapExtension(},},{- key: HOTKEYS.getHotkey("cell.viewAsMarkdown").key,+ key: hotkeys.getHotkey("cell.viewAsMarkdown").key,preventDefault: true,run: (ev) => {const response = toggleMarkdown(cellId, ev, updateCellCode);diff --git a/frontend/src/core/codemirror/find-replace/extension.ts b/frontend/src/core/codemirror/find-replace/extension.tsindex 623b648be2..83b7cf64e3 100644--- a/frontend/src/core/codemirror/find-replace/extension.ts+++ b/frontend/src/core/codemirror/find-replace/extension.ts@@ -1,5 +1,5 @@/* Copyright 2024 Marimo. All rights reserved. */-import { HOTKEYS } from "@/core/hotkeys/hotkeys";+import { HotkeyProvider } from "@/core/hotkeys/hotkeys";import {highlightSelectionMatches,selectNextOccurrence,@@ -12,7 +12,7 @@ import {searchState,} from "./search-highlight";-export function findReplaceBundle() {+export function findReplaceBundle(hotkeys: HotkeyProvider) {return [keymap.of([{@@ -22,12 +22,12 @@ export function findReplaceBundle() {run: closeFindReplacePanel,},{- key: HOTKEYS.getHotkey("cell.selectNextOccurrence").key,+ key: hotkeys.getHotkey("cell.selectNextOccurrence").key,preventDefault: true,run: selectNextOccurrence,},{- key: HOTKEYS.getHotkey("cell.findAndReplace").key,+ key: hotkeys.getHotkey("cell.findAndReplace").key,preventDefault: true,run: openFindReplacePanel,},diff --git a/frontend/src/core/codemirror/language/__tests__/utils.test.ts b/frontend/src/core/codemirror/language/__tests__/utils.test.tsindex 2e26a27f80..f7c1d0d34c 100644--- a/frontend/src/core/codemirror/language/__tests__/utils.test.ts+++ b/frontend/src/core/codemirror/language/__tests__/utils.test.ts@@ -8,16 +8,20 @@ import { EditorState } from "@codemirror/state";import { EditorView } from "@codemirror/view";import { describe, it, expect } from "vitest";import { adaptiveLanguageConfiguration, switchLanguage } from "../extension";+import { OverridingHotkeyProvider } from "@/core/hotkeys/hotkeys";function createEditor(doc: string) {return new EditorView({state: EditorState.create({doc,extensions: [- adaptiveLanguageConfiguration({- activate_on_typing: true,- copilot: false,- }),+ adaptiveLanguageConfiguration(+ {+ activate_on_typing: true,+ copilot: false,+ },+ new OverridingHotkeyProvider({}),+ ),],}),});diff --git a/frontend/src/core/codemirror/language/extension.ts b/frontend/src/core/codemirror/language/extension.tsindex 5e1f948c68..1e68e37562 100644--- a/frontend/src/core/codemirror/language/extension.ts+++ b/frontend/src/core/codemirror/language/extension.ts@@ -11,11 +11,15 @@ import { EditorView, Panel, keymap, showPanel } from "@codemirror/view";import { MarkdownLanguageAdapter } from "./markdown";import { clamp } from "@/utils/math";import { CompletionConfig } from "@/core/config/config-schema";-import { completionConfigState } from "../config/extension";+import {+ completionConfigState,+ hotkeysProviderState,+} from "../config/extension";import { historyCompartment } from "../editing/extensions";import { history } from "@codemirror/commands";import { formattingChangeEffect } from "../format";import { getEditorCodeAsPython } from "./utils";+import { HotkeyProvider } from "@/core/hotkeys/hotkeys";export const LanguageAdapters: Record<LanguageAdapter["type"],@@ -99,6 +103,7 @@ function updateLanguageAdapterAndCode(const currentLanguage = view.state.field(languageAdapterState);const code = view.state.doc.toString();const completionConfig = view.state.facet(completionConfigState);+ const hotkeysProvider = view.state.facet(hotkeysProviderState);// Update the codeconst [codeOut, cursorDiff1] = currentLanguage.transformOut(code);@@ -115,7 +120,7 @@ function updateLanguageAdapterAndCode(effects: [setLanguageAdapter.of(nextLanguage),languageCompartment.reconfigure(- nextLanguage.getExtension(completionConfig),+ nextLanguage.getExtension(completionConfig, hotkeysProvider),),// Clear historyhistoryCompartment.reconfigure([]),@@ -155,12 +160,14 @@ function createLanguagePanel(view: EditorView): Panel {*/export function adaptiveLanguageConfiguration(completionConfig: CompletionConfig,+ hotkeysProvider: HotkeyProvider,) {return [completionConfigState.of(completionConfig),+ hotkeysProviderState.of(hotkeysProvider),languageToggle(completionConfig),languageCompartment.of(- LanguageAdapters.python().getExtension(completionConfig),+ LanguageAdapters.python().getExtension(completionConfig, hotkeysProvider),),languageAdapterState,];@@ -194,9 +201,10 @@ export function switchLanguage(export function reconfigureLanguageEffect(view: EditorView,completionConfig: CompletionConfig,+ hotkeysProvider: HotkeyProvider,) {const language = view.state.field(languageAdapterState);return languageCompartment.reconfigure(- language.getExtension(completionConfig),+ language.getExtension(completionConfig, hotkeysProvider),);}diff --git a/frontend/src/core/codemirror/language/markdown.ts b/frontend/src/core/codemirror/language/markdown.tsindex 614ad63f31..b9b78dd3aa 100644--- a/frontend/src/core/codemirror/language/markdown.ts+++ b/frontend/src/core/codemirror/language/markdown.ts@@ -14,6 +14,8 @@ import {} from "@codemirror/autocomplete";import { once } from "lodash-es";import { enhancedMarkdownExtension } from "../markdown/extension";+import { CompletionConfig } from "@/core/config/config-schema";+import { HotkeyProvider } from "@/core/hotkeys/hotkeys";const prefixKinds = ["", "f", "r", "fr", "rf"] as const;type PrefixKind = (typeof prefixKinds)[number];@@ -108,7 +110,10 @@ export class MarkdownLanguageAdapter implements LanguageAdapter {return regexes.some(([, regex]) => regex.test(pythonCode));}- getExtension(): Extension {+ getExtension(+ _completionConfig: CompletionConfig,+ hotkeys: HotkeyProvider,+ ): Extension {return [markdown({codeLanguages: languages,@@ -141,7 +146,7 @@ export class MarkdownLanguageAdapter implements LanguageAdapter {},],}),- enhancedMarkdownExtension(),+ enhancedMarkdownExtension(hotkeys),autocompletion({activateOnTyping: true,override: [emojiCompletionSource],diff --git a/frontend/src/core/codemirror/language/types.ts b/frontend/src/core/codemirror/language/types.tsindex b49671e4c6..b0a08e8c52 100644--- a/frontend/src/core/codemirror/language/types.ts+++ b/frontend/src/core/codemirror/language/types.ts@@ -1,5 +1,6 @@/* Copyright 2024 Marimo. All rights reserved. */import { CompletionConfig } from "@/core/config/config-schema";+import { HotkeyProvider } from "@/core/hotkeys/hotkeys";import { Extension } from "@codemirror/state";/**@@ -12,5 +13,8 @@ export interface LanguageAdapter {transformIn(code: string): [string, number];transformOut(code: string): [string, number];isSupported(code: string): boolean;- getExtension(completionConfig: CompletionConfig): Extension;+ getExtension(+ completionConfig: CompletionConfig,+ hotkeys: HotkeyProvider,+ ): Extension;}diff --git a/frontend/src/core/codemirror/markdown/extension.ts b/frontend/src/core/codemirror/markdown/extension.tsindex f2e4445213..d61c9a81bf 100644--- a/frontend/src/core/codemirror/markdown/extension.ts+++ b/frontend/src/core/codemirror/markdown/extension.ts@@ -10,48 +10,50 @@ import {insertUL,} from "./commands";import { EditorView, keymap } from "@codemirror/view";-import { HOTKEYS } from "@/core/hotkeys/hotkeys";+import { HotkeyProvider } from "@/core/hotkeys/hotkeys";-export function enhancedMarkdownExtension(): Extension[] {+export function enhancedMarkdownExtension(+ hotkeys: HotkeyProvider,+): Extension[] {return [Prec.highest(keymap.of([// Runs always{- key: HOTKEYS.getHotkey("markdown.bold").key,+ key: hotkeys.getHotkey("markdown.bold").key,stopPropagation: true,run: insertBoldMarker,},// Runs always{- key: HOTKEYS.getHotkey("markdown.italic").key,+ key: hotkeys.getHotkey("markdown.italic").key,stopPropagation: true,run: insertItalicMarker,},// Only runs on selection{- key: HOTKEYS.getHotkey("markdown.link").key,+ key: hotkeys.getHotkey("markdown.link").key,stopPropagation: true,run: (cm) => insertLink(cm),},// Only runs on selection{- key: HOTKEYS.getHotkey("markdown.orderedList").key,+ key: hotkeys.getHotkey("markdown.orderedList").key,run: insertOL,},// Only runs on selection{- key: HOTKEYS.getHotkey("markdown.unorderedList").key,+ key: hotkeys.getHotkey("markdown.unorderedList").key,run: insertUL,},// Only runs on selection{- key: HOTKEYS.getHotkey("markdown.blockquote").key,+ key: hotkeys.getHotkey("markdown.blockquote").key,run: insertBlockquote,},// Only runs on selection{- key: HOTKEYS.getHotkey("markdown.code").key,+ key: hotkeys.getHotkey("markdown.code").key,run: insertCodeMarker,},// Only runs on selectiondiff --git a/frontend/src/core/config/__tests__/config-schema.test.ts b/frontend/src/core/config/__tests__/config-schema.test.tsindex 7caf2f2fc4..a2484160ea 100644--- a/frontend/src/core/config/__tests__/config-schema.test.ts+++ b/frontend/src/core/config/__tests__/config-schema.test.ts@@ -43,6 +43,7 @@ test("default UserConfig - empty", () => {"line_length": 79,},"keymap": {+ "overrides": {},"preset": "default",},"package_management": {@@ -89,6 +90,7 @@ test("default UserConfig - one level", () => {"line_length": 79,},"keymap": {+ "overrides": {},"preset": "default",},"package_management": {diff --git a/frontend/src/core/config/config-schema.ts b/frontend/src/core/config/config-schema.tsindex da737973fa..ed28d63a8e 100644--- a/frontend/src/core/config/config-schema.ts+++ b/frontend/src/core/config/config-schema.ts@@ -45,6 +45,7 @@ export const UserConfigSchema = zkeymap: z.object({preset: z.enum(["default", "vim"]).default("default"),+ overrides: z.record(z.string()).default({}),}).default({}),runtime: zdiff --git a/frontend/src/core/config/config.ts b/frontend/src/core/config/config.tsindex 37ff8d3b76..cd7ee5c2c6 100644--- a/frontend/src/core/config/config.ts+++ b/frontend/src/core/config/config.ts@@ -7,6 +7,7 @@ import {parseUserConfig,} from "./config-schema";import { store } from "../state/jotai";+import { OverridingHotkeyProvider } from "../hotkeys/hotkeys";/*** Atom for storing the user config.@@ -17,6 +18,15 @@ export const autoInstantiateAtom = atom((get) => {return get(userConfigAtom).runtime.auto_instantiate;});+export const hotkeyOverridesAtom = atom((get) => {+ return get(userConfigAtom).keymap.overrides;+});++export const hotkeysAtom = atom((get) => {+ const overrides = get(hotkeyOverridesAtom);+ return new OverridingHotkeyProvider(overrides);+});+/*** Returns the user config.*/diff --git a/frontend/src/core/hotkeys/hotkeys.ts b/frontend/src/core/hotkeys/hotkeys.tsindex dc5e14a6ab..b90ff1b460 100644--- a/frontend/src/core/hotkeys/hotkeys.ts+++ b/frontend/src/core/hotkeys/hotkeys.ts@@ -314,6 +314,9 @@ export function isHotkeyAction(x: string): x is HotkeyAction {return x in DEFAULT_HOT_KEY;}+export function getDefaultHotkey(action: HotkeyAction): ResolvedHotkey {+ return new HotkeyProvider(DEFAULT_HOT_KEY).getHotkey(action);+}export interface IHotkeyProvider {getHotkey(action: HotkeyAction): ResolvedHotkey;}@@ -386,8 +389,3 @@ export class OverridingHotkeyProvider extends HotkeyProvider {};}}--export const HOTKEYS = new OverridingHotkeyProvider({- // Override default hotkeys here.- // This can be from the user's settings.-});diff --git a/frontend/src/css/app/Header.css b/frontend/src/css/app/Header.cssindex c88cced76a..73fdf186e2 100644--- a/frontend/src/css/app/Header.css+++ b/frontend/src/css/app/Header.css@@ -41,14 +41,3 @@.keyboard-shortcut-group {margin-bottom: 40px;}--.keyboard-shortcut {- /* [shortcut] [auto:whitespace] [description] */- grid-template-columns: 1fr auto 1fr;- display: grid;- align-items: baseline;-}--.keyboard-shortcut span {- grid-column: 3;-}diff --git a/frontend/src/hooks/useHotkey.ts b/frontend/src/hooks/useHotkey.tsindex 6e6f0301ea..b667bb7af7 100644--- a/frontend/src/hooks/useHotkey.ts+++ b/frontend/src/hooks/useHotkey.ts@@ -5,10 +5,12 @@ import { parseShortcut } from "../core/hotkeys/shortcuts";import { useEventListener } from "./useEventListener";import { useEvent } from "./useEvent";import { useSetRegisteredAction } from "../core/hotkeys/actions";-import { HOTKEYS, HotkeyAction } from "@/core/hotkeys/hotkeys";+import { HotkeyAction } from "@/core/hotkeys/hotkeys";import { Objects } from "@/utils/objects";import { Logger } from "@/utils/Logger";import { Functions } from "@/utils/functions";+import { hotkeysAtom } from "@/core/config/config";+import { useAtomValue } from "jotai";// eslint-disable-next-line @typescript-eslint/no-invalid-void-typetype HotkeyHandler = () => boolean | void | undefined | Promise<void>;@@ -21,12 +23,13 @@ type HotkeyHandler = () => boolean | void | undefined | Promise<void>;*/export function useHotkey(shortcut: HotkeyAction, callback: HotkeyHandler) {const { registerAction, unregisterAction } = useSetRegisteredAction();+ const hotkeys = useAtomValue(hotkeysAtom);const isNOOP = callback === Functions.NOOP;const memoizeCallback = useEvent(() => callback());const listener = useEvent((e: KeyboardEvent) => {- const key = HOTKEYS.getHotkey(shortcut).key;+ const key = hotkeys.getHotkey(shortcut).key;if (parseShortcut(key)(e)) {const response = callback();// Prevent default if the callback does not return false@@ -57,9 +60,10 @@ export function useHotkeysOnElement<T extends HotkeyAction>(element: HTMLElement | null,handlers: Record<T, HotkeyHandler>,) {+ const hotkeys = useAtomValue(hotkeysAtom);useEventListener(element, "keydown", (e) => {for (const [shortcut, callback] of Objects.entries(handlers)) {- const key = HOTKEYS.getHotkey(shortcut).key;+ const key = hotkeys.getHotkey(shortcut).key;if (parseShortcut(key)(e)) {Logger.debug("Satisfied", key, e);const response = callback();diff --git a/frontend/src/stories/cell.stories.tsx b/frontend/src/stories/cell.stories.tsxindex 6fd8d771c2..6221a0410d 100644--- a/frontend/src/stories/cell.stories.tsx+++ b/frontend/src/stories/cell.stories.tsx@@ -72,6 +72,7 @@ const props: CellProps = {},keymap: {preset: "default",+ overrides: {},},formatting: {line_length: 79,diff --git a/frontend/src/stories/editor.stories.tsx b/frontend/src/stories/editor.stories.tsxindex 4b7b807dc0..5b78f8b20d 100644--- a/frontend/src/stories/editor.stories.tsx+++ b/frontend/src/stories/editor.stories.tsx@@ -8,6 +8,7 @@ import { basicBundle } from "../core/codemirror/cm";import { python } from "@codemirror/lang-python";import { CopilotConfig } from "@/core/codemirror/copilot/copilot-config";import { copilotBundle } from "@/core/codemirror/copilot/extension";+import { OverridingHotkeyProvider } from "@/core/hotkeys/hotkeys";const meta: Meta = {title: "Editor",@@ -63,6 +64,7 @@ export const Primary: Story = {extensions={basicBundle({ activate_on_typing: false, copilot: false },ctx.globals.theme,+ new OverridingHotkeyProvider({}),)}/></div>diff --git a/marimo/_config/config.py b/marimo/_config/config.pyindex b04f0added..ba474a2baa 100644--- a/marimo/_config/config.py+++ b/marimo/_config/config.py@@ -55,9 +55,11 @@ class KeymapConfig(TypedDict, total=False):**Keys.**- `preset`: one of `"default"` or `"vim"`+ - `overrides`: a dict of keymap actions to their keymap override"""preset: Literal["default", "vim"]+ overrides: Dict[str, str]OnCellChangeType = Literal["lazy", "autorun"]@@ -190,7 +192,7 @@ DEFAULT_CONFIG: MarimoConfig = {"cell_output": "above",},"formatting": {"line_length": 79},- "keymap": {"preset": "default"},+ "keymap": {"preset": "default", "overrides": {}},"runtime": {"auto_instantiate": True,"auto_reload": "off",@@ -218,6 +220,13 @@ def merge_config(config: MarimoConfig, new_config: MarimoConfig) -> MarimoConfig:"""Merge a user configuration with a new configuration."""+ # Remove the keymap overrides from the incoming config,+ # so that they don't get merged into the new config+ if new_config.get("keymap", {}).get("overrides") is not None:+ # Clone config to avoid modifying the original+ config = _deep_copy(config)+ config.get("keymap", {}).pop("overrides", {})+merged = cast(MarimoConfig,deep_merge(diff --git a/tests/_config/test_config.py b/tests/_config/test_config.pyindex 33d6b7bb37..cf6ca04a90 100644--- a/tests/_config/test_config.py+++ b/tests/_config/test_config.py@@ -1,4 +1,6 @@# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations+from marimo._config.config import (DEFAULT_CONFIG,MarimoConfig,@@ -15,7 +17,7 @@ def assert_config(override: MarimoConfig) -> None:def test_configure_partial_keymap() -> None:- assert_config(MarimoConfig(keymap={"preset": "vim"}))+ assert_config(MarimoConfig(keymap={"preset": "vim", "overrides": {}}))def test_configure_full() -> None:@@ -27,7 +29,7 @@ def test_configure_full() -> None:"autosave_delay": 2,"format_on_save": False,},- keymap={"preset": "vim"},+ keymap={"preset": "vim", "overrides": {}},package_management={"manager": "pip"},))@@ -64,6 +66,50 @@ def test_merge_config() -> None:assert new_config["ai"]["open_ai"]["model"] == "davinci"+def test_merge_config_with_keymap_overrides() -> None:+ prev_config = merge_default_config(+ MarimoConfig(+ keymap={+ "preset": "default",+ "overrides": {+ "run-all": "ctrl-enter",+ },+ },+ )+ )+ assert prev_config["keymap"]["preset"] == "default"+ assert prev_config["keymap"]["overrides"]["run-all"] == "ctrl-enter"++ new_config = merge_config(+ prev_config,+ MarimoConfig(+ keymap={+ "preset": "vim",+ "overrides": {+ "run-cell": "ctrl-enter",+ },+ },+ ),+ )++ assert new_config["keymap"]["preset"] == "vim"+ assert "run-all" not in new_config["keymap"]["overrides"]+ assert new_config["keymap"]["overrides"]["run-cell"] == "ctrl-enter"++ new_config = merge_config(+ prev_config,+ MarimoConfig(+ keymap={+ "preset": "vim",+ "overrides": {},+ },+ ),+ )++ assert new_config["keymap"]["preset"] == "vim"+ assert new_config["keymap"]["overrides"] == {}++def test_mask_secrets() -> None:config = MarimoConfig(ai={"open_ai": {"api_key": "super_secret"}})assert config["ai"]["open_ai"]["api_key"] == "super_secret"diff --git a/tests/_server/templates/snapshots/export1.txt b/tests/_server/templates/snapshots/export1.txtindex bab697f43b..d8bef7c8c6 100644--- a/tests/_server/templates/snapshots/export1.txt+++ b/tests/_server/templates/snapshots/export1.txt@@ -56,7 +56,7 @@<marimo-filename hidden>notebook.py</marimo-filename><marimo-mode data-mode='read' hidden></marimo-mode><marimo-version data-version='0.0.0' hidden></marimo-version>- <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"preset": "default"}, "package_management": {"manager": "pip"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}}' hidden></marimo-user-config>+ <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "package_management": {"manager": "pip"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}}' hidden></marimo-user-config><marimo-app-config data-config='{"app_title": null, "layout_file": null, "width": "normal"}' hidden></marimo-app-config><marimo-server-token data-token='token' hidden></marimo-server-token><title>notebook</title>diff --git a/tests/_server/templates/snapshots/export2.txt b/tests/_server/templates/snapshots/export2.txtindex 73e5755862..51176d3875 100644--- a/tests/_server/templates/snapshots/export2.txt+++ b/tests/_server/templates/snapshots/export2.txt@@ -56,7 +56,7 @@<marimo-filename hidden></marimo-filename><marimo-mode data-mode='read' hidden></marimo-mode><marimo-version data-version='0.0.0' hidden></marimo-version>- <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"preset": "default"}, "package_management": {"manager": "pip"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}}' hidden></marimo-user-config>+ <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "package_management": {"manager": "pip"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}}' hidden></marimo-user-config><marimo-app-config data-config='{"app_title": null, "layout_file": null, "width": "normal"}' hidden></marimo-app-config><marimo-server-token data-token='token' hidden></marimo-server-token><title>marimo</title>diff --git a/tests/_server/templates/snapshots/export3.txt b/tests/_server/templates/snapshots/export3.txtindex c2b999b906..aa88bab164 100644--- a/tests/_server/templates/snapshots/export3.txt+++ b/tests/_server/templates/snapshots/export3.txt@@ -56,7 +56,7 @@<marimo-filename hidden>notebook.py</marimo-filename><marimo-mode data-mode='read' hidden></marimo-mode><marimo-version data-version='0.0.0' hidden></marimo-version>- <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"preset": "default"}, "package_management": {"manager": "pip"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}}' hidden></marimo-user-config>+ <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "package_management": {"manager": "pip"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}}' hidden></marimo-user-config><marimo-app-config data-config='{"app_title": null, "layout_file": null, "width": "normal"}' hidden></marimo-app-config><marimo-server-token data-token='token' hidden></marimo-server-token><title>notebook</title>diff --git a/tests/_server/templates/test_templates.py b/tests/_server/templates/test_templates.pyindex c46811fd41..1bebaf081b 100644--- a/tests/_server/templates/test_templates.py+++ b/tests/_server/templates/test_templates.py@@ -28,7 +28,7 @@ class TestNotebookPageTemplate(unittest.TestCase):self.base_url = "/subpath"self.user_config = DEFAULT_CONFIG- self.server_token = "token"+ self.server_token = SkewProtectionToken("token")self.app_config = _AppConfig()self.filename = "notebook.py"self.mode = SessionMode.RUN@@ -45,7 +45,7 @@ class TestNotebookPageTemplate(unittest.TestCase):)assert self.base_url in result- assert self.server_token in result+ assert str(self.server_token) in resultassert self.filename in resultassert "read" in result@@ -61,7 +61,7 @@ class TestNotebookPageTemplate(unittest.TestCase):)assert self.base_url in result- assert self.server_token in result+ assert str(self.server_token) in resultassert "<title>marimo</title>" in resultassert "read" in result@@ -77,7 +77,7 @@ class TestNotebookPageTemplate(unittest.TestCase):)assert self.base_url in result- assert self.server_token in result+ assert str(self.server_token) in resultassert self.filename in resultassert "edit" in result@@ -93,7 +93,7 @@ class TestHomePageTemplate(unittest.TestCase):self.base_url = "/subpath"self.user_config = DEFAULT_CONFIG- self.server_token = "token"+ self.server_token = SkewProtectionToken("token")def test_home_page_template(self) -> None:result = templates.home_page_template(@@ -104,7 +104,7 @@ class TestHomePageTemplate(unittest.TestCase):)assert self.base_url in result- assert self.server_token in result+ assert str(self.server_token) in resultassert json.dumps(self.user_config) in resultassert "marimo" in resultassert json.dumps({}) in result