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: custom_css in pyproject.toml (#4378)
Myles Scolnickc83223734310
diff --git a/marimo/_config/config.py b/marimo/_config/config.pyindex 9781270879..9b68cb67cf 100644--- a/marimo/_config/config.py+++ b/marimo/_config/config.py@@ -155,6 +155,7 @@ class DisplayConfig(TypedDict):- `code_editor_font_size`: font size for the code editor- `cell_output`: `"above"` or `"below"`- `dataframes`: `"rich"` or `"plain"`+ - `custom_css`: list of paths to custom CSS files"""theme: Theme@@ -162,6 +163,7 @@ class DisplayConfig(TypedDict):cell_output: Literal["above", "below"]default_width: WidthTypedataframes: Literal["rich", "plain"]+ custom_css: NotRequired[list[str]]@mddocdiff --git a/marimo/_config/manager.py b/marimo/_config/manager.pyindex ae6e58d2a7..d0822c59ea 100644--- a/marimo/_config/manager.py+++ b/marimo/_config/manager.py@@ -184,6 +184,7 @@ class ProjectConfigManager(PartialMarimoConfigReader):return {}project_config = self._resolve_pythonpath(project_config)project_config = self._resolve_dotenv(project_config)+ project_config = self._resolve_custom_css(project_config)except Exception as e:LOGGER.warning("Failed to read project config: %s", e)return {}@@ -239,6 +240,30 @@ class ProjectConfigManager(PartialMarimoConfigReader):]return {**config, "runtime": {**runtime, "dotenv": resolved_dotenv}}+ def _resolve_custom_css(+ self, config: PartialMarimoConfig+ ) -> PartialMarimoConfig:+ if self.pyproject_path is None:+ return config++ if "display" not in config:+ return config++ display = config["display"]+ custom_css = display.get("custom_css", [])++ if not isinstance(custom_css, list):+ return config++ resolved_custom_css = [+ str((self.pyproject_path.parent / path).absolute())+ for path in custom_css+ ]+ return {+ **config,+ "display": {**display, "custom_css": resolved_custom_css},+ }+class ScriptConfigManager(PartialMarimoConfigReader):"""Read the script configuration following PEP 723diff --git a/marimo/_server/file_manager.py b/marimo/_server/file_manager.pyindex 06c4e84e23..dd18b4d0a6 100644--- a/marimo/_server/file_manager.py+++ b/marimo/_server/file_manager.py@@ -339,13 +339,28 @@ class AppFileManager:def read_css_file(css_file: str, filename: Optional[str]) -> Optional[str]:- if not css_file or not filename:+ """Read the contents of a CSS file.++ Args:+ css_file: The path to the CSS file.+ filename: The filename of the notebook.++ Returns:+ The contents of the CSS file.+ """+ if not css_file:return None- app_dir = Path(filename).parent- filepath = app_dir / css_file+ filepath = Path(css_file)++ # If not an absolute path, make it absolute using the filename+ if not filepath.is_absolute():+ if not filename:+ return None+ filepath = Path(filename).parent / filepath+if not filepath.exists():- LOGGER.error("CSS file %s does not exist", css_file)+ LOGGER.error("CSS file %s does not exist", filepath)return Nonetry:return filepath.read_text(encoding="utf-8")diff --git a/marimo/_server/templates/templates.py b/marimo/_server/templates/templates.pyindex a2b42f16bc..bdbcd49b06 100644--- a/marimo/_server/templates/templates.py+++ b/marimo/_server/templates/templates.py@@ -5,7 +5,7 @@ import base64import jsonimport osfrom textwrap import dedent-from typing import Any, Literal, Optional, cast+from typing import Any, Literal, Optional, Union, castfrom marimo import __version__from marimo._ast.app import _AppConfig@@ -39,6 +39,9 @@ def home_page_template(html = html.replace("{{ filename }}", "")html = html.replace("{{ mode }}", "home")+ # Add custom CSS from display config+ html = _inject_custom_css_for_config(html, user_config)+ html = _inject_custom_css_for_config(html, config_overrides)return html@@ -82,6 +85,10 @@ def notebook_page_template(# Append to headhtml = html.replace("</head>", f"{css_contents}</head>")+ # Add custom CSS from display config+ html = _inject_custom_css_for_config(html, user_config, filename)+ html = _inject_custom_css_for_config(html, config_overrides, filename)+# Add HTML head file contents if specifiedif app_config.html_head_file:head_contents = read_html_head_file(@@ -198,6 +205,14 @@ def static_notebook_template(if css_contents:static_block += _custom_css_block(css_contents)+ # Add custom CSS from display config+ static_block = _inject_custom_css_for_config(+ static_block, user_config, filepath+ )+ static_block = _inject_custom_css_for_config(+ static_block, config_overrides, filepath+ )+code_block = dedent(f"""<marimo-code hidden="">@@ -226,6 +241,8 @@ def static_notebook_template(# Append to bodyhtml = html.replace("</body>", f"{code_block}</body>")+ html = _inject_custom_css_for_config(html, user_config, filepath)+ html = _inject_custom_css_for_config(html, config_overrides, filepath)return html@@ -301,6 +318,10 @@ def wasm_notebook_template(# Append to headbody = body.replace("</head>", f"{css_contents}</head>")+ # Add custom CSS from display config+ body = _inject_custom_css_for_config(body, user_config, filename)+ body = _inject_custom_css_for_config(body, config_overrides, filename)+# Add HTML head file contents if specifiedif app_config.html_head_file:head_contents = read_html_head_file(@@ -358,3 +379,26 @@ def _custom_css_block(css_contents: str) -> str:# marimo-custom is used by the frontend to identify this stylesheet# comes from marimoreturn f"<style title='marimo-custom'>{css_contents}</style>"+++def _inject_custom_css_for_config(+ html: str,+ config: Union[MarimoConfig, PartialMarimoConfig],+ filename: Optional[str] = None,+) -> str:+ """Inject custom CSS from display config into HTML."""+ custom_css = config.get("display", {}).get("custom_css", [])+ if not custom_css:+ return html++ css_contents: list[str] = []+ for css_path in custom_css:+ css_content = read_css_file(css_path, filename=filename)+ if css_content:+ css_contents.append(_custom_css_block(css_content))++ if not css_contents:+ return html++ css_block = "\n".join(css_contents)+ return html.replace("</head>", f"{css_block}</head>")diff --git a/openapi/api.yaml b/openapi/api.yamlindex 1c0c152e19..4bbb82cf7d 100644--- a/openapi/api.yaml+++ b/openapi/api.yaml@@ -1430,6 +1430,10 @@ components:type: stringcode_editor_font_size:type: integer+ custom_css:+ items:+ type: string+ type: arraydataframes:enum:- rich@@ -2479,7 +2483,7 @@ components:type: objectinfo:title: marimo API- version: 0.12.0+ version: 0.12.2openapi: 3.1.0paths:/@file/{filename_and_length}:diff --git a/openapi/src/api.ts b/openapi/src/api.tsindex 990c784f83..c0e27f45a9 100644--- a/openapi/src/api.ts+++ b/openapi/src/api.ts@@ -2932,6 +2932,7 @@ export interface components {/** @enum {string} */cell_output: "above" | "below";code_editor_font_size: number;+ custom_css?: string[];/** @enum {string} */dataframes: "rich" | "plain";/** @enum {string} */diff --git a/tests/_config/test_manager.py b/tests/_config/test_manager.pyindex 579be5ca63..1417d6257c 100644--- a/tests/_config/test_manager.py+++ b/tests/_config/test_manager.py@@ -348,3 +348,44 @@ def test_project_config_manager_resolve_missing_paths(tmp_path: Path) -> None:assert config["runtime"].get("pythonpath", []) == []assert config["runtime"]["dotenv"] == [str(tmp_path / ".env")]assert config["runtime"]["other_setting"] == "value"+++def test_project_config_manager_resolve_custom_css(tmp_path: Path) -> None:+ # Create a pyproject.toml with custom_css paths+ pyproject_path = tmp_path / "pyproject.toml"+ pyproject_content = """+ [tool.marimo.display]+ custom_css = ["styles.css", "themes/dark.css"]+ """+ pyproject_path.write_text(textwrap.dedent(pyproject_content))++ # Initialize ProjectConfigManager+ manager = get_default_config_manager(current_path=str(pyproject_path))+ config = manager.get_config(hide_secrets=False)++ # Verify custom_css paths are resolved correctly+ expected_custom_css = [+ str((tmp_path / "styles.css").absolute()),+ str((tmp_path / "themes" / "dark.css").absolute()),+ ]+ assert config["display"]["custom_css"] == expected_custom_css+++def test_project_config_manager_resolve_invalid_custom_css(+ tmp_path: Path,+) -> None:+ # Create a pyproject.toml with invalid custom_css type+ pyproject_path = tmp_path / "pyproject.toml"+ pyproject_content = """+ [tool.marimo.display]+ custom_css = "not_a_list"+ """+ pyproject_path.write_text(textwrap.dedent(pyproject_content))++ # Initialize ProjectConfigManager+ # Initialize ProjectConfigManager+ manager = get_default_config_manager(current_path=str(pyproject_path))+ config = manager.get_config(hide_secrets=False)++ # Verify invalid custom_css is not modified+ assert config["display"]["custom_css"] == "not_a_list"diff --git a/tests/_server/templates/snapshots/export6.txt b/tests/_server/templates/snapshots/export6.txtnew file mode 100644index 0000000000..ff589a8ec3--- /dev/null+++ b/tests/_server/templates/snapshots/export6.txt@@ -0,0 +1,79 @@+<!DOCTYPE html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <link rel="icon" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/favicon.ico" />+ <!-- Preload is necessary because we show these images when we disconnect from the server,+ but at that point we cannot load these images from the server -->+ <link rel="preload" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/gradient.png"" as="image" />+ <link rel="preload" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/noise.png"" as="image" />+ <!-- Preload the fonts -->+ <link rel="preload" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/Lora-VariableFont_wght.ttf"" as="font" crossorigin="anonymous" />+ <link rel="preload" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/PTSans-Regular.ttf"" as="font" crossorigin="anonymous" />+ <link rel="preload" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/PTSans-Bold.ttf"" as="font" crossorigin="anonymous" />+ <link rel="preload" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/FiraMono-Regular.ttf"" as="font" crossorigin="anonymous" />+ <link rel="preload" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/FiraMono-Medium.ttf"" as="font" crossorigin="anonymous" />+ <link rel="preload" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/FiraMono-Bold.ttf"" as="font" crossorigin="anonymous" />++ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <meta name="theme-color" content="#000000" />+ <meta name="description" content="a marimo app" />+ <link rel="apple-touch-icon" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/apple-touch-icon.png" />+ <link rel="manifest" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/manifest.json" />++ <script data-marimo="true">+ function __resizeIframe(obj) {+ var scrollbarHeight = 20; // Max between windows, mac, and linux++ function setHeight() {+ var element = obj.contentWindow.document.documentElement;+ // If there is no vertical scrollbar, we don't need to resize the iframe+ if (element.scrollHeight === element.clientHeight) {+ return;+ }++ // Create a new height that includes the scrollbar height if it's visible+ var hasHorizontalScrollbar = element.scrollWidth > element.clientWidth;+ var newHeight = element.scrollHeight + (hasHorizontalScrollbar ? scrollbarHeight : 0);++ // Only update the height if it's different from the current height+ if (obj.style.height !== `${newHeight}px`) {+ obj.style.height = `${newHeight}px`;+ }+ }++ // Resize the iframe to the height of the content and bottom scrollbar height+ setHeight();++ // Resize the iframe when the content changes+ const resizeObserver = new ResizeObserver((entries) => {+ setHeight();+ });+ resizeObserver.observe(obj.contentWindow.document.body);+ }+ </script>+ <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, "custom_css": ["custom1.css", "custom2.css"], "dataframes": "rich", "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": true}}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun", "output_max_bytes": 8000000, "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}' data-overrides='{"formatting": {"line_length": 100}}' hidden></marimo-user-config>+ <marimo-app-config data-config='{"width": "compact"}' hidden></marimo-app-config>+ <marimo-server-token data-token='token' hidden></marimo-server-token>+ <title>notebook</title>+ <script type="module" crossorigin crossorigin="anonymous" src="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/index.js""></script>+ <link rel="stylesheet" crossorigin crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/index.css"">++<script data-marimo="true">+ window.__MARIMO_STATIC__ = {};+ window.__MARIMO_STATIC__.version = "0.0.0";+ window.__MARIMO_STATIC__.notebookState = {"cellIds": [], "cellNames": [], "cellCodes": [], "cellConfigs": [], "cellOutputs": {}, "cellConsoleOutputs": {}};+ window.__MARIMO_STATIC__.assetUrl = "https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist";+ window.__MARIMO_STATIC__.files = {};+</script>+<style title='marimo-custom'>/* custom css 1 */</style>+<style title='marimo-custom'>/* custom css 2 */</style></head>+ <body>+ <div id="root"></div>+ <marimo-code hidden=""></marimo-code>+<marimo-code-hash hidden="">2b33215fadf3c54926d5c4100348afc158dbff4c94b15044e3a7fe804f80ed2d</marimo-code-hash>+</body>+</html>diff --git a/tests/_server/templates/test_templates.py b/tests/_server/templates/test_templates.pyindex 7e6c1af617..92a1ac984d 100644--- a/tests/_server/templates/test_templates.py+++ b/tests/_server/templates/test_templates.py@@ -146,6 +146,104 @@ class TestNotebookPageTemplate(unittest.TestCase):assert head in result+ def test_notebook_page_template_with_custom_css_config(self) -> None:+ # Create CSS files+ css1 = "/* custom css 1 */"+ css2 = "/* custom css 2 */"++ css_file1 = self.filename.parent / "custom1.css"+ css_file2 = self.filename.parent / "custom2.css"+ css_file1.write_text(css1)+ css_file2.write_text(css2)++ # Update config with custom CSS paths+ config = merge_default_config(self.user_config)+ config["display"]["custom_css"] = ["custom1.css", "custom2.css"]++ result = templates.notebook_page_template(+ self.html,+ self.base_url,+ config,+ self.config_overrides,+ self.server_token,+ self.app_config,+ str(self.filename),+ self.mode,+ )++ assert css1 in result+ assert css2 in result+ assert "<style title='marimo-custom'>" in result++ def test_notebook_page_template_with_absolute_custom_css(self) -> None:+ # Create CSS file with absolute path+ css = "/* absolute path css */"+ css_file = self.filename.parent / "absolute.css"+ css_file.write_text(css)++ # Update config with absolute CSS path+ config = merge_default_config(self.user_config)+ config["display"]["custom_css"] = [str(css_file)]++ result = templates.notebook_page_template(+ self.html,+ self.base_url,+ config,+ self.config_overrides,+ self.server_token,+ self.app_config,+ str(self.filename),+ self.mode,+ )++ assert css in result+ assert "<style title='marimo-custom'>" in result++ def test_notebook_page_template_with_config_overrides_custom_css(+ self,+ ) -> None:+ # Create CSS files+ css1 = "/* config override css */"+ css_file1 = self.filename.parent / "override.css"+ css_file1.write_text(css1)++ # Update config_overrides with custom CSS path+ config_overrides = self.config_overrides.copy()+ config_overrides["display"] = {"custom_css": ["override.css"]}++ result = templates.notebook_page_template(+ self.html,+ self.base_url,+ self.user_config,+ config_overrides,+ self.server_token,+ self.app_config,+ str(self.filename),+ self.mode,+ )++ assert css1 in result+ assert "<style title='marimo-custom'>" in result++ def test_notebook_page_template_with_nonexistent_custom_css(self) -> None:+ # Update config with nonexistent CSS path+ config = merge_default_config(self.user_config)+ config["display"]["custom_css"] = ["nonexistent.css"]++ result = templates.notebook_page_template(+ self.html,+ self.base_url,+ config,+ self.config_overrides,+ self.server_token,+ self.app_config,+ str(self.filename),+ self.mode,+ )++ assert "nonexistent.css" in result+ assert "<style title='marimo-custom'>" not in result+class TestHomePageTemplate(unittest.TestCase):def setUp(self) -> None:@@ -360,6 +458,102 @@ class TestStaticNotebookTemplate(unittest.TestCase):snapshot("export5.txt", normalize_index_html(result))+ def test_static_notebook_template_with_custom_css_config(self) -> None:+ # Create CSS files+ css1 = "/* custom css 1 */"+ css2 = "/* custom css 2 */"++ css_file1 = self.filename.parent / "custom1.css"+ css_file2 = self.filename.parent / "custom2.css"+ css_file1.write_text(css1)+ css_file2.write_text(css2)++ # Update config with custom CSS paths+ config = merge_default_config(self.user_config)+ config["display"]["custom_css"] = ["custom1.css", "custom2.css"]++ result = templates.static_notebook_template(+ self.html,+ config,+ self.config_overrides,+ self.server_token,+ self.app_config,+ str(self.filename),+ "",+ hash_code(self.code),+ [],+ [],+ [],+ [],+ {},+ {},+ {},+ )++ assert css1 in result+ assert css2 in result+ assert "<style title='marimo-custom'>" in result+ snapshot("export6.txt", normalize_index_html(result))++ def test_static_notebook_template_with_absolute_custom_css(self) -> None:+ # Create CSS file with absolute path+ css = "/* absolute path css */"+ css_file = self.filename.parent / "absolute.css"+ css_file.write_text(css)++ # Update config with absolute CSS path+ config = merge_default_config(self.user_config)+ config["display"]["custom_css"] = [str(css_file)]++ result = templates.static_notebook_template(+ self.html,+ config,+ self.config_overrides,+ self.server_token,+ self.app_config,+ str(self.filename),+ "",+ hash_code(self.code),+ [],+ [],+ [],+ [],+ {},+ {},+ {},+ )++ assert css in result+ assert "<style title='marimo-custom'>" in result++ def test_static_notebook_template_with_nonexistent_custom_css(+ self,+ ) -> None:+ # Update config with nonexistent CSS path+ config = merge_default_config(self.user_config)+ config["display"]["custom_css"] = ["nonexistent.css"]++ result = templates.static_notebook_template(+ self.html,+ config,+ self.config_overrides,+ self.server_token,+ self.app_config,+ str(self.filename),+ "",+ hash_code(self.code),+ [],+ [],+ [],+ [],+ {},+ {},+ {},+ )++ assert "nonexistent.css" in result+ assert "<style title='marimo-custom'>" not in result+class TestWasmNotebookTemplate(unittest.TestCase):def setUp(self) -> None: