### Launch Euporie Hub Source: https://github.com/joouha/euporie/blob/dev/docs/apps/hub.md Run the euporie hub command to start the server. Ensure euporie is installed and accessible in your PATH. ```bash $ euporie hub ``` -------------------------------- ### Install Euporie via uv Source: https://context7.com/joouha/euporie/llms.txt Install Euporie globally, try it without installation, or install the latest development version from GitHub. ```console # Install globally as a tool $ uv tool install euporie ``` ```console # Try without installing $ uvx euporie notebook ``` ```console # Install from git (latest dev) $ uv tool install git+https://github.com/joouha/euporie.git@dev ``` -------------------------------- ### Install Euporie from Git (Development Version) Source: https://github.com/joouha/euporie/blob/dev/docs/pages/installation.md Install the latest development version of Euporie directly from its GitHub repository. ```bash $ uv tool install git+https://github.com/joouha/euporie.git@dev ``` ```bash $ pipx install git+https://github.com/joouha/euporie.git@dev ``` ```bash $ pip install git+https://github.com/joouha/euporie.git@dev ``` -------------------------------- ### Try Euporie Without Installing Source: https://github.com/joouha/euporie/blob/dev/docs/pages/installation.md Use uv or pipx to run Euporie commands without a permanent installation. ```bash $ uvx euporie notebook ``` ```bash $ pipx run --spec 'euporie[all]' euporie notebook ``` -------------------------------- ### Install IPython Kernel with uv Source: https://github.com/joouha/euporie/blob/dev/docs/pages/installation.md Install the IPython kernel in a virtual environment using uv for Python notebooks. ```bash $ uv pip install ipykernel $ uv run python -m ipykernel install --user ``` -------------------------------- ### Euporie Preview CLI Examples Source: https://context7.com/joouha/euporie/llms.txt Render notebooks to terminal output using euporie-preview. Suitable for scripting and file manager integration. ```bash # Print a notebook to terminal $ euporie-preview notebook.ipynb ``` ```bash # Send to system pager $ euporie-preview --page notebook.ipynb ``` ```bash # Pipe to bat with 24-bit color $ euporie-preview --color-depth=24 notebook.ipynb | bat ``` ```bash # Run all cells before rendering $ euporie-preview --run notebook.ipynb ``` ```bash # Run cells, then save the executed notebook $ euporie-preview --run --save notebook.ipynb ``` ```bash # Preview only cells 3–6 (0-indexed) $ euporie-preview --cell-start=3 --cell-end=6 notebook.ipynb ``` ```bash # Force sixel graphics $ euporie-preview --graphics=sixel --force-graphics notebook.ipynb ``` ```bash # Use with ranger file manager (scope.sh) # handle_extension() { # ipynb) euporie-preview --color-depth=8 "${FILE_PATH}" && exit 4 ;; # } ``` -------------------------------- ### Install and Register IPython Kernel Source: https://github.com/joouha/euporie/blob/dev/docs/pages/troubleshooting.md Ensure ipykernel is installed and register your kernel with the system so euporie can discover it. This is crucial for notebooks to start correctly. ```bash pip install ipykernel ``` ```bash python -m ipykernel install --user ``` -------------------------------- ### Launch Euporie with Environment-Driven Config Source: https://context7.com/joouha/euporie/llms.txt Launch Euporie with specific environment variables set for the current session. This example sets the color scheme to light and enables notebook expansion. ```bash $ EUPORIE_COLOR_SCHEME=light EUPORIE_EXPAND=True euporie-notebook notebook.ipynb ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/joouha/euporie/blob/dev/DEVELOPMENT.rst Install pre-commit hooks to automate code checks and formatting before commits. Use 'uv run pre-commit install' for this. ```bash uv run pre-commit install ``` -------------------------------- ### Install IPython Kernel with pip Source: https://github.com/joouha/euporie/blob/dev/docs/pages/installation.md Install the IPython kernel for the current user using pip. ```bash $ pip install --user ipykernel $ python -m ipykernel install --user ``` -------------------------------- ### Install Dependencies with uv Source: https://github.com/joouha/euporie/blob/dev/DEVELOPMENT.rst Install project dependencies using the 'uv sync' command. This ensures all necessary packages are available for development. ```bash uv sync ``` -------------------------------- ### Install Euporie with uv, pipx, or pip Source: https://github.com/joouha/euporie/blob/dev/README.rst Install Euporie using your preferred Python package manager. uv is recommended. ```console $ uv tool install euporie ``` ```console $ # OR $ pipx install euporie ``` ```console $ # OR $ python -m pip install --user euporie ``` -------------------------------- ### Start euporie-console Source: https://context7.com/joouha/euporie/llms.txt Launch the interactive kernel console. Connect to a specific kernel by name or use an existing kernel's connection file. ```console # Start a Python console $ euporie-console ``` ```console # Connect to a specific kernel by name $ euporie-console --kernel python3 ``` ```console # Connect to an existing kernel via connection file $ euporie-console --connection-file /path/to/kernel-12345.json ``` -------------------------------- ### Run Euporie Hub with Key Configuration Source: https://github.com/joouha/euporie/blob/dev/docs/apps/hub.md Start Euporie Hub, specifying the paths to the generated host keys and the authorized_keys file for clients. Users can then log in using keys listed in the authorized_keys file. ```bash $ euporie-hub --host-keys ssh_host_ed25519_key --client-keys "~/.ssh/authorized_keys" ``` -------------------------------- ### Google-Style Docstring Example Source: https://github.com/joouha/euporie/blob/dev/CONVENTIONS.rst Demonstrates a Google-style docstring for a function, including a brief description, extended explanation, Args, Returns, and Raises sections. ```python def merge_configs( base: dict[str, Any], override: dict[str, Any], *, deep: bool = True, ) -> dict[str, Any]: """Merge two configuration dictionaries. Combines base and override configs, with override taking precedence. Nested dictionaries are merged recursively when deep=True. Args: base: The base configuration dictionary. override: Configuration values to override. deep: Whether to recursively merge nested dicts. Returns: A new dictionary with merged configuration. Raises: TypeError: If inputs are not dictionaries. """ ... ``` -------------------------------- ### Install Euporie Globally Source: https://github.com/joouha/euporie/blob/dev/docs/pages/installation.md Install Euporie using your preferred Python package manager for global access. ```bash $ uv tool install euporie ``` ```bash $ pipx install euporie ``` ```bash $ pip install euporie ``` -------------------------------- ### Install Euporie via pipx or pip Source: https://context7.com/joouha/euporie/llms.txt Install Euporie using pipx or pip. Individual applications can also be installed separately. Ensure ipykernel is installed for Python notebook execution. ```console $ pipx install euporie # or $ pip install euporie ``` ```console # Individual apps can also be installed separately $ pip install euporie-notebook euporie-console euporie-preview euporie-hub ``` ```console # Install ipykernel for Python notebook execution $ pip install ipykernel && python -m ipykernel install --user ``` -------------------------------- ### Creating a Changelog Entry Source: https://github.com/joouha/euporie/blob/dev/CONVENTIONS.rst Examples of creating changelog fragment files for different types of changes (feature, fix) using echo. ```bash # For a new feature related to issue #123 echo "Added support for custom color schemes" > changelog/123.added.rst # For a bug fix related to issue #456 echo "Fixed crash when opening empty notebooks" > changelog/456.fixed.rst # For changes without an issue number, use a unique identifier echo "Improved startup performance" > changelog/+perf-startup.changed.rst ``` -------------------------------- ### Setup Terminal Fitting Source: https://github.com/joouha/euporie/blob/dev/docs/_static/lite.html Applies initial fitting to the terminal using the FitAddon and ensures the terminal refits after fonts are loaded. This ensures the terminal correctly resizes to its container. ```javascript function setupTerminalFitting(fitAddon) { // Initial fit fitAddon.fit(); // Refit after fonts load const fontsReadyPromise = document.fonts ? document.fonts.ready : Promise.resolve(); fontsReadyPromise .ca ``` -------------------------------- ### Launch Euporie Console Source: https://github.com/joouha/euporie/blob/dev/README.rst Connect to a Jupyter kernel and start an interactive code session in the terminal with euporie-console. Press Ctrl+C to open the command palette. ```console $ euporie-console ``` -------------------------------- ### Euporie Hub SSH Server Setup Source: https://context7.com/joouha/euporie/llms.txt Set up and run euporie-hub as a multi-user SSH server. Requires SSH host keys for secure operation. ```bash # Generate SSH host keys $ ssh-keygen -t ed25519 -f ssh_host_ed25519_key ``` ```bash # Start hub with default settings (port 8022) $ euporie-hub \ --host-keys ssh_host_ed25519_key \ --client-keys ~/.ssh/authorized_keys ``` ```bash # Start hub on a custom host/port serving the console app $ euporie-hub \ --host 0.0.0.0 \ --port 9022 \ --hub-app console \ --host-keys /etc/ssh/ssh_host_ed25519_key \ --client-keys /etc/euporie/authorized_keys ``` ```bash # Allow unauthenticated access (DANGEROUS — use only in trusted environments) $ euporie-hub --no-auth --host-keys ssh_host_ed25519_key ``` ```bash # Connect as a user $ ssh -p 8022 localhost ``` -------------------------------- ### Run Euporie Hub Source: https://github.com/joouha/euporie/blob/dev/README.rst Start euporie-hub, a multi-user SSH server for Euporie applications. Ensure you provide paths to your host and authorized keys files. ```console $ euporie-hub --port 8022 --host-keys=ssh_host_ed25519_key --client-keys=authorized_keys ``` -------------------------------- ### Python Import Order Example Source: https://github.com/joouha/euporie/blob/dev/CONVENTIONS.rst Demonstrates the required import order: future imports, standard library, third-party, and local imports. Blank lines separate each group. ```python from __future__ import annotations import os from collections.abc import Callable, Sequence from typing import TYPE_CHECKING, Any from apptk.application import Application from apptk.layout.containers import HSplit, VSplit from euporie.core.app import BaseApp from euporie.core.config import Config if TYPE_CHECKING: from apptk.key_binding import KeyBindings ``` -------------------------------- ### Creating UI Content Source: https://github.com/joouha/euporie/blob/dev/CONVENTIONS.rst Instantiate UIContent with lambda functions for getting lines and specifying the total line count to define UI elements. ```python from apptk.layout.controls import UIContent def create_content() -> UIContent: return UIContent( get_line=lambda i: [...], line_count=10, ) ``` -------------------------------- ### Advanced Custom Key Bindings (JSON) Source: https://context7.com/joouha/euporie/llms.txt Configure advanced key bindings, including adding new shortcuts, removing existing ones, and replacing default bindings. This example demonstrates adding 'c-y' and removing 'c-c' for copy, and adding a global, eager binding for 'activate-command-bar'. ```json { "key_bindings": { "copy": { "add": ["c-y"], "remove": ["c-c"] }, "activate-command-bar": { "add": [ {"keys": "c-p", "is_global": true, "eager": true} ] }, "dangerous-command": { "replace": true } } } ``` -------------------------------- ### Custom Key Bindings Configuration (JSON) Source: https://context7.com/joouha/euporie/llms.txt Define custom key bindings for Euporie commands using a JSON object. This example shows how to set bindings for 'quit', 'save-file', and 'new-notebook'. An empty list means no binding for that command. ```json { "key_bindings": { "quit": ["c-q", "A-F4"], "save-file": ["c-s"], "new-notebook": [] } } ``` -------------------------------- ### Setup Before Unload Sync (JavaScript) Source: https://github.com/joouha/euporie/blob/dev/docs/_static/lite.html Attaches an event listener to the `beforeunload` event to ensure that any pending changes in the persistent home directory are synchronized to IndexedDB before the page is closed. This prevents data loss. ```javascript function setupBeforeUnloadSync(pyodide) { window.addEventListener("beforeunload", () => { try { pyodide.FS.syncfs(false, (err) => { if (err) console.error("Final sync before unload failed:", err); }); } catch (e) { console.error("Error during beforeunload sync:", e); } }); } ``` -------------------------------- ### Apply Key Bindings via CLI Source: https://context7.com/joouha/euporie/llms.txt Apply custom key bindings directly from the command line using the --key-bindings argument. This example sets 'quit' to 'c-q' and 'c-p', and 'new-notebook' to an empty list. ```bash $ euporie-notebook \ --key-bindings='{"quit": ["c-q", "c-p"], "new-notebook": []}' \ notebook.ipynb ``` -------------------------------- ### Custom Key Bindings Configuration Source: https://github.com/joouha/euporie/blob/dev/docs/pages/keybindings.md Example of setting custom key bindings for the Notebook app in a configuration file. This overrides default bindings, so include defaults if you wish to retain them. ```javascript { "notebook": { "autoformat": false, "expand": true, "key_bindings": { "euporie.notebook.app:NotebookApp": { "quit": ["c-q", "c-p"], "new-notebook": [] } }, } } ``` -------------------------------- ### Setup Pyodide Input/Output Bridge (JavaScript) Source: https://github.com/joouha/euporie/blob/dev/docs/_static/lite.html Connects the xterm.js terminal's input and resize events to Pyodide. Terminal input data is passed to Pyodide's `handle_input` function, and resize events trigger Pyodide's `handle_resize` function. ```javascript async function setupPyodideIO(pyodide, term) { // Connect xterm.js input to Python term.onData((data) => { pyodide.runPythonAsync(`handle_input(${JSON.stringify(data)})`); }); // Listen for terminal resize events term.onResize(({ cols, rows }) => { pyodide.runPythonAsync(`handle_resize(${cols}, ${rows})`); }); } ``` -------------------------------- ### Create a New Notebook from Command Line Source: https://github.com/joouha/euporie/blob/dev/docs/apps/notebook.md Launch Euporie with a new notebook file path to create it. Ensure the file path is specified correctly. ```console $ euporie-notebook ./my-new-notebook.ipynb ``` -------------------------------- ### Open an Existing Notebook from Command Line Source: https://github.com/joouha/euporie/blob/dev/docs/apps/notebook.md Launch Euporie with an existing notebook file path to open it. This is useful for quickly resuming work. ```console $ euporie-notebook ./my-notebook.ipynb ``` -------------------------------- ### Initialize and Run Euporie Lite Source: https://github.com/joouha/euporie/blob/dev/docs/_static/lite.html This code initializes Pyodide, sets up keyboard and terminal I/O, and then loads and runs the Euporie application. It includes error handling and final synchronization steps. ```javascript async function main() { try { window.term.focus(); window.term.write("Loading Euporie...\r\n"); // Load Pyodide const pyodide = await loadPyodide({ packages: PYODIDE_PACKAGES }); window.term.write("Pyodide loaded\r\n"); // Setup keyboard handling setupKeyboardHandler(window.term, pyodide); // Setup persistent storage setupBeforeUnloadSync(pyodide); await mountPersistentHome(pyodide); startAutoSync(pyodide, AUTO_SYNC_INTERVAL_MS); // Connect terminal I/O to Python await setupPyodideIO(pyodide, window.term); // Load and run Euporie await loadAndRunEuporie(pyodide, window.term); // Final sync after completion await syncPersistentHome(pyodide); window.term.write("\r\n[Euporie has exited]\r\n"); } catch (err) { window.term.write(`\r\nError: ${err.message}\r\n`); console.error(err); } } // Start the application main(); ``` -------------------------------- ### Configure Ranger for Notebook Previews Source: https://github.com/joouha/euporie/blob/dev/docs/apps/preview.md Integrate euporie-preview into the ranger file manager by adding configuration to `scope.sh` to handle `.ipynb` files. ```bash # ... handle_extension() { case "${FILE_EXTENSION_LOWER}" in # ... ## Notebook ipynb) euporie-preview --color-depth=8 "${FILE_PATH}" && exit 4 esac } # ... ``` -------------------------------- ### Automated Notebook Execution with euporie-preview Source: https://context7.com/joouha/euporie/llms.txt Use `euporie-preview --run --save` for automated notebook execution, particularly useful in CI pipelines. ```bash euporie-preview --run --save ``` -------------------------------- ### Class Docstring Example Source: https://github.com/joouha/euporie/blob/dev/CONVENTIONS.rst Provides an example of a class docstring that describes the class's purpose and lists its public attributes. ```python class NotebookCell: """Represents a single cell in a notebook. ``` -------------------------------- ### Python Naming Conventions Example Source: https://github.com/joouha/euporie/blob/dev/CONVENTIONS.rst Shows examples of Python naming conventions: type variables ('_T'), constants ('MAX_BUFFER_SIZE'), private members ('_cache', '_transform'), and class/method naming. ```python from typing import TypeVar _T = TypeVar("_T") MAX_BUFFER_SIZE = 1024 class DataProcessor: def __init__(self) -> None: self._cache: dict[str, Any] = {} def process(self, data: _T) -> _T: return self._transform(data) def _transform(self, data: _T) -> _T: ... ``` -------------------------------- ### Getting the Current Application Instance Source: https://github.com/joouha/euporie/blob/dev/CONVENTIONS.rst Retrieve the current application instance using get_app and perform actions like refreshing it. ```python from euporie.core.app.current import get_app def do_something() -> None: app = get_app() app.refresh() ``` -------------------------------- ### Initialize and Run Euporie Notebook App Source: https://github.com/joouha/euporie/blob/dev/docs/_static/lite.html Initializes the Euporie notebook application within the Pyodide environment. It configures the event loop, sets up input/output adapters, and runs the application asynchronously. ```python async def run(): """Initialize and run the Euporie notebook application.""" from euporie.core.layout import containers as containers from euporie.notebook.app import NotebookApp as App from prompt_toolkit.application.current import create_app_session, set_app # Configure event loop for Pyodide environment _loop = asyncio.get_event_loop() if not hasattr(_loop, "slow_callback_duration"): _loop.slow_callback_duration = 0.5 # Signal handlers don't work in browser, so stub them out _loop.add_signal_handler = lambda *a, **k: None _loop.remove_signal_handler = lambda *a, **k: None # Create output adapter output = Vt100_Output( stdout=XtermJsStdout(), get_size=lambda: Size(rows=app_state["rows"], columns=app_state["cols"]), term="xterm-256color", default_color_depth=ColorDepth.DEPTH_24_BIT, enable_bell=True, enable_cpr=False, ) app_state["output"] = output # Create input adapter input_obj = XtermJsInput() app_state["input"] = input_obj # Clear the terminal before launching the app output.erase_screen() output.flush() # Load application configuration App.config.load() # Set default configuration values for browser environment App.config._values.update({ "show_file_icons": True, "show_side_bar": True, "clipboard": "terminal", }) # Run the application with with create_app_session(input=input_obj, output=output): app = App(input=input_obj, output=output) with set_app(app): await app.run_async(handle_sigint=False) ``` -------------------------------- ### Configure Euporie via Environment Variables Source: https://github.com/joouha/euporie/blob/dev/docs/pages/configuration.md Set environment variables to configure Euporie globally or for specific applications. Prefix global variables with EUPORIE_ and application-specific variables with EUPORIE__. Empty strings for boolean values evaluate to False. ```console $ EUPORIE_COLOR_SCHEME=light EUPORIE_SHOW_CELL_BORDERS=False EUPORIE_EXPAND=True euporie-notebook notebook.ipynb ``` -------------------------------- ### Clone Euporie Repository Source: https://github.com/joouha/euporie/blob/dev/DEVELOPMENT.rst Clone the Euporie repository and navigate into the directory. This is the first step for setting up the development environment. ```bash git clone https://github.com/joouha/euporie.git cd euporie ``` -------------------------------- ### Enable and Configure LSP Servers Source: https://context7.com/joouha/euporie/llms.txt Enable Language Server Protocol support with --lsp and configure custom servers via --language-servers or the config file. ```console # Enable LSP (uses built-in defaults for known languages) $ euporie-notebook --lsp notebook.ipynb ``` ```console # Add custom LSP servers $ euporie-notebook --lsp \ --language-servers='{ "pylsp": {"command": ["pylsp"], "languages": ["python"]}, "ruff": {"command": ["ruff-lsp"], "languages": ["python"]}, "typos": {"command": ["typos-lsp"], "languages": ["python", "markdown"]} }' notebook.ipynb ``` ```console # Disable a built-in LSP server (e.g. the awk server) $ euporie-notebook --lsp \ --language-servers='{"awk-language-server": {}}' notebook.ipynb ``` -------------------------------- ### Preview Subset of Cells Source: https://github.com/joouha/euporie/blob/dev/docs/apps/preview.md Display only a specific range of cells from the notebook by specifying the start and end cell numbers. This is useful for focusing on particular sections. ```bash $ euporie-preview --cell-start=3 --cell-end=6 notebook.ipynb ``` -------------------------------- ### Configure Euporie via Command Line Arguments Source: https://github.com/joouha/euporie/blob/dev/docs/pages/configuration.md Use command-line flags to set configuration options for a specific Euporie instance. These settings override environment variables and configuration files. ```console $ euporie --color-scheme=light --no-show-cell-borders --expand notebook.ipynb ``` -------------------------------- ### Launch euporie-notebook with various configurations Source: https://context7.com/joouha/euporie/llms.txt Configure the euporie-notebook editor with options for layout, color scheme, editing mode, LSP, syntax theme, graphics protocol, and formatting. ```console # Open or create a notebook $ euporie-notebook analysis.ipynb ``` ```console # Open multiple notebooks as tabs $ euporie-notebook notebook1.ipynb notebook2.ipynb ``` ```console # Start with expanded layout, light color scheme, vi bindings, and LSP enabled $ euporie-notebook \ --expand \ --color-scheme=light \ --edit-mode=vi \ --lsp \ --syntax-theme=monokai \ analysis.ipynb ``` ```console # Auto-run notebook on open, hide top bar, use kitty graphics protocol $ euporie-notebook \ --run \ --no-show-top-bar \ --graphics=kitty \ experiment.ipynb ``` ```console # Tile two notebooks vertically side by side $ euporie-notebook --tab-mode=tile_vertically nb1.ipynb nb2.ipynb ``` ```console # Configure formatters via CLI (ruff for Python) $ euporie-notebook \ --formatters='{"ruff-format": {"command": ["ruff", "format", "-"], "languages": ["python"]}}' \ code.ipynb ``` -------------------------------- ### Synchronize Terminal Size and Run Pyodide Code Source: https://github.com/joouha/euporie/blob/dev/docs/_static/lite.html Synchronizes the initial terminal size with Pyodide and then executes the main Python script to start the Euporie application. ```javascript await pyodide.runPythonAsync( `handle_resize(${term.cols}, ${term.rows})` ); term.write("Starting euporie...\r\n"); await pyodide.runPythonAsync("await run()"); ``` -------------------------------- ### Euporie Environment Variables Source: https://context7.com/joouha/euporie/llms.txt Configure Euporie settings using environment variables. Global options are prefixed with EUPORIE_, and per-app options use specific prefixes. ```bash # Global settings $ export EUPORIE_COLOR_SCHEME=light $ export EUPORIE_SYNTAX_THEME=dracula $ export EUPORIE_EDIT_MODE=vi $ export EUPORIE_GRAPHICS=kitty $ export EUPORIE_SHOW_ICONS=True $ export EUPORIE_LOG_LEVEL=debug $ export EUPORIE_LOG_FILE=/tmp/euporie.log ``` -------------------------------- ### Standard Python File Header Source: https://github.com/joouha/euporie/blob/dev/CONVENTIONS.rst All Python files must start with 'from __future__ import annotations'. This import enables postponed evaluation of type annotations. ```python from __future__ import annotations ``` -------------------------------- ### Initialize ConsoleApp with kwargs Source: https://github.com/joouha/euporie/blob/dev/CONVENTIONS.rst Use **kwargs with setdefault for flexible initialization when subclassing BaseApp. ```python class ConsoleApp(BaseApp): """Console application for interactive computing.""" def __init__(self, **kwargs: Any) -> None: """Initialize the console application.""" kwargs.setdefault("title", "euporie-console") kwargs.setdefault("full_screen", False) super().__init__(**kwargs) ``` -------------------------------- ### Python Type Annotations Example Source: https://github.com/joouha/euporie/blob/dev/CONVENTIONS.rst Illustrates the use of modern type annotations, including built-in generics, union types with '|', abstract types from 'collections.abc', and 'TYPE_CHECKING' for conditional imports. ```python from __future__ import annotations from collections.abc import Callable, Sequence from typing import TYPE_CHECKING, Any if TYPE_CHECKING: from apptk.layout import Container def process_items( items: Sequence[str], callback: Callable[[str], None] | None = None, ) -> dict[str, Any]: """Process a sequence of items.""" ... def create_layout(children: list[Container]) -> Container: """Create a layout from children.""" ... ``` -------------------------------- ### Custom Key Bindings via Command Line Source: https://github.com/joouha/euporie/blob/dev/docs/pages/keybindings.md How to pass custom key binding configurations as a JSON string on the command line. ```console $ euporie-notebook --key-bindings='{"euporie.notebook.app:NotebookApp": {"new-notebook": [],"quit": ["c-q", "c-p"]}}' ``` -------------------------------- ### Configuration & Setting API (`euporie.core.config`) Source: https://context7.com/joouha/euporie/llms.txt Defines typed configuration options using the `Setting` class and integrates with `ConfigurableApp` for automatic configuration management. ```APIDOC ## `euporie.core.config` — Configuration & Setting API The `Setting` class declares typed configuration options. `ConfigurableApp` subclasses list their `settings` and `states`, and automatically get a `Config` and `State` instance. ```python from euporie.core.config._setting import Setting from euporie.core.app.base import ConfigurableApp # Define a custom setting my_option = Setting( name="my_option", flags=["--my-option"], type_=str, default="hello", choices=["hello", "world"], help_="An example option", description="A longer description for documentation.", ) # Settings support hooks (callbacks on value change) refresh_hook = Setting( name="show_widget", flags=["--show-widget"], type_=bool, default=True, hooks=[lambda value: print(f"show_widget changed to {value}")], ) # Access config values in an app from euporie.notebook.app import NotebookApp cfg = NotebookApp.config print(cfg.color_scheme) # e.g. "dark" print(cfg.edit_mode) # e.g. EditingMode.MICRO print(cfg.syntax_theme) # e.g. "monokai" ``` ``` -------------------------------- ### Configure Euporie via JSON File Source: https://github.com/joouha/euporie/blob/dev/docs/pages/configuration.md Define configuration settings in a JSON file for persistent customization. Settings can be applied globally or to individual applications by nesting them under the application's name. ```json { "color_scheme": "light", "syntax_theme": "native", "notebook": { "expand": false, "always_show_tab_bar": true, "show_cell_borders": false }, "console": { "color_scheme": "default", "syntax_theme": "dracula" }, "preview": { "show_cell_borders": true } } ``` -------------------------------- ### Setup Custom Keyboard Handler (JavaScript) Source: https://github.com/joouha/euporie/blob/dev/docs/_static/lite.html Configures a custom keyboard event handler for the terminal, supporting macOS native copy/paste shortcuts and custom key combinations like Ctrl+Enter for specific actions. It also prevents default browser shortcuts when meta keys are involved. ```javascript function setupKeyboardHandler(term, pyodide) { term.attachCustomKeyEventHandler((ev) => { // macOS native copy/paste with ⌘C / ⌘V if (IS_MAC) { if ( ev.metaKey && ev.key.toLowerCase() === "c" && term.hasSelection() ) { return false; } if (ev.metaKey && ev.key.toLowerCase() === "v") { return false; } } // CSI-u for Ctrl+Enter / Shift+Enter if (ev.code === "Enter" && ev.type === "keydown") { if (ev.ctrlKey && !ev.shiftKey && !ev.altKey && !ev.metaKey) { pyodide.runPythonAsync(`handle_input("\\x1b[13;5u")`); ev.preventDefault(); return false; } else if ( ev.shiftKey && !ev.ctrlKey && !ev.altKey && !ev.metaKey ) { pyodide.runPythonAsync(`handle_input("\\x1b[13;2u")`); ev.preventDefault(); return false; } } // Allow Ctrl+Shift+C / Ctrl+Shift+V for copy/paste if ( ev.ctrlKey && ev.shiftKey && (ev.key.toLowerCase() === "c" || ev.key.toLowerCase() === "v") ) { return true; } // Prevent default for browser shortcuts if (ev.ctrlKey || ev.altKey || ev.metaKey) { ev.preventDefault(); } return true; }); } ``` -------------------------------- ### Class Initialization Source: https://github.com/joouha/euporie/blob/dev/docs/_templates/autosummary/class.rst Details the constructor for the class. ```APIDOC ## __init__ ### Description Initializes a new instance of the class. ### Method __init__ ``` -------------------------------- ### Launch Euporie applications via unified launcher Source: https://context7.com/joouha/euporie/llms.txt Use the `euporie` command as a unified launcher for various applications like notebook, console, and preview. Flags for specific apps can be passed after the subcommand. ```console # Launch the notebook editor with a file $ euporie notebook my_analysis.ipynb ``` ```console # Launch the console with a specific kernel $ euporie console --kernel python3 ``` ```console # Preview a notebook and pipe to bat with 24-bit color $ euporie preview --color-depth=24 report.ipynb | bat ``` ```console # Launch euporie hub on a custom port $ euporie hub --port 9022 --host-keys ssh_host_ed25519_key --client-keys ~/.ssh/authorized_keys ``` ```console # Print version and exit $ euporie --version ``` -------------------------------- ### Euporie Clipboard Integration Source: https://context7.com/joouha/euporie/llms.txt Select the clipboard backend for euporie-notebook using the --clipboard argument. ```console # System clipboard via pyperclip (default) $ euporie-notebook --clipboard=external notebook.ipynb ``` ```console # Internal clipboard (isolated, does not touch system clipboard) $ euporie-notebook --clipboard=internal notebook.ipynb ``` ```console # OSC52 terminal clipboard (works over SSH) $ euporie-notebook --clipboard=terminal notebook.ipynb ``` -------------------------------- ### JavaScript Initialization for Euporie Lite Source: https://github.com/joouha/euporie/blob/dev/docs/_static/lite.html Initializes the xterm.js terminal and sets up communication with Pyodide. It loads terminal addons, fits the terminal to the window, and synchronizes the initial terminal size. ```javascript window.term = createTerminal(); const fitAddon = loadTerminalAddons(window.term); setupTerminalFitting(fitAddon); ``` -------------------------------- ### Create and Manage Notebooks with euporie.core.nbformat Source: https://context7.com/joouha/euporie/llms.txt Provides fast, validation-free utilities for creating, reading, and writing notebooks, compatible with the nbformat API. NotebookNode objects allow attribute-style access to cell data. ```python from euporie.core.nbformat import ( new_notebook, new_code_cell, read as read_nb, write as write_nb, NotebookNode, NOTEBOOK_EXTENSIONS, ) from pathlib import Path # Create a new notebook programmatically nb = new_notebook() nb.cells.append(new_code_cell(source="print('Hello, euporie!')")) nb.cells.append(new_code_cell(source="import sys; sys.version")) # Write to disk with Path("output.ipynb").open("w") as f: write_nb(nb, f) # Read an existing notebook with Path("existing.ipynb").open() as f: nb = read_nb(f, as_version=4) print(nb.metadata.kernelspec.display_name) # e.g. 'Python 3' print([c.source for c in nb.cells]) # ["print('Hello, euporie!')", "import sys; sys.version"] # NotebookNode: dict with attribute access cell = new_code_cell(source="x = 42") cell.metadata["tags"] = ["important"] print(cell.source) # "x = 42" print(cell["source"]) # "x = 42" # Supported file extensions (with jupytext installed) print(NOTEBOOK_EXTENSIONS) # ['.ipynb', '.md', '.py', '.R', '.jl', '.rs', '.go', ...] ``` -------------------------------- ### Notebook Utilities (`euporie.core.nbformat`) Source: https://context7.com/joouha/euporie/llms.txt Provides fast, validation-free utilities for creating and reading notebook files, compatible with the nbformat API. ```APIDOC ## `euporie.core.nbformat` — Notebook Utilities Fast, validation-free notebook creation and I/O utilities, compatible with the `nbformat` API but without the startup overhead of JSON schema validation. ```python from euporie.core.nbformat import ( new_notebook, new_code_cell, read as read_nb, write as write_nb, NotebookNode, NOTEBOOK_EXTENSIONS, ) from pathlib import Path # Create a new notebook programmatically b = new_notebook() b.cells.append(new_code_cell(source="print('Hello, euporie!')")) b.cells.append(new_code_cell(source="import sys; sys.version")) # Write to disk with Path("output.ipynb").open("w") as f: write_nb(nb, f) # Read an existing notebook with Path("existing.ipynb").open() as f: nb = read_nb(f, as_version=4) print(nb.metadata.kernelspec.display_name) # e.g. 'Python 3' print([c.source for c in nb.cells]) # ["print('Hello, euporie!')", "import sys; sys.version"] # NotebookNode: dict with attribute access cell = new_code_cell(source="x = 42") cell.metadata["tags"] = ["important"] print(cell.source) # "x = 42" print(cell["source"]) # "x = 42" # Supported file extensions (with jupytext installed) print(NOTEBOOK_EXTENSIONS) # ['.ipynb', '.md', '.py', '.R', '.jl', '.rs', '.go', ...] ``` ``` -------------------------------- ### Compose UI Layout with apptk Containers Source: https://github.com/joouha/euporie/blob/dev/CONVENTIONS.rst Use apptk layout containers like HSplit, VSplit, and Box for UI composition. ```python from apptk.layout.containers import HSplit, VSplit from apptk.layout.dimension import Dimension as D from euporie.core.widgets.layout import Box layout = HSplit([ VSplit([ Box(sidebar, width=D(preferred=30)), Box(main_content, width=D(weight=1)), ]), Box(statusbar, height=D.exact(1)), ]) ``` -------------------------------- ### Synchronize Persistent Home Directory (JavaScript) Source: https://github.com/joouha/euporie/blob/dev/docs/_static/lite.html Provides functions to synchronize the persistent home directory between IndexedDB and the Pyodide filesystem. `syncPersistentHome` performs a one-time sync, while `startAutoSync` sets up periodic background synchronization. ```javascript async function syncPersistentHome(pyodide) { if (syncInProgress) { return syncInProgress; } syncInProgress = new Promise((resolve, reject) => { pyodide.FS.syncfs(false, (err) => { syncInProgress = null; if (err) reject(err); else resolve(); }); }); return syncInProgress; } ``` ```javascript function startAutoSync(pyodide, intervalMs) { setInterval(() => { syncPersistentHome(pyodide).catch((e) => { console.error("Auto-sync failed:", e); }); }, intervalMs); } ``` -------------------------------- ### Run and Save Notebook Source: https://github.com/joouha/euporie/blob/dev/docs/apps/preview.md Execute the notebook's code and then save the updated notebook, including any new outputs, to a file. This combines execution with persistence. ```bash $ euporie-preview --run --save notebook.ipynb ``` -------------------------------- ### Euporie Key Binding Utilities Source: https://context7.com/joouha/euporie/llms.txt Import KeyBindings and COMMANDS from apptk.key_binding for managing key bindings in euporie applications. ```python from apptk.key_binding.key_bindings import KeyBindings from apptk.commands import COMMANDS ``` -------------------------------- ### Load and Run Euporie Core Logic (Python) Source: https://github.com/joouha/euporie/blob/dev/docs/_static/lite.html Loads and executes the main Python code for Euporie within Pyodide. This includes setting up the necessary bridges for input/output with xterm.js and prompt_toolkit. ```python async function loadAndRunEuporie(pyodide, term) { // Now load and run main.py // const launch_code = await (await fetch("main.py")).text(); await pyodide.runPythonAsync(` """ Python bridge for Euporie in Pyodide. Minimal input/output bridge to xterm.js for prompt_toolkit. """ import asyncio from euporie.core.io import Vt100_Output, Vt100Parser from js import term from prompt_toolkit.data_structures import Size from prompt_toolkit.input.base import _dummy_context_manager, Input from prompt_toolkit.output.color_depth import ColorDepth # Global state app_state = { "input_callback": None, "cols": int(term.cols), "rows": int(term.rows), "input": None, "output": None, } class XtermJsInput(Input): """Input adapter that bridges xterm.js keyboard events to prompt_toolkit.""" def __init__(self): """Initialize with a VT100 parser for escape sequence decoding.""" self._keys = [] self._vt100_parser = Vt100Parser(self._on_key_press) def _on_key_press(self, key_press): """Callback from VT100Parser when a key is decoded.""" self._keys.append(key_press) def feed(self, data: str) -> None: """Feed raw input data (escape sequences) into the VT100 parser.""" self._vt100_parser.feed(data) def read_keys(self): """Return accumulated KeyPress objects since last read.""" result = self._keys self._keys = [] return result def flush(self): """Flush input (no-op for this implementation).""" pass def flush_keys(self): """Drain and return any remaining keys from the queue.""" return self.read_keys() @property def closed(self): """Return True if input is closed.""" return False def fileno(self): """Return file descriptor (not applicab ``` -------------------------------- ### Add Configuration Setting with Config.add_setting Source: https://github.com/joouha/euporie/blob/dev/CONVENTIONS.rst Use the Config class to add application settings with defaults and choices. ```python from euporie.core.config import Config Config.add_setting( "color_scheme", default="dark", help_="Color scheme for the interface", choices=["dark", "light", "auto"], ) ``` -------------------------------- ### Define Settings with euporie.core.config._setting.Setting Source: https://context7.com/joouha/euporie/llms.txt Declares typed configuration options for applications. Settings can include flags, types, default values, choices, help text, and hooks that execute on value changes. ```python from euporie.core.config._setting import Setting from euporie.core.app.base import ConfigurableApp # Define a custom setting my_option = Setting( name="my_option", flags=["--my-option"], type_=str, default="hello", choices=["hello", "world"], help_="An example option", description="A longer description for documentation.", ) # Settings support hooks (callbacks on value change) refresh_hook = Setting( name="show_widget", flags=["--show-widget"], type_=bool, default=True, hooks=[lambda value: print(f"show_widget changed to {value}")], ) # Access config values in an app from euporie.notebook.app import NotebookApp cfg = NotebookApp.config print(cfg.color_scheme) # e.g. "dark" print(cfg.edit_mode) # e.g. EditingMode.MICRO print(cfg.syntax_theme) # e.g. "monokai" ```