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: configurable line length in format (#528)

Akshay Agrawal415437804a6a
diff --git a/frontend/src/components/app-config/user-config-form.tsx b/frontend/src/components/app-config/user-config-form.tsx
index 6ed6f7e433..10817ffb0e 100644
--- a/frontend/src/components/app-config/user-config-form.tsx
+++ b/frontend/src/components/app-config/user-config-form.tsx
@@ -122,6 +122,32 @@ export const UserConfigForm: React.FC = () => {
)}
/>
</div>
+ <FormField
+ control={form.control}
+ name="formatting.line_length"
+ render={({ field }) => (
+ <FormItem className="mb-2">
+ <FormLabel>Line length</FormLabel>
+ <FormDescription>
+ Maximum line length when formatting code.
+ </FormDescription>
+ <FormControl>
+ <span className="inline-flex mx-2">
+ <Input
+ type="number"
+ className="m-0 w-20 inline-flex"
+ {...field}
+ value={field.value}
+ min={1}
+ max={1000}
+ onChange={(e) => field.onChange(e.target.valueAsNumber)}
+ />
+ </span>
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
<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 4653a8096f..cd7c2f9e8b 100644
--- a/frontend/src/core/codemirror/format.ts
+++ b/frontend/src/core/codemirror/format.ts
@@ -13,6 +13,7 @@ import {
updateEditorCodeFromPython,
} from "./language/utils";
import { StateEffect } from "@codemirror/state";
+import { getUserConfig } from "../config/config";
export const formattingChangeEffect = StateEffect.define<boolean>();
@@ -26,7 +27,10 @@ export async function formatEditorViews(
) {
const codes = Objects.mapValues(views, (view) => getEditorCodeAsPython(view));
- const formatResponse = await sendFormat(codes);
+ const formatResponse = await sendFormat({
+ codes,
+ lineLength: getUserConfig().formatting.line_length,
+ });
for (const [cellId, formattedCode] of Objects.entries(formatResponse)) {
const originalCode = codes[cellId];
diff --git a/frontend/src/core/config/config-schema.ts b/frontend/src/core/config/config-schema.ts
index 7605443ca5..256f1823be 100644
--- a/frontend/src/core/config/config-schema.ts
+++ b/frontend/src/core/config/config-schema.ts
@@ -22,6 +22,15 @@ export const UserConfigSchema = z
.default(1000),
format_on_save: z.boolean().default(false),
}),
+ formatting: z
+ .object({
+ line_length: z
+ .number()
+ .nonnegative()
+ .default(79)
+ .transform((n) => Math.min(n, 1000)),
+ })
+ .default({ line_length: 79 }),
keymap: z.object({
preset: z.enum(["default", "vim"]).default("default"),
}),
diff --git a/frontend/src/core/network/requests.ts b/frontend/src/core/network/requests.ts
index 0c8a532c23..a3ecab8a1a 100644
--- a/frontend/src/core/network/requests.ts
+++ b/frontend/src/core/network/requests.ts
@@ -60,10 +60,11 @@ function createNetworkRequests(): EditRequests & RunRequests {
return API.post<SaveKernelRequest>("/kernel/save/", request);
},
- sendFormat: (codes: Record<CellId, string>) => {
- return API.post<FormatRequest, FormatResponse>("/kernel/format/", {
- codes: codes,
- }).then((res) => res.codes);
+ sendFormat: (request: FormatRequest) => {
+ return API.post<FormatRequest, FormatResponse>(
+ "/kernel/format/",
+ request
+ ).then((res) => res.codes);
},
sendInterrupt: () => {
return API.post("/kernel/interrupt/", {});
diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.ts
index 892e49857c..e65e831ad4 100644
--- a/frontend/src/core/network/types.ts
+++ b/frontend/src/core/network/types.ts
@@ -22,6 +22,10 @@ export interface FormatRequest {
* mapping of cell ids to code
*/
codes: Record<CellId, string>;
+ /**
+ * line-length
+ */
+ lineLength: number;
}
export interface FormatResponse {
@@ -116,9 +120,7 @@ export interface EditRequests {
sendRun: (cellIds: CellId[], codes: string[]) => Promise<null>;
sendInterrupt: () => Promise<null>;
sendShutdown: () => Promise<null>;
- sendFormat: (
- codes: Record<CellId, string>
- ) => Promise<Record<CellId, string>>;
+ sendFormat: (request: FormatRequest) => Promise<Record<CellId, string>>;
sendDeleteCell: (cellId: CellId) => Promise<null>;
sendDirectoryAutocompleteRequest: (
prefix: string
diff --git a/frontend/src/stories/cell.stories.tsx b/frontend/src/stories/cell.stories.tsx
index ad3e90ddbe..20d91eb157 100644
--- a/frontend/src/stories/cell.stories.tsx
+++ b/frontend/src/stories/cell.stories.tsx
@@ -64,6 +64,9 @@ const props: CellProps = {
keymap: {
preset: "default",
},
+ formatting: {
+ line_length: 79,
+ },
experimental: {},
},
};
diff --git a/marimo/_config/config.py b/marimo/_config/config.py
index cff95899bc..91ccd20aaf 100644
--- a/marimo/_config/config.py
+++ b/marimo/_config/config.py
@@ -83,6 +83,17 @@ class DisplayConfig(TypedDict, total=False):
theme: Literal["light", "dark"]
+@mddoc
+class FormattingConfig(TypedDict, total=False):
+ """Configuration for code formatting.
+
+ **Keys.**
+
+ - `line_length`: max line length
+ """
+
+ line_length: int
+
class ServerConfig(TypedDict, total=False):
"""Configuration for the server.
@@ -118,6 +129,7 @@ class MarimoConfig(TypedDict, total=False):
completion: CompletionConfig
display: DisplayConfig
+ formatting: FormattingConfig
keymap: KeymapConfig
runtime: RuntimeConfig
save: SaveConfig
@@ -128,6 +140,7 @@ class MarimoConfig(TypedDict, total=False):
DEFAULT_CONFIG: MarimoConfig = {
"completion": {"activate_on_typing": True, "copilot": False},
"display": {"theme": "light"},
+ "formatting": {"line_length": 79},
"keymap": {"preset": "default"},
"runtime": {"auto_instantiate": True},
"save": {
diff --git a/marimo/_server/api/format.py b/marimo/_server/api/format.py
index 95d7e88562..f3942ad252 100644
--- a/marimo/_server/api/format.py
+++ b/marimo/_server/api/format.py
@@ -17,10 +17,11 @@ LOGGER = _loggers.marimo_logger()
class Format:
# map from cell id to code
codes: Dict[cell.CellId_t, str]
+ line_length: int
class FormatHandler(ValidatedHandler):
- """Save an app to disk."""
+ """Format code."""
@sessions.requires_edit
def post(self) -> None:
@@ -37,7 +38,7 @@ class FormatHandler(ValidatedHandler):
formatted_codes: dict[cell.CellId_t, str] = {}
for key, code in codes.items():
try:
- mode = black.Mode(line_length=79) # type: ignore
+ mode = black.Mode(line_length=args.line_length) # type: ignore
formatted = black.format_str(code, mode=mode)
formatted_codes[key] = formatted.strip()
except Exception: