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
improvement: 'open in editor' via file-explorer (#3766)
Myles Scolnickd7f0aa3a60dd
diff --git a/frontend/src/components/editor/file-tree/file-explorer.tsx b/frontend/src/components/editor/file-tree/file-explorer.tsxindex d59ace6f00..75c44c8ec7 100644--- a/frontend/src/components/editor/file-tree/file-explorer.tsx+++ b/frontend/src/components/editor/file-tree/file-explorer.tsx@@ -65,7 +65,7 @@ import type { RequestingTree } from "./requesting-tree";import type { FilePath } from "@/utils/paths";import useEvent from "react-use-event-hook";import { copyToClipboard } from "@/utils/copy";-import { sendFileDetails } from "@/core/network/requests";+import { openFile, sendFileDetails } from "@/core/network/requests";import { downloadBlob } from "@/utils/download";const RequestingTreeContext = React.createContext<RequestingTree | null>(null);@@ -430,6 +430,16 @@ const Node = ({ node, style, dragHandle }: NodeRendererProps<FileInfo>) => {Open file</DropdownMenuItem>)}+ {!node.data.isDirectory && !isWasm() && (+ <DropdownMenuItem+ onSelect={() => {+ openFile({ path: node.data.path });+ }}+ >+ <ExternalLinkIcon {...iconProps} />+ Open file in external editor+ </DropdownMenuItem>+ )}{node.data.isDirectory && (<><DropdownMenuItem onSelect={() => handleCreateFile()}>diff --git a/frontend/src/core/network/requests-network.ts b/frontend/src/core/network/requests-network.tsindex 12c24c52d8..cd9e8c37d1 100644--- a/frontend/src/core/network/requests-network.ts+++ b/frontend/src/core/network/requests-network.ts@@ -1,5 +1,4 @@/* Copyright 2024 Marimo. All rights reserved. */-import { reloadSafe } from "@/utils/reload-safe";import { API, marimoClient } from "./api";import type { RunRequests, EditRequests } from "./types";@@ -161,14 +160,10 @@ export function createNetworkRequests(): EditRequests & RunRequests {},openFile: async (request) => {await marimoClient- .POST("/api/kernel/open", {+ .POST("/api/files/open", {body: request,}).then(handleResponseReturnNull);- await marimoClient- .POST("/api/kernel/restart_session")- .then(handleResponseReturnNull);- reloadSafe();return null;},getUsageStats: () => {diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.tsindex 4d25a392cc..ca01a2c5f9 100644--- a/frontend/src/core/network/types.ts+++ b/frontend/src/core/network/types.ts@@ -49,7 +49,6 @@ export type PackageOperationResponse = schemas["PackageOperationResponse"];export type InstantiateRequest = schemas["InstantiateRequest"];export type MarimoConfig = schemas["MarimoConfig"];export type MarimoFile = schemas["MarimoFile"];-export type OpenFileRequest = schemas["OpenFileRequest"];export type PreviewDatasetColumnRequest =schemas["PreviewDatasetColumnRequest"];export type ReadCodeResponse = schemas["ReadCodeResponse"];diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.pyindex 67f173fb65..91e4f18763 100644--- a/marimo/_cli/development/commands.py+++ b/marimo/_cli/development/commands.py@@ -134,6 +134,7 @@ def _generate_schema() -> dict[str, Any]:files.FileListResponse,files.FileMoveRequest,files.FileMoveResponse,+ files.FileOpenRequest,files.FileUpdateRequest,files.FileUpdateResponse,packages.AddPackageRequest,@@ -151,7 +152,6 @@ def _generate_schema() -> dict[str, Any]:models.FormatRequest,models.FormatResponse,models.InstantiateRequest,- models.OpenFileRequest,models.ReadCodeResponse,models.RenameFileRequest,models.RunRequest,diff --git a/marimo/_server/api/endpoints/file_explorer.py b/marimo/_server/api/endpoints/file_explorer.pyindex dff8525dd0..7f7f9d5eee 100644--- a/marimo/_server/api/endpoints/file_explorer.py+++ b/marimo/_server/api/endpoints/file_explorer.py@@ -20,9 +20,15 @@ from marimo._server.models.files import (FileListResponse,FileMoveRequest,FileMoveResponse,+ FileOpenRequest,FileUpdateRequest,FileUpdateResponse,)+from marimo._server.models.models import (+ BaseResponse,+ ErrorResponse,+ SuccessResponse,+)from marimo._server.router import APIRouterif TYPE_CHECKING:@@ -213,3 +219,33 @@ async def update_file(except Exception as e:LOGGER.error(f"Error updating file or directory: {e}")return FileUpdateResponse(success=False, message=str(e))++[email protected]("/open")+@requires("edit")+async def open_file(+ *,+ request: Request,+) -> BaseResponse:+ """+ requestBody:+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/FileOpenRequest"+ responses:+ 200:+ description: Open a file in the system editor+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/BaseResponse"+ """+ body = await parse_request(request, cls=FileOpenRequest)+ try:+ file_system.get_details(body.path)+ success = file_system.open_in_editor(body.path)+ return SuccessResponse(success=success)+ except Exception as e:+ LOGGER.error(f"Error opening file: {e}")+ return ErrorResponse(success=False, message=str(e))diff --git a/marimo/_server/api/endpoints/files.py b/marimo/_server/api/endpoints/files.pyindex 0322a3cdde..cf05cc86b6 100644--- a/marimo/_server/api/endpoints/files.py+++ b/marimo/_server/api/endpoints/files.py@@ -1,7 +1,6 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-import osfrom typing import TYPE_CHECKINGfrom starlette.authentication import requires@@ -9,7 +8,6 @@ from starlette.exceptions import HTTPExceptionfrom starlette.responses import PlainTextResponsefrom marimo import _loggers-from marimo._ast import codegenfrom marimo._server.api.deps import AppStatefrom marimo._server.api.status import HTTPStatusfrom marimo._server.api.utils import parse_request@@ -17,7 +15,6 @@ from marimo._server.ids import ConsumerIdfrom marimo._server.models.models import (BaseResponse,CopyNotebookRequest,- OpenFileRequest,ReadCodeResponse,RenameFileRequest,SaveAppConfigurationRequest,@@ -113,56 +110,6 @@ async def rename_file(return SuccessResponse()[email protected]("/open")-@requires("edit")-async def open_file(- *,- request: Request,-) -> BaseResponse:- """- requestBody:- content:- application/json:- schema:- $ref: "#/components/schemas/OpenFileRequest"- responses:- 200:- description: Open a file- content:- application/json:- schema:- $ref: "#/components/schemas/SuccessResponse"- 400:- description: File does not exist- """- body = await parse_request(request, cls=OpenFileRequest)-- # Validate file exists- if not os.path.exists(body.path):- raise HTTPException(- status_code=HTTPStatus.BAD_REQUEST,- detail=f"File {body.path} does not exist",- )-- # Get relative path- filename = os.path.relpath(body.path)-- try:- app = codegen.get_app(filename)- if app is None:- raise HTTPException(- status_code=HTTPStatus.BAD_REQUEST,- detail=f"File {filename} is not a valid marimo app",- )- except Exception as e:- raise HTTPException(- status_code=HTTPStatus.SERVER_ERROR,- detail=f"Failed to read file: {str(e)}",- ) from e-- return SuccessResponse()--@router.post("/save")@requires("edit")async def save(diff --git a/marimo/_server/files/os_file_system.py b/marimo/_server/files/os_file_system.pyindex c88a53d77d..ac18e0a54c 100644--- a/marimo/_server/files/os_file_system.py+++ b/marimo/_server/files/os_file_system.py@@ -4,13 +4,18 @@ from __future__ import annotationsimport base64import mimetypesimport os+import platformimport reimport shutil+import subprocessfrom typing import List, Literal, Optional, Union+from marimo import _loggersfrom marimo._server.files.file_system import FileSystemfrom marimo._server.models.files import FileDetailsResponse, FileInfo+LOGGER = _loggers.marimo_logger()+IGNORE_LIST = [".","..",@@ -165,6 +170,36 @@ class OSFileSystem(FileSystem):file.write(contents)return self.get_details(path).file+ def open_in_editor(self, path: str) -> bool:+ try:+ # First try to get editor from environment variable+ editor = os.environ.get("EDITOR")++ # If editor is a terminal-based editor, we just call `open`, because+ # otherwise it silently opens the terminal in the same window that is+ # running marimo.+ if editor and not _is_terminal_editor(editor):+ try:+ # For GUI editors+ subprocess.run([editor, path])+ return True+ except Exception as e:+ LOGGER.error(f"Error opening with EDITOR: {e}")+ pass++ # Use system default if no editor specified+ if platform.system() == "Darwin": # macOS+ subprocess.call(("open", path))+ elif platform.system() == "Windows": # Windows+ # startfile only exists on Windows+ os.startfile(path) # type: ignore[attr-defined]+ else: # Linux variants+ subprocess.call(("xdg-open", path))+ return True+ except Exception as e:+ LOGGER.error(f"Error opening file: {e}")+ return False+def natural_sort_file(file: FileInfo) -> List[Union[int, str]]:return natural_sort(file.name)@@ -178,3 +213,19 @@ def natural_sort(filename: str) -> List[Union[int, str]]:return [convert(c) for c in re.split("([0-9]+)", key)]return alphanum_key(filename)+++def _is_terminal_editor(editor: str) -> bool:+ return any(+ ed in editor.lower()+ for ed in [+ "vim",+ "vi",+ "emacs",+ "nano",+ "nvim",+ "neovim",+ "pico",+ "micro",+ ]+ )diff --git a/marimo/_server/models/models.py b/marimo/_server/models/models.pyindex 31394db2f6..15e893fae1 100644--- a/marimo/_server/models/models.py+++ b/marimo/_server/models/models.py@@ -49,6 +49,12 @@ class SuccessResponse(BaseResponse):success: bool = True+@dataclass+class ErrorResponse(BaseResponse):+ success: bool = False+ message: Optional[str] = None++@dataclassclass FormatRequest:codes: Dict[CellId_t, str]@@ -73,11 +79,6 @@ class RenameFileRequest:return RenameRequest(filename=os.path.abspath(self.filename))-@dataclass-class OpenFileRequest:- path: str--@dataclassclass RunRequest:# ids of cells to rundiff --git a/marimo/_smoke_tests/altair/vegafusion_select.py b/marimo/_smoke_tests/altair/vegafusion_select.pynew file mode 100644index 0000000000..2c61a2e921--- /dev/null+++ b/marimo/_smoke_tests/altair/vegafusion_select.py@@ -0,0 +1,60 @@+# /// script+# requires-python = ">=3.13"+# dependencies = [+# "altair==5.5.0",+# "marimo",+# "vega-datasets==0.9.0",+# "vegafusion[embed]==2.0.1",+# "vl-convert-python==1.7.0",+# ]+# ///++import marimo++__generated_with = "0.11.2"+app = marimo.App(width="medium")+++def _():+ import marimo as mo+ import altair as alt+ from vega_datasets import data++ alt.data_transformers.enable("vegafusion")++ # Load some data+ cars = data.cars()++ # Create an Altair chart+ _chart = (+ alt.Chart(cars)+ .mark_point()+ .encode(+ x="Horsepower",+ y="Miles_per_Gallon",+ color="Origin",+ )+ .properties(height=300)+ .add_params(alt.selection_interval(name="interval"))+ )++ # Make it reactive ⚡+ chart = mo.ui.anywidget(alt.JupyterChart(_chart))+ return alt, cars, chart, data, mo+++def _(chart):+ chart+ return+++def _(chart):+ list(chart.selections.interval.value.items())+ return+++if __name__ == "__main__":+ app.run()diff --git a/openapi/api.yaml b/openapi/api.yamlindex fe04d9d338..7f6896d96d 100644--- a/openapi/api.yaml+++ b/openapi/api.yaml@@ -755,6 +755,13 @@ components:required:- successtype: object+ FileOpenRequest:+ properties:+ path:+ type: string+ required:+ - path+ type: objectFileUpdateRequest:properties:contents:@@ -1489,13 +1496,6 @@ components:- type: boolean- format: bytetype: string- OpenFileRequest:- properties:- path:- type: string- required:- - path- type: objectOpenTutorialRequest:properties:tutorialId:@@ -2258,6 +2258,20 @@ paths:schema:$ref: '#/components/schemas/FileMoveResponse'description: Move a file or directory+ /api/files/open:+ post:+ requestBody:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/FileOpenRequest'+ responses:+ 200:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/BaseResponse'+ description: Open a file in the system editor/api/files/update:post:requestBody:@@ -2439,22 +2453,6 @@ paths:schema:$ref: '#/components/schemas/SuccessResponse'description: Interrupt the kernel's execution- /api/kernel/open:- post:- requestBody:- content:- application/json:- schema:- $ref: '#/components/schemas/OpenFileRequest'- responses:- 200:- content:- application/json:- schema:- $ref: '#/components/schemas/SuccessResponse'- description: Open a file- 400:- description: File does not exist/api/kernel/read_code:post:responses:diff --git a/openapi/src/api.ts b/openapi/src/api.tsindex 77554891c5..c81ed960c6 100644--- a/openapi/src/api.ts+++ b/openapi/src/api.ts@@ -636,6 +636,45 @@ export interface paths {patch?: never;trace?: never;};+ "/api/files/open": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ get?: never;+ put?: never;+ post: {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ requestBody?: {+ content: {+ "application/json": components["schemas"]["FileOpenRequest"];+ };+ };+ responses: {+ /** @description Open a file in the system editor */+ 200: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["BaseResponse"];+ };+ };+ };+ };+ delete?: never;+ options?: never;+ head?: never;+ patch?: never;+ trace?: never;+ };"/api/files/update": {parameters: {query?: never;@@ -1170,52 +1209,6 @@ export interface paths {patch?: never;trace?: never;};- "/api/kernel/open": {- parameters: {- query?: never;- header?: never;- path?: never;- cookie?: never;- };- get?: never;- put?: never;- post: {- parameters: {- query?: never;- header?: never;- path?: never;- cookie?: never;- };- requestBody?: {- content: {- "application/json": components["schemas"]["OpenFileRequest"];- };- };- responses: {- /** @description Open a file */- 200: {- headers: {- [name: string]: unknown;- };- content: {- "application/json": components["schemas"]["SuccessResponse"];- };- };- /** @description File does not exist */- 400: {- headers: {- [name: string]: unknown;- };- content?: never;- };- };- };- delete?: never;- options?: never;- head?: never;- patch?: never;- trace?: never;- };"/api/kernel/read_code": {parameters: {query?: never;@@ -2380,6 +2373,9 @@ export interface components {message?: string | null;success: boolean;};+ FileOpenRequest: {+ path: string;+ };FileUpdateRequest: {contents: string;path: string;@@ -2699,9 +2695,6 @@ export interface components {type: "multiple-defs";};NonNestedLiteral: number | string | boolean;- OpenFileRequest: {- path: string;- };OpenTutorialRequest: {tutorialId:| (diff --git a/tests/_server/api/endpoints/test_file_explorer.py b/tests/_server/api/endpoints/test_file_explorer.pyindex 3468696cb8..ee954a3f90 100644--- a/tests/_server/api/endpoints/test_file_explorer.py+++ b/tests/_server/api/endpoints/test_file_explorer.py@@ -102,3 +102,14 @@ def test_move_file_or_directory(client: TestClient) -> None:assert response.status_code == 200, response.textassert response.headers["content-type"] == "application/json"assert response.json()["success"] is True+++def test_open_file(client: TestClient) -> None:+ response = client.post(+ "/api/files/open",+ headers=HEADERS,+ json={"path": test_file_path},+ )+ assert response.status_code == 200, response.text+ assert response.headers["content-type"] == "application/json"+ assert "success" in response.json()