Skip to content

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

feat: format on save (#184)

Myles Scolnick845ca3a24423
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 4b4fad3fd2..84c25aa9f0 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -47,6 +47,7 @@ import { CellsRenderer } from "./editor/renderers/cells-renderer";
import { getSerializedLayout } from "./core/state/layout";
import { useAtom } from "jotai";
import { useRunStaleCells } from "./editor/cell/useRunCells";
+import { formatAll } from "./core/codemirror/format";
interface AppProps {
userConfig: UserConfig;
@@ -55,7 +56,7 @@ interface AppProps {
export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {
const cells = useCells();
- const { setCells } = useCellActions();
+ const { setCells, updateCellCode } = useCellActions();
const [viewState, setViewState] = useAtom(viewStateAtom);
const [filename, setFilename] = useState(getFilenameFromDOM());
const [savedCodes, setSavedCodes] = useState<string[]>([""]);
@@ -117,7 +118,7 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {
savedConfigs.some((config, index) => configs[index] !== config);
// Save the notebook with the given filename
- const saveNotebook = useEvent((filename: string, showToast: boolean) => {
+ const saveNotebook = useEvent((filename: string, userInitiated: boolean) => {
// Don't save if there are no cells
if (codes.length === 0) {
return;
@@ -143,8 +144,11 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {
layout: getSerializedLayout(),
})
.then(() => {
- if (showToast) {
+ if (userInitiated) {
toast({ title: "Notebook saved" });
+ if (userConfig.save.format_on_save) {
+ formatAll(updateCellCode);
+ }
}
setSavedCodes(codes);
setSavedConfigs(configs);
@@ -155,9 +159,9 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {
});
// Save the notebook with the current filename, only if the filename exists
- const saveIfNotebookIsNamed = useEvent((showToast = false) => {
+ const saveIfNotebookIsNamed = useEvent((userInitiated = false) => {
if (filename !== null && connStatus.state === WebSocketState.OPEN) {
- saveNotebook(filename, showToast);
+ saveNotebook(filename, userInitiated);
}
});
diff --git a/frontend/src/components/app-config/user-config-form.tsx b/frontend/src/components/app-config/user-config-form.tsx
index c886f9490a..06c3867641 100644
--- a/frontend/src/components/app-config/user-config-form.tsx
+++ b/frontend/src/components/app-config/user-config-form.tsx
@@ -104,6 +104,25 @@ export const UserConfigForm: React.FC = () => {
</FormItem>
)}
/>
+ <div>
+ <FormField
+ control={form.control}
+ name="save.format_on_save"
+ render={({ field }) => (
+ <FormItem className="flex flex-row items-start space-x-2 space-y-0">
+ <FormControl>
+ <Checkbox
+ checked={field.value}
+ onCheckedChange={(checked) => {
+ return field.onChange(checked);
+ }}
+ />
+ </FormControl>
+ <FormLabel className="font-normal">Format on save</FormLabel>
+ </FormItem>
+ )}
+ />
+ </div>
<FormField
control={form.control}
name="completion.activate_on_typing"
diff --git a/frontend/src/core/codemirror/format.ts b/frontend/src/core/codemirror/format.ts
index f4d6669864..f56ce1a3fd 100644
--- a/frontend/src/core/codemirror/format.ts
+++ b/frontend/src/core/codemirror/format.ts
@@ -3,7 +3,7 @@ import { EditorView } from "@codemirror/view";
import { CellId } from "../model/ids";
import { Objects } from "../../utils/objects";
import { sendFormat } from "../network/requests";
-import { CellActions } from "../state/cells";
+import { CellActions, getCells } from "../state/cells";
/**
* Format the code in the editor views via the marimo server,
@@ -43,3 +43,18 @@ export async function formatEditorViews(
});
}
}
+
+/**
+ * Format all cells in the notebook.
+ */
+export function formatAll(updateCellCode: CellActions["updateCellCode"]) {
+ const cells = getCells();
+ const views: Record<CellId, EditorView> = {};
+ cells.forEach((cell) => {
+ const editorView = cell.ref.current?.editorView;
+ if (editorView) {
+ views[cell.key] = editorView;
+ }
+ });
+ return formatEditorViews(views, updateCellCode);
+}
diff --git a/frontend/src/core/config/config.ts b/frontend/src/core/config/config.ts
index b79fabc751..a285026031 100644
--- a/frontend/src/core/config/config.ts
+++ b/frontend/src/core/config/config.ts
@@ -17,6 +17,7 @@ export const UserConfigSchema = z
// Ensure that the delay is at least 1 second
.transform((millis) => Math.max(millis, 1000))
.default(1000),
+ format_on_save: z.boolean().default(false),
}),
keymap: z.object({
preset: z.enum(["default", "vim"]).default("default"),
diff --git a/frontend/src/editor/renderers/CellArray.tsx b/frontend/src/editor/renderers/CellArray.tsx
index eba82aeb38..b0331c8e01 100644
--- a/frontend/src/editor/renderers/CellArray.tsx
+++ b/frontend/src/editor/renderers/CellArray.tsx
@@ -1,6 +1,5 @@
/* Copyright 2023 Marimo. All rights reserved. */
import { useEffect } from "react";
-import { EditorView } from "@codemirror/view";
import { sendDeleteCell } from "@/core/network/requests";
import { Cell } from "editor/Cell";
import { RuntimeState } from "../../core/RuntimeState";
@@ -10,8 +9,7 @@ import { AppConfig, UserConfig } from "../../core/config/config";
import { AppMode } from "../../core/mode";
import { useHotkey } from "../../hooks/useHotkey";
import { useEvent } from "../../hooks/useEvent";
-import { CellId } from "../../core/model/ids";
-import { formatEditorViews } from "../../core/codemirror/format";
+import { formatAll } from "../../core/codemirror/format";
import { useTheme } from "../../theme/useTheme";
import { VerticalLayoutWrapper } from "./vertical-layout/vertical-layout-wrapper";
import { useDelayVisibility } from "./vertical-layout/useDelayVisiblity";
@@ -63,14 +61,7 @@ export const CellArray: React.FC<CellArrayProps> = ({
useHotkey("global.foldCode", foldAll);
useHotkey("global.unfoldCode", unfoldAll);
useHotkey("global.formatAll", () => {
- const views: Record<CellId, EditorView> = {};
- cells.present.forEach((cell) => {
- const editorView = cell.ref.current?.editorView;
- if (editorView) {
- views[cell.key] = editorView;
- }
- });
- formatEditorViews(views, updateCellCode);
+ formatAll(updateCellCode);
});
const onDeleteCell: typeof deleteCell = useEvent((payload) => {
diff --git a/frontend/src/stories/cell.stories.tsx b/frontend/src/stories/cell.stories.tsx
index 075b246970..b51f70c178 100644
--- a/frontend/src/stories/cell.stories.tsx
+++ b/frontend/src/stories/cell.stories.tsx
@@ -49,6 +49,7 @@ const props: CellProps = {
save: {
autosave: "off",
autosave_delay: 1000,
+ format_on_save: false,
},
runtime: {
auto_instantiate: true,
diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts
index b8f5d0c235..6f7581ad9c 100644
--- a/frontend/vite.config.ts
+++ b/frontend/vite.config.ts
@@ -21,6 +21,9 @@ const htmlDevPlugin = (): Plugin => {
save: {
autosave: "off",
autosave_delay: 0,
+ format_on_save: false,
+ },
+ runtime: {
auto_instantiate: true,
},
keymap: {
diff --git a/marimo/_config/config.py b/marimo/_config/config.py
index 4ec7275758..45f4c15248 100644
--- a/marimo/_config/config.py
+++ b/marimo/_config/config.py
@@ -42,10 +42,12 @@ class SaveConfig(TypedDict, total=False):
- `autosave`: one of `"off"` or `"after_delay"`
- `delay`: number of milliseconds to wait before autosaving
+ - `format_on_save`: if `True`, format the code on save
"""
autosave: Literal["off", "after_delay"]
autosave_delay: int
+ format_on_save: bool
@mddoc
@@ -111,7 +113,11 @@ class MarimoConfig(TypedDict, total=False):
DEFAULT_CONFIG: MarimoConfig = {
"completion": {"activate_on_typing": True, "copilot": False},
- "save": {"autosave": "after_delay", "autosave_delay": 1000},
+ "save": {
+ "autosave": "after_delay",
+ "autosave_delay": 1000,
+ "format_on_save": False,
+ },
"keymap": {"preset": "default"},
"runtime": {"auto_instantiate": True},
}
diff --git a/marimo/_config/test_config.py b/marimo/_config/test_config.py
index 7163dcedfe..a59971b9fb 100644
--- a/marimo/_config/test_config.py
+++ b/marimo/_config/test_config.py
@@ -15,7 +15,11 @@ def test_configure_full() -> None:
assert_config(
MarimoConfig(
completion={"activate_on_typing": False, "copilot": False},
- save={"autosave": "after_delay", "autosave_delay": 2},
+ save={
+ "autosave": "after_delay",
+ "autosave_delay": 2,
+ "format_on_save": False,
+ },
keymap={"preset": "vim"},
)
)