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: mo.ui.code_editor (#531)

Myles Scolnickbe758a1a94dd
diff --git a/docs/api/inputs/code_editor.md b/docs/api/inputs/code_editor.md
new file mode 100644
index 0000000000..29ce139433
--- /dev/null
+++ b/docs/api/inputs/code_editor.md
@@ -0,0 +1,10 @@
+# Code Editor
+
+<!-- <iframe class="demo" src="https://components.marimo.io/?component=code_editor" frameborder="no"></iframe> -->
+
+```{eval-rst}
+.. autoclass:: marimo.ui.code_editor
+ :members:
+
+ .. autoclasstoc:: marimo._plugins.ui._impl.input.code_editor
+```
diff --git a/docs/api/inputs/index.md b/docs/api/inputs/index.md
index bfa180cbbe..51beb138b3 100644
--- a/docs/api/inputs/index.md
+++ b/docs/api/inputs/index.md
@@ -10,6 +10,7 @@
button
checkbox
chart
+ code_editor
dataframe
date
dictionary
@@ -40,6 +41,7 @@ powerful notebooks and apps. These elements are available in `marimo.ui`.
marimo.ui.button
marimo.ui.checkbox
marimo.ui.chart
+ marimo.ui.code_editor
marimo.ui.dataframe
marimo.ui.date
marimo.ui.dictionary
diff --git a/frontend/package.json b/frontend/package.json
index 0fb1b527d9..d9dce5a388 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -16,8 +16,8 @@
"@codemirror/commands": "^6.3.3",
"@codemirror/lang-markdown": "^6.2.3",
"@codemirror/lang-python": "^6.1.3",
- "@codemirror/language-data": "^6.3.1",
"@codemirror/language": "^6.10.0",
+ "@codemirror/language-data": "^6.3.1",
"@codemirror/lint": "^6.4.2",
"@codemirror/search": "^6.5.5",
"@codemirror/state": "^6.4.0",
@@ -64,6 +64,7 @@
"@types/js-cookie": "^3.0.6",
"@types/jsdom": "^21.1.6",
"@types/react-grid-layout": "^1.3.5",
+ "@uiw/codemirror-extensions-langs": "^4.21.21",
"@uiw/react-codemirror": "^4.21.21",
"blob-polyfill": "^7.0.20220408",
"class-variance-authority": "^0.7.0",
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index 8f4c53fa34..d192495a53 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -161,6 +161,9 @@ dependencies:
'@types/react-grid-layout':
specifier: ^1.3.5
version: 1.3.5
+ '@uiw/codemirror-extensions-langs':
+ specifier: ^4.21.21
+ version: 4.21.21(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])
'@uiw/react-codemirror':
specifier: ^4.21.21
@@ -2054,6 +2057,25 @@ packages:
- '@codemirror/view'
dev: false
+ /@codemirror/[email protected]:
+ resolution: {integrity: sha512-WHwjI7OqKFBEfkunohweqA5B/jIlxaZso6Nl3weVckz8EafYbPZldQEKSDb4QQ9H9BUkle4PVELP4sftKoA0uQ==}
+ dependencies:
+ '@codemirror/language': 6.10.0
+ '@codemirror/state': 6.4.0
+ '@lezer/common': 1.2.0
+ '@lezer/lezer': 1.1.2
+ dev: false
+
+ /@codemirror/[email protected]:
+ resolution: {integrity: sha512-DRmtaBHtAP63I5IDa1OEk00oh3NsR7DFGkvFmLc9ODqdy2uEGkcjNn+QqgbLuy3zSjQcl5cdiX2FSjOXzPx5BA==}
+ dependencies:
+ '@codemirror/lang-html': 6.4.7
+ '@codemirror/language': 6.10.0
+ '@lezer/common': 1.2.0
+ '@lezer/highlight': 1.2.0
+ '@lezer/lr': 1.3.14
+ dev: false
+
/@codemirror/[email protected]:
resolution: {integrity: sha512-wCewRLWpdefWi7uVkHIDiE8+45Fe4buvMDZkihqEom5uRUQrl76Zb13emjeK3W+8pcRgRfAmwelURBbxNEKCIg==}
dependencies:
@@ -3091,6 +3113,13 @@ packages:
'@lezer/lr': 1.3.14
dev: false
+ resolution: {integrity: sha512-O8yw3CxPhzYHB1hvwbdozjnAslhhR8A5BH7vfEMof0xk3p+/DFDfZkA9Tde6J+88WgtwaHy4Sy6ThZSkaI0Evw==}
+ dependencies:
+ '@lezer/highlight': 1.2.0
+ '@lezer/lr': 1.3.14
+ dev: false
+
resolution: {integrity: sha512-z5mY4LStlA3yL7aHT/rqgG614cfcvklS+8oFRFBYrs4YaWLJyKKM4+nN6KopToX0o9Hj6zmH6M5kinOYuy06ug==}
dependencies:
@@ -3387,6 +3416,19 @@ packages:
tar-fs: 2.1.1
dev: true
+ /@nextjournal/[email protected]:
+ resolution: {integrity: sha512-gOCV71XrYD0DhwGoPMWZmZ0r92/lIHsqQu9QWdpZYYBwiChNwMO4sbVMP7eTuAqffFB2BTtCSC+1skSH9d3bNg==}
+ dependencies:
+ '@codemirror/language': 6.10.0
+ '@nextjournal/lezer-clojure': 1.0.0
+ dev: false
+
+ /@nextjournal/[email protected]:
+ resolution: {integrity: sha512-VZyuGu4zw5mkTOwQBTaGVNWmsOZAPw5ZRxu1/Knk/Xfs7EDBIogwIs5UXTYkuECX5ZQB8eOB+wKA2pc7VyqaZQ==}
+ dependencies:
+ '@lezer/lr': 1.3.14
+ dev: false
+
/@nodelib/[email protected]:
resolution: {integrity: sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==}
engines: {node: '>= 8'}
@@ -5066,6 +5108,82 @@ packages:
- immer
dev: false
+ resolution: {integrity: sha512-6utbaWkoymhoAXj051mkRp+VIJlpwUgCX9Toevz3YatiZsz512fw3OVCedXQx+WcR0wb6zVHjChnuxqfCLtFVQ==}
+ peerDependencies:
+ '@codemirror/autocomplete': ^6.0.0
+ '@codemirror/language': ^6.0.0
+ '@codemirror/state': ^6.0.0
+ '@codemirror/view': ^6.0.0
+ '@lezer/common': ^1.0.0
+ '@lezer/highlight': ^1.0.0
+ '@lezer/lr': ^1.0.0
+ dependencies:
+ '@codemirror/autocomplete': 6.11.1(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])
+ '@codemirror/language': 6.10.0
+ '@codemirror/state': 6.4.0
+ '@codemirror/view': 6.23.0
+ '@lezer/common': 1.2.0
+ '@lezer/highlight': 1.2.0
+ '@lezer/lr': 1.3.14
+ dev: false
+
+ resolution: {integrity: sha512-lvzjoYn9nfJzBD5qdm3Ut6G3+Or2wEacYIDJ49h9+19WSChVnxv4ojf+rNmQ78ncuxIt/bfbMvDLMeMP0xze6g==}
+ peerDependencies:
+ '@codemirror/autocomplete': ^6.0.0
+ '@codemirror/language': ^6.0.0
+ '@codemirror/state': ^6.0.0
+ '@codemirror/view': ^6.0.0
+ '@lezer/common': ^1.0.0
+ '@lezer/highlight': ^1.0.0
+ '@lezer/lr': ^1.0.0
+ dependencies:
+ '@codemirror/autocomplete': 6.11.1(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])
+ '@codemirror/language': 6.10.0
+ '@codemirror/state': 6.4.0
+ '@codemirror/view': 6.23.0
+ '@lezer/common': 1.2.0
+ '@lezer/highlight': 1.2.0
+ '@lezer/lr': 1.3.14
+ dev: false
+
+ /@replit/[email protected](@codemirror/[email protected]):
+ resolution: {integrity: sha512-kDnak0xZelGmvzJwKTpMTl6gYSfFq9hnxrkbLaMV0CARq/MFvDQJmcmYon/k8uZqXy6DfzewKDV8tx9kY2WUZg==}
+ peerDependencies:
+ '@codemirror/language': ^6.0.0
+ dependencies:
+ '@codemirror/language': 6.10.0
+ dev: false
+
+ /@replit/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected]):
+ resolution: {integrity: sha512-U2OqqgMM6jKelL0GNWbAmqlu1S078zZNoBqlJBW+retTc5M4Mha6/Y2cf4SVg6ddgloJvmcSpt4hHrVoM4ePRA==}
+ peerDependencies:
+ '@codemirror/autocomplete': ^6.0.0
+ '@codemirror/lang-css': ^6.0.1
+ '@codemirror/lang-html': ^6.2.0
+ '@codemirror/lang-javascript': ^6.1.1
+ '@codemirror/language': ^6.0.0
+ '@codemirror/state': ^6.0.0
+ '@codemirror/view': ^6.0.0
+ '@lezer/common': ^1.0.0
+ '@lezer/highlight': ^1.0.0
+ '@lezer/javascript': ^1.2.0
+ '@lezer/lr': ^1.0.0
+ dependencies:
+ '@codemirror/autocomplete': 6.11.1(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])
+ '@codemirror/lang-css': 6.2.1(@codemirror/[email protected])
+ '@codemirror/lang-html': 6.4.7
+ '@codemirror/lang-javascript': 6.2.1
+ '@codemirror/language': 6.10.0
+ '@codemirror/state': 6.4.0
+ '@codemirror/view': 6.23.0
+ '@lezer/common': 1.2.0
+ '@lezer/highlight': 1.2.0
+ '@lezer/javascript': 1.4.9
+ '@lezer/lr': 1.3.14
+ dev: false
+
/@replit/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected]):
resolution: {integrity: sha512-XATcrMBYphSgTTDHaL5cTdBKA+/kwg8x0kHpX9xFHkI8c2G9+nXdkIzFCtk76x1VDYQSlT6orNhudNt+9H9zOA==}
peerDependencies:
@@ -7078,6 +7196,50 @@ packages:
'@codemirror/view': 6.23.0
dev: false
+ resolution: {integrity: sha512-h08pw2NeGLDgBiY8Ju5GNjfVzq1f6+wc0uPdqN5tkYBaKmByyKI10l5Gds7wBPzFH0uZlevP+Jyf9oSTcula5Q==}
+ peerDependencies:
+ '@codemirror/language-data': '>=6.0.0'
+ '@codemirror/legacy-modes': '>=6.0.0'
+ dependencies:
+ '@codemirror/lang-angular': 0.1.2
+ '@codemirror/lang-cpp': 6.0.2
+ '@codemirror/lang-css': 6.2.1(@codemirror/[email protected])
+ '@codemirror/lang-html': 6.4.7
+ '@codemirror/lang-java': 6.0.1
+ '@codemirror/lang-javascript': 6.2.1
+ '@codemirror/lang-json': 6.0.1
+ '@codemirror/lang-less': 6.0.1(@codemirror/[email protected])
+ '@codemirror/lang-lezer': 6.0.1
+ '@codemirror/lang-liquid': 6.2.0
+ '@codemirror/lang-markdown': 6.2.3
+ '@codemirror/lang-php': 6.0.1
+ '@codemirror/lang-python': 6.1.3(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])
+ '@codemirror/lang-rust': 6.0.1
+ '@codemirror/lang-sass': 6.0.2(@codemirror/[email protected])
+ '@codemirror/lang-sql': 6.5.4(@codemirror/[email protected])(@lezer/[email protected])
+ '@codemirror/lang-vue': 0.1.2
+ '@codemirror/lang-wast': 6.0.1
+ '@codemirror/lang-xml': 6.0.2(@codemirror/[email protected])
+ '@codemirror/language-data': 6.3.1(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])
+ '@codemirror/legacy-modes': 6.3.3
+ '@nextjournal/lang-clojure': 1.0.0
+ '@replit/codemirror-lang-csharp': 6.2.0(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])
+ '@replit/codemirror-lang-nix': 6.0.1(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])
+ '@replit/codemirror-lang-solidity': 6.0.1(@codemirror/[email protected])
+ '@replit/codemirror-lang-svelte': 6.0.0(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])
+ codemirror-lang-mermaid: 0.5.0
+ transitivePeerDependencies:
+ - '@codemirror/autocomplete'
+ - '@codemirror/language'
+ - '@codemirror/state'
+ - '@codemirror/view'
+ - '@lezer/common'
+ - '@lezer/highlight'
+ - '@lezer/javascript'
+ - '@lezer/lr'
+ dev: false
+
resolution: {integrity: sha512-PaxBMarufMWoR0qc5zuvBSt76rJ9POm9qoOaJbqRmnNL2viaF+d+Paf2blPSlm1JSnqn7hlRjio+40nZJ9TKzw==}
peerDependencies:
@@ -8234,6 +8396,14 @@ packages:
'@codemirror/view': 6.23.0
dev: false
+ resolution: {integrity: sha512-Taw/2gPCyNArQJCxIP/HSUif+3zrvD+6Ugt7KJZ2dUKou/8r3ZhcfG8krNTZfV2iu8AuGnymKuo7bLPFyqsh/A==}
+ dependencies:
+ '@codemirror/language': 6.10.0
+ '@lezer/highlight': 1.2.0
+ '@lezer/lr': 1.3.14
+ dev: false
+
resolution: {integrity: sha512-QtFEMc1yhi8wzKasE+OseMeikHpHdFt1wQdt5F4O3sKl7B1m56OcVuqmCAJipklbIPDkLecaXhd8oFvA72lfnw==}
dependencies:
diff --git a/frontend/src/plugins/impl/CodeEditorPlugin.tsx b/frontend/src/plugins/impl/CodeEditorPlugin.tsx
new file mode 100644
index 0000000000..4fcd7b2d9d
--- /dev/null
+++ b/frontend/src/plugins/impl/CodeEditorPlugin.tsx
@@ -0,0 +1,71 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import { z } from "zod";
+import { IPlugin, IPluginProps, Setter } from "../types";
+
+import { Labeled } from "./common/labeled";
+import { Theme, getTheme } from "@/theme/useTheme";
+import { lazy } from "react";
+
+type T = string;
+
+interface Data {
+ language: string;
+ placeholder: string;
+ theme: Theme;
+ label: string | null;
+ disabled?: boolean;
+ minHeight?: number;
+}
+
+export class CodeEditorPlugin implements IPlugin<T, Data> {
+ tagName = "marimo-code-editor";
+
+ validator = z.object({
+ initialValue: z.string(),
+ language: z.string().default("python"),
+ placeholder: z.string(),
+ theme: z.enum(["light", "dark"]).default("light"),
+ label: z.string().nullable(),
+ disabled: z.boolean().optional(),
+ minHeight: z.number().optional(),
+ });
+
+ render(props: IPluginProps<T, Data>): JSX.Element {
+ return (
+ <CodeEditorComponent
+ {...props.data}
+ value={props.value}
+ setValue={props.setValue}
+ />
+ );
+ }
+}
+
+const LazyAnyLanguageCodeMirror = lazy(
+ () => import("./code/any-language-editor")
+);
+
+interface CodeEditorComponentProps extends Data {
+ value: T;
+ setValue: Setter<T>;
+}
+
+const CodeEditorComponent = (props: CodeEditorComponentProps) => {
+ const theme = props.theme || getTheme();
+ const minHeight = props.minHeight ? `${props.minHeight}px` : "70px";
+
+ return (
+ <Labeled label={props.label} align="top">
+ <LazyAnyLanguageCodeMirror
+ className={`cm [&>*]:outline-none border rounded overflow-hidden ${theme}`}
+ theme={theme === "dark" ? "dark" : "light"}
+ minHeight={minHeight}
+ placeholder={props.placeholder}
+ editable={!props.disabled}
+ value={props.value}
+ language={props.language}
+ onChange={(value) => props.setValue(value)}
+ />
+ </Labeled>
+ );
+};
diff --git a/frontend/src/plugins/impl/code/any-language-editor.tsx b/frontend/src/plugins/impl/code/any-language-editor.tsx
new file mode 100644
index 0000000000..b49f597c24
--- /dev/null
+++ b/frontend/src/plugins/impl/code/any-language-editor.tsx
@@ -0,0 +1,49 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import ReactCodeMirror, { ReactCodeMirrorProps } from "@uiw/react-codemirror";
+import {
+ loadLanguage,
+ langs,
+ LanguageName,
+} from "@uiw/codemirror-extensions-langs";
+import React from "react";
+import { Logger } from "@/utils/Logger";
+import { ErrorBanner } from "../common/error-banner";
+
+/**
+ * A code editor that supports any language.
+ *
+ * This lives in a separate file because we want to lazy load the additional
+ * language support.
+ */
+const AnyLanguageCodeMirror: React.FC<
+ ReactCodeMirrorProps & {
+ language: string;
+ }
+> = ({ language, extensions = [], ...props }) => {
+ const isNotSupported = !(language in langs);
+ if (isNotSupported) {
+ Logger.warn(`Language ${language} not found in CodeMirror.`);
+ }
+
+ return (
+ <>
+ {isNotSupported && (
+ <ErrorBanner
+ className="mb-1 rounded-sm"
+ error={`Language ${language} not supported. \n\nSupported languages are: ${Object.keys(
+ langs
+ ).join(", ")}`}
+ />
+ )}
+ <ReactCodeMirror
+ {...props}
+ extensions={[
+ loadLanguage(language as LanguageName),
+ ...extensions,
+ ].filter(Boolean)}
+ />
+ </>
+ );
+};
+
+export default AnyLanguageCodeMirror;
diff --git a/frontend/src/plugins/impl/common/error-banner.tsx b/frontend/src/plugins/impl/common/error-banner.tsx
new file mode 100644
index 0000000000..33fd319e8b
--- /dev/null
+++ b/frontend/src/plugins/impl/common/error-banner.tsx
@@ -0,0 +1,55 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import { prettyError } from "@/utils/errors";
+import { useState } from "react";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogContent,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@/components/ui/alert-dialog";
+import { cn } from "@/utils/cn";
+
+export const ErrorBanner = ({
+ error,
+ className,
+}: {
+ error: Error | string;
+ className?: string;
+}) => {
+ const [open, setOpen] = useState(false);
+
+ if (!error) {
+ return null;
+ }
+
+ const message = prettyError(error);
+
+ return (
+ <>
+ <div
+ className={cn(
+ "text-error border-[var(--red-6)] bg-[var(--red-2)] text-sm p-2 border cursor-pointer hover:bg-[var(--red-3)] whitespace-pre-wrap",
+ className
+ )}
+ onClick={() => setOpen(true)}
+ >
+ <span className="line-clamp-4">{message}</span>
+ </div>
+ <AlertDialog open={open} onOpenChange={setOpen}>
+ <AlertDialogContent className="max-w-[80%]">
+ <AlertDialogHeader>
+ <AlertDialogTitle className="text-error">Error</AlertDialogTitle>
+ </AlertDialogHeader>
+ <div className="text-error text-sm p-2 font-mono">{message}</div>
+ <AlertDialogFooter>
+ <AlertDialogAction autoFocus={true} onClick={() => setOpen(false)}>
+ Ok
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </>
+ );
+};
diff --git a/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx b/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx
index 9718f1f9a0..38f1e1357a 100644
--- a/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx
+++ b/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx
@@ -13,17 +13,9 @@ import { useAsyncData } from "@/hooks/useAsyncData";
import { LoadingDataTableComponent } from "../DataTablePlugin";
import { Functions } from "@/utils/functions";
import { Arrays } from "@/utils/arrays";
-import { prettyError } from "@/utils/errors";
import { useState } from "react";
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogContent,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
-} from "@/components/ui/alert-dialog";
import { TooltipProvider } from "@/components/ui/tooltip";
+import { ErrorBanner } from "../common/error-banner";
/**
* Arguments for a data table
@@ -169,37 +161,3 @@ export const DataFrameComponent = ({
</div>
);
};
-
-const ErrorBanner = ({ error }: { error: Error }) => {
- const [open, setOpen] = useState(false);
-
- if (!error) {
- return null;
- }
-
- const message = prettyError(error);
-
- return (
- <>
- <div
- className="text-error border-[var(--red-6)] bg-[var(--red-2)] text-sm p-2 border cursor-pointer hover:bg-[var(--red-3)]"
- onClick={() => setOpen(true)}
- >
- <span className="line-clamp-4">{message}</span>
- </div>
- <AlertDialog open={open} onOpenChange={setOpen}>
- <AlertDialogContent className="max-w-[80%]">
- <AlertDialogHeader>
- <AlertDialogTitle className="text-error">Error</AlertDialogTitle>
- </AlertDialogHeader>
- <div className="text-error text-sm p-2 font-mono">{message}</div>
- <AlertDialogFooter>
- <AlertDialogAction autoFocus={true} onClick={() => setOpen(false)}>
- Ok
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- </>
- );
-};
diff --git a/frontend/src/plugins/impl/data-frames/python/code-panel.tsx b/frontend/src/plugins/impl/data-frames/python/code-panel.tsx
index ece7fe6804..5f6cd5c7e5 100644
--- a/frontend/src/plugins/impl/data-frames/python/code-panel.tsx
+++ b/frontend/src/plugins/impl/data-frames/python/code-panel.tsx
@@ -16,8 +16,8 @@ export const CodePanel: React.FC<Props> = ({ transforms, dataframeName }) => {
return (
<ReadonlyPythonCode
- className="min-h-[200px]"
- minHeight="200px"
+ minHeight="215px"
+ maxHeight="215px"
code={pythonPrintTransforms(dataframeName, transforms.transforms)}
/>
);
diff --git a/frontend/src/plugins/plugins.ts b/frontend/src/plugins/plugins.ts
index d7902a4558..45e77b59ef 100644
--- a/frontend/src/plugins/plugins.ts
+++ b/frontend/src/plugins/plugins.ts
@@ -32,6 +32,7 @@ import { VegaPlugin } from "./impl/vega/VegaPlugin";
import { StatPlugin } from "./layout/StatPlugin";
import { DataFramePlugin } from "./impl/data-frames/DataFramePlugin";
import { PlotlyPlugin } from "./impl/plotly/PlotlyPlugin";
+import { CodeEditorPlugin } from "./impl/CodeEditorPlugin";
// List of UI plugins
export const UI_PLUGINS: Array<IPlugin<any, unknown>> = [
@@ -40,6 +41,7 @@ export const UI_PLUGINS: Array<IPlugin<any, unknown>> = [
DataTablePlugin,
new DatePickerPlugin(),
new DictPlugin(),
+ new CodeEditorPlugin(),
new DropdownPlugin(),
new FileUploadPlugin(),
new FormPlugin(),
diff --git a/frontend/src/utils/errors.ts b/frontend/src/utils/errors.ts
index 193ca9157b..f39d59a834 100644
--- a/frontend/src/utils/errors.ts
+++ b/frontend/src/utils/errors.ts
@@ -1,6 +1,9 @@
/* Copyright 2023 Marimo. All rights reserved. */
export function prettyError(error: unknown) {
+ if (typeof error === "string") {
+ return error;
+ }
if (error instanceof Error) {
return error.message;
}
diff --git a/marimo/_plugins/ui/__init__.py b/marimo/_plugins/ui/__init__.py
index a903b70c43..dbaaa06b4d 100644
--- a/marimo/_plugins/ui/__init__.py
+++ b/marimo/_plugins/ui/__init__.py
@@ -10,6 +10,7 @@ __all__ = [
"batch",
"button",
"checkbox",
+ "code_editor",
"date",
"dataframe",
"dictionary",
@@ -38,6 +39,7 @@ from marimo._plugins.ui._impl.dictionary import dictionary
from marimo._plugins.ui._impl.input import (
button,
checkbox,
+ code_editor,
date,
dropdown,
file,
diff --git a/marimo/_plugins/ui/_impl/input.py b/marimo/_plugins/ui/_impl/input.py
index addcc1906b..1befaf87c0 100644
--- a/marimo/_plugins/ui/_impl/input.py
+++ b/marimo/_plugins/ui/_impl/input.py
@@ -429,6 +429,67 @@ class text_area(UIElement[str, str]):
return value
+@mddoc
+class code_editor(UIElement[str, str]):
+ """
+ A code editor.
+
+ **Example.**
+
+ ```python
+ code_editor = mo.ui.code_editor()
+ ```
+
+ **Attributes.**
+
+ - `value`: a string of the code editor contents
+
+ **Initialization Args.**
+
+ - `value`: initial value of the code editor
+ - `language`: language of the code editor, defaults to `"python"`; most
+ major languages are supported, including "sql", "javascript",
+ "typescript", "html", "css", "c", "cpp", "rust", and more
+ - `placeholder`: placeholder text to display when the code editor is empty
+ - `theme`: theme of the code editor, defaults to `"light"`
+ - `disabled`: whether the input is disabled
+ - `min_height`: minimum height of the code editor in pixels
+ - `label`: text label for the element
+ - `on_change`: optional callback to run when this element's value changes
+ """
+
+ _name: Final[str] = "marimo-code-editor"
+
+ def __init__(
+ self,
+ value: str = "",
+ language: str = "python",
+ placeholder: str = "",
+ theme: Literal["light", "dark"] = "light",
+ disabled: bool = False,
+ min_height: Optional[int] = None,
+ *,
+ label: str = "",
+ on_change: Optional[Callable[[str], None]] = None,
+ ) -> None:
+ super().__init__(
+ component_name=code_editor._name,
+ initial_value=value,
+ label=label,
+ args={
+ "language": language,
+ "placeholder": placeholder,
+ "theme": theme,
+ "disabled": disabled,
+ "min-height": min_height,
+ },
+ on_change=on_change,
+ )
+
+ def _convert_value(self, value: str) -> str:
+ return value
+
+
@mddoc
class dropdown(UIElement[List[str], Any]):
"""
diff --git a/marimo/_smoke_tests/code_editor.py b/marimo/_smoke_tests/code_editor.py
new file mode 100644
index 0000000000..3a054f9282
--- /dev/null
+++ b/marimo/_smoke_tests/code_editor.py
@@ -0,0 +1,66 @@
+import marimo
+
+__generated_with = "0.1.73"
+app = marimo.App()
+
+
+def __(mo):
+ mo.ui.code_editor("print(2 + 2)", min_height=50)
+ return
+
+
+def __(mo):
+ mo.ui.code_editor("SELECT * FROM table;", language="sql")
+ return
+
+
[email protected](hide_code=True)
+def __(languages, mo):
+ language_select = mo.ui.dropdown(
+ languages,
+ value="javascript",
+ label="Language",
+ full_width=True,
+ )
+ theme_select = mo.ui.radio(["light", "dark"], value="dark", label="Theme")
+ mo.hstack([language_select, theme_select], justify="start", gap=2)
+ return language_select, theme_select
+
+
+def __(language_select, mo, samples, theme_select):
+ mo.ui.code_editor(
+ samples[language_select.value],
+ language=language_select.value,
+ theme=theme_select.value,
+ )
+ return
+
+
+def __():
+ languages = ["sql", "python", "javascript", "ruby", "c", "java", "go"]
+ samples = {
+ "sql": "SELECT * FROM table;",
+ "python": "print(2 + 2)",
+ "javascript": "console.log(2 + 2)",
+ "ruby": "puts 2 + 2",
+ "c": 'printf("%d", 2 + 2);',
+ "c++": "cout << 2 + 2 << endl;",
+ "c#": "Console.WriteLine(2 + 2);",
+ "java": "System.out.println(2 + 2);",
+ "go": "fmt.Println(2 + 2)",
+ }
+ return languages, samples
+
+
+def __():
+ import marimo as mo
+ return mo,
+
+
+if __name__ == "__main__":
+ app.run()