### Install Ratatui-Py and Run Demo Source: https://github.com/holo-q/ratatui-py/blob/main/docs/quickstart.md Installs the ratatui-py library using pip and then runs the provided demo hub. This is the first step to getting started with the library. ```bash pip install ratatui ratatui-demos ``` -------------------------------- ### Ratatui-Py App Loop Helper Source: https://github.com/holo-q/ratatui-py/blob/main/docs/quickstart.md An example of using the App helper in ratatui-py to manage the application's render and event handling logic. It defines separate functions for rendering the UI and processing events, and then runs the app with initial state. ```python from ratatui_py import App, Terminal, Paragraph def render(term: Terminal, state: dict) -> None: w, h = term.size() p = Paragraph.from_text(state.get("msg", "Hi")) p.set_block_title("Demo", True) term.draw_paragraph(p, (0, 0, w, h)) def on_event(term: Terminal, evt: dict, state: dict) -> bool: if evt.get("kind") == "key" and evt.get("ch") in (ord('q'), ord('Q')): return False return True App(render=render, on_event=on_event, tick_ms=250).run({"msg": "Hello from App"}) ``` -------------------------------- ### Serve Documentation Preview Source: https://github.com/holo-q/ratatui-py/blob/main/CONTRIBUTING.md Installs MkDocs and the Material theme, then serves a local preview of the project's documentation. This allows contributors to see how their documentation changes will render. ```shell pip install mkdocs mkdocs-material mkdocs serve ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/holo-q/ratatui-py/blob/main/CONTRIBUTING.md Installs the ratatui-py package in editable mode along with development requirements for linting, type checking, and testing. Ensure you have Python 3.9+ and a virtual environment set up. ```shell pip install -e . pip install -r requirements-dev.txt ``` -------------------------------- ### Minimal Ratatui-Py Program Source: https://github.com/holo-q/ratatui-py/blob/main/docs/quickstart.md A basic Python program demonstrating the core functionality of ratatui-py. It initializes a terminal, creates a paragraph with text and a title, draws it to the terminal, and waits for user input or a timeout. ```python from ratatui_py import Terminal, Paragraph with Terminal() as term: p = Paragraph.from_text("Hello ratatui!\nPress any key to exit.") p.set_block_title("Demo", True) term.draw_paragraph(p) term.next_event(5000) ``` -------------------------------- ### Python Bar Chart Visualization with Ratatui-Py Source: https://context7.com/holo-q/ratatui-py/llms.txt Demonstrates how to create and render a bar chart using the ratatui-py library. It includes setting values, labels, bar dimensions, styles, and a block title. This requires the ratatui-py library to be installed. ```python from ratatui_py import Terminal, BarChart, Style, rgb with Terminal() as term: w, h = term.size() chart = BarChart() chart.set_values([10, 25, 15, 40, 30]) chart.set_labels(["Mon", "Tue", "Wed", "Thu", "Fri"]) chart.set_bar_width(5) chart.set_bar_gap(1) chart.set_styles( bar=Style(fg=rgb(100, 200, 255)), value=Style(fg=Color.White), label=Style(fg=Color.Gray) ) chart.set_block_title("Weekly Data", True) term.draw_barchart(chart, (0, 0, w, h)) term.next_event(5000) ``` -------------------------------- ### Python Line Chart Visualization with Ratatui-Py Source: https://context7.com/holo-q/ratatui-py/llms.txt Provides an example of creating and rendering a line chart with multiple data series, axes, and legends using ratatui-py. This code snippet requires the ratatui-py library and demonstrates setting chart bounds and titles. ```python from ratatui_py import Terminal, Chart, Style, Color with Terminal() as term: w, h = term.size() chart = Chart() # Add multiple data series chart.add_line( "Series 1", [(0.0, 0.0), (1.0, 2.0), (2.0, 1.5), (3.0, 4.0), (4.0, 3.5)], Style(fg=Color.LightBlue) ) chart.add_line( "Series 2", [(0.0, 1.0), (1.0, 1.5), (2.0, 3.0), (3.0, 2.5), (4.0, 4.5)], Style(fg=Color.LightGreen) ) # Configure chart chart.set_bounds(0.0, 4.0, 0.0, 5.0) chart.set_axes_titles("Time", "Value") chart.set_block_title("Data Plot", True) term.draw_chart(chart, (0, 0, w, h)) term.next_event(5000) ``` -------------------------------- ### Process Tasks for CPU-Bound Work in Python Source: https://context7.com/holo-q/ratatui-py/llms.txt Run pure-Python CPU-bound computations in a separate process to bypass the GIL using ProcessTask. This example demonstrates how to start a process, submit jobs with parameters, receive results, and handle task stopping. It requires the ratatui_py library. ```python from ratatui_py import Terminal, Paragraph, ProcessTask def heavy_compute(ctx): """CPU-bound worker that runs in separate process""" params = None while not ctx.should_stop(): # Get latest job parameters msg = ctx.recv_latest(timeout=0.01) if msg is not None: params = msg if params is None: continue # CPU-intensive computation n = params.get("n", 1000) result = sum(i * i for i in range(n)) # Publish result ctx.publish({"result": result, "n": n}) with Terminal() as term: w, h = term.size() # Start process task task = ProcessTask(heavy_compute, loop=True) task.start() # Submit initial job task.submit({"n": 10000}) # Render loop for i in range(200): # Check for latest result result = task.peek() if result: text = f"Result: {result['result']}\nN: {result['n']}" else: text = "Computing..." p = Paragraph.from_text(text + "\n\nPress 'q' to quit") p.set_block_title("Process Task", True) term.draw_paragraph(p, (0, 0, w, h)) evt = term.next_event(50) if evt and evt.get("kind") == "key" and evt.get("ch") == ord('q'): break # Clean shutdown task.stop(join=True, terminate=True) ``` -------------------------------- ### Manual Batching with DrawCmd in Python Source: https://context7.com/holo-q/ratatui-py/llms.txt Construct draw commands manually for fine-grained control over rendering. This example shows how to create Paragraph and List widgets and then batch their drawing commands for execution. It requires the ratatui_py library. ```python from ratatui_py import Terminal, Paragraph, List, DrawCmd with Terminal() as term: w, h = term.size() p1 = Paragraph.from_text("Paragraph 1").set_block_title("P1", True) p2 = Paragraph.from_text("Paragraph 2").set_block_title("P2", True) lst = List() lst.append_item("Item A") lst.set_block_title("List", True) # Create draw commands cmds = [ DrawCmd.paragraph(p1, (0, 0, w // 2, 5)), DrawCmd.paragraph(p2, (w // 2, 0, w // 2, 5)), DrawCmd.list(lst, (0, 5, w, h - 5)) ] # Execute batched draw ok = term.draw_frame(cmds) print(f"Frame success: {ok}") term.next_event(2000) ``` -------------------------------- ### Convert Asciinema to GIF (asciicast2gif) Source: https://github.com/holo-q/ratatui-py/blob/main/docs/recording.md Converts an asciinema recording to an animated GIF using 'asciicast2gif'. This method requires PhantomJS to be installed or the PHANTOMJS_BIN environment variable to be set. It supports theme selection, speed multiplier, and scale factor adjustments. ```bash asciicast2gif -t solarized-dark -S 2 -s 2 demo.cast docs/assets/dashboard.gif ``` -------------------------------- ### Headless Frame Rendering for Testing in Python Source: https://context7.com/holo-q/ratatui-py/llms.txt Test complete frame compositions by rendering them to a string without a TTY. This example shows how to create Paragraph widgets, define their positions using DrawCmd, and then render the entire frame. It requires the ratatui_py library. ```python from ratatui_py import Paragraph, DrawCmd, headless_render_frame # Create widgets p1 = Paragraph.from_text("Left").set_block_title("L", True) p2 = Paragraph.from_text("Right").set_block_title("R", True) # Create frame commands cmds = [ DrawCmd.paragraph(p1, (0, 0, 20, 5)), DrawCmd.paragraph(p2, (20, 0, 20, 5)) ] # Render frame to string (80x24 terminal) output = headless_render_frame(80, 24, cmds) # Verify output assert "Left" in output assert "Right" in output print(output) ``` -------------------------------- ### Convert GIF to MP4 with FFmpeg Source: https://github.com/holo-q/ratatui-py/blob/main/docs/recording.md Converts an existing GIF file to an MP4 video using FFmpeg. This is useful for achieving smoother playback in browsers. It optimizes the video for fast start and ensures pixel format compatibility, while also scaling the video dimensions to be even. ```bash ffmpeg -y -i docs/assets/dashboard.gif -movflags +faststart -pix_fmt yuv420p \ -vf "scale=trunc(iw/2)*2:trunc(ih/2)*2" docs/assets/dashboard.mp4 ``` -------------------------------- ### Python Sparkline for Compact Data Visualization in Ratatui-Py Source: https://context7.com/holo-q/ratatui-py/llms.txt Illustrates the use of Sparkline for creating compact, inline data visualizations within a terminal application using ratatui-py. It shows how to set data, maximum value, style, and a block title. Ensure ratatui-py is installed. ```python from ratatui_py import Terminal, Sparkline, Style, Color with Terminal() as term: w, h = term.size() sparkline = Sparkline() data = [1, 3, 2, 5, 4, 8, 6, 10, 7, 9] sparkline.set_values(data) sparkline.set_max(15) sparkline.set_style(Style(fg=Color.LightGreen)) sparkline.set_block_title("Trend", True) term.draw_sparkline(sparkline, (0, 0, w, 5)) term.next_event(5000) ``` -------------------------------- ### Convert Asciinema to GIF (asciinema-agg) Source: https://github.com/holo-q/ratatui-py/blob/main/docs/recording.md Converts an asciinema recording to an animated GIF using the 'asciinema-agg' tool. This tool can be installed via Homebrew or cargo. It allows setting the frames per second (fps) and idle time before conversion. Recommended for creating embeddable GIFs. ```bash asciinema-agg --fps 60 --idle 2 demo.cast docs/assets/dashboard.gif ``` -------------------------------- ### Tabs Widget for Navigation Source: https://context7.com/holo-q/ratatui-py/llms.txt Shows how to create and render a Tabs widget for navigation within a terminal UI. This example configures tab titles, highlights the selected tab, sets a divider, and applies custom styles for selected and unselected tabs. ```python from ratatui_py import Terminal, Tabs, Style, Color with Terminal() as term: w, h = term.size() tabs = Tabs() tabs.set_titles(["Home", "Settings", "About"]) tabs.set_selected(1) tabs.set_divider(" | ") tabs.set_styles( unselected=Style(fg=Color.Gray), selected=Style(fg=Color.LightBlue).bold() ) tabs.set_block_title("Navigation", True) term.draw_tabs(tabs, (0, 0, w, 3)) term.next_event(5000) ``` -------------------------------- ### Convert Asciinema to SVG (svg-term) Source: https://github.com/holo-q/ratatui-py/blob/main/docs/recording.md Converts an asciinema recording to an SVG file using the 'svg-term-cli' Node.js package. This method is suitable for creating vector-based animations that can be embedded in documentation. It requires Node.js and npm for installation. Options include adding a window frame, specifying dimensions, and font size. ```bash npm i -g svg-term-cli svg-term --cast demo.cast --out docs/assets/dashboard.svg \ --window --width 100 --height 30 --font-size 14 ``` -------------------------------- ### Enable Advanced FFI Diagnostics and Backtraces Source: https://github.com/holo-q/ratatui-py/blob/main/README.md Activates a suite of advanced diagnostic flags for the FFI (Foreign Function Interface) layer, including Rust backtraces, FFI call tracing, and logging. This setup is crucial for deep debugging of Rust-related issues within Ratatui-Py. ```bash # or enable flags individually RUST_BACKTRACE=full \ RATATUI_FFI_TRACE=1 \ RATATUI_FFI_NO_ALTSCR=1 \ RATATUI_FFI_PROFILE=debug \ RATATUI_FFI_LOG=ratatui_ffi.log \ uv run ratatui-demos ``` -------------------------------- ### Python Canvas Drawing with Shapes in Ratatui-Py Source: https://context7.com/holo-q/ratatui-py/llms.txt Shows how to use the Canvas widget in ratatui-py to draw various geometric shapes like rectangles, lines, and points. This example utilizes custom coordinate bounds and styles for elements. The ratatui-py library is a prerequisite. ```python from ratatui_py import Terminal, Canvas, Style, rgb with Terminal() as term: w, h = term.size() # Create canvas with coordinate bounds canvas = Canvas(0.0, 100.0, 0.0, 100.0) # Add shapes canvas.add_rect(10, 10, 80, 60, Style(fg=rgb(0, 255, 255))) canvas.add_line(10, 10, 90, 70, Style(fg=rgb(255, 128, 0))) # Add multiple points points = [(20, 20), (30, 40), (40, 30), (50, 60), (60, 50)] canvas.add_points(points, Style(fg=rgb(255, 0, 255))) canvas.set_block_title("Canvas Demo", True) term.draw_canvas(canvas, (0, 0, w, h)) term.next_event(5000) ``` -------------------------------- ### Python Typed Terminal Layout with Rect Dataclass in Ratatui-Py Source: https://context7.com/holo-q/ratatui-py/llms.txt Illustrates using the typed Rect dataclass for terminal layout management in ratatui-py, offering better IDE support. This example demonstrates creating Rect objects, applying margins, and splitting areas, with the resulting regions also being Rect objects. Requires ratatui-py. ```python from ratatui_py import Terminal, Paragraph, Rect, margin_rect, split_v_rect with Terminal() as term: w, h = term.size() # Use Rect dataclass area = Rect(0, 0, w, h) body = margin_rect(area, all=2) # Split returns typed Rect objects left, right = split_v_rect(body, 0.5, 0.5, gap=1) # Access rect properties print(f"Left rect: x={left.x}, y={left.y}, right={left.right}") p1 = Paragraph.from_text("Left").set_block_title("Left", True) p2 = Paragraph.from_text("Right").set_block_title("Right", True) term.draw_paragraph(p1, left) term.draw_paragraph(p2, right) term.next_event(5000) ``` -------------------------------- ### Run Ratatui-Py Demos (Bash) Source: https://github.com/holo-q/ratatui-py/blob/main/docs/demos.md Demonstrates how to execute the main ratatui-py demo entrypoint and specific demo applications from the command line using bash. This is useful for quickly testing the library's features. ```bash ratatui-demos # or run specific ones ratatui-hello ratatui-widgets ratatui-life ratatui-dashboard ``` -------------------------------- ### Run a Simple Application Loop Source: https://github.com/holo-q/ratatui-py/blob/main/README.md Illustrates how to use the `App` helper class for managing a typical application's render and event handling loop. It defines `render` and `on_event` functions to control the UI and application flow, respectively. ```python from ratatui_py import App, Terminal, Paragraph def render(term: Terminal, state: dict) -> None: w, h = term.size() p = Paragraph.from_text("Hello ratatui!\nPress q to quit.") p.set_block_title("Demo", True) term.draw_paragraph(p, (0, 0, w, h)) def on_event(term: Terminal, evt: dict, state: dict) -> bool: return not (evt.get("kind") == "key" and evt.get("ch") in (ord('q'), ord('Q'))) App(render=render, on_event=on_event, tick_ms=250).run({}) ``` -------------------------------- ### Record Asciinema Cast Source: https://github.com/holo-q/ratatui-py/blob/main/docs/recording.md Records terminal output into a 'demo.cast' file. This is the first step for all recording methods. It requires the 'ratatui-dashboard' command to be executed. ```bash asciinema rec demo.cast -c "ratatui-dashboard" ``` -------------------------------- ### Use prelude for convenient access to ratatui_py components Source: https://github.com/holo-q/ratatui-py/blob/main/README.md The ratatui_py.prelude module provides a convenient way to import commonly used components such as Terminal, Paragraph, Rect, and Color, simplifying import statements. ```python from ratatui_py.prelude import * # Terminal, Paragraph, Rect, Color, etc. ``` -------------------------------- ### Basic Terminal UI with Paragraph in Python Source: https://github.com/holo-q/ratatui-py/blob/main/docs/index.md Demonstrates the basic usage of ratatui-py to create a simple terminal UI. It initializes a terminal, creates a Paragraph widget with text and a title, and draws it to the terminal. The `next_event` call keeps the UI displayed for a duration. Requires the `ratatui_py` library. ```python from ratatui_py import Terminal, Paragraph with Terminal() as term: p = Paragraph.from_text("Hello from Python!\nThis is ratatui.") p.set_block_title("Demo", True) term.draw_paragraph(p) term.next_event(3000) ``` -------------------------------- ### Create and Draw a Paragraph Source: https://github.com/holo-q/ratatui-py/blob/main/README.md Demonstrates the basic usage of the `Terminal` and `Paragraph` classes to display simple text in the terminal. It initializes a terminal session, creates a paragraph with text and a title, draws it, and waits for user input to exit. ```python from ratatui_py import Terminal, Paragraph with Terminal() as term: p = Paragraph.from_text("Hello from Python!\nThis is ratatui.\n\nPress any key to exit.") p.set_block_title("Demo", show_border=True) term.draw_paragraph(p) term.next_event(5000) # wait for key or 5s ``` -------------------------------- ### Upload Asciinema Cast to asciinema.org Source: https://github.com/holo-q/ratatui-py/blob/main/docs/recording.md Uploads a recorded asciinema cast file directly to the asciinema.org platform. This allows for easy sharing and embedding of terminal recordings via a provided URL. ```bash asciinema upload demo.cast ``` -------------------------------- ### Record Ratatui-Py Demos with Asciinema (Hide Code Pane) Source: https://github.com/holo-q/ratatui-py/blob/main/README.md Records the Ratatui-Py demo hub, optimizing for minimal churn by hiding the code pane. Similar to the dashboard recording, it configures dimensions and idle time, utilizing `RATATUI_PY_RECORDING`, `RATATUI_PY_NO_CODE`, and `RATATUI_PY_FPS` environment variables. ```bash # Or record the demo hub (hide code pane for minimal churn) ascinema rec -q --cols 80 --rows 24 --idle-time-limit 2 \ -c 'RATATUI_PY_RECORDING=1 RATATUI_PY_NO_CODE=1 RATATUI_PY_FPS=60 uv run ratatui-demos' \ docs/assets/demos.cast --overwrite ``` -------------------------------- ### Initialize Terminal Session with Context Manager Source: https://context7.com/holo-q/ratatui-py/llms.txt Demonstrates basic terminal initialization and rendering of a paragraph widget using a context manager for automatic resource cleanup. It waits for user input or a timeout before exiting. ```python from ratatui_py import Terminal, Paragraph # Basic terminal session with Terminal() as term: p = Paragraph.from_text("Hello from Python!\nThis is ratatui.\n\nPress any key to exit.") p.set_block_title("Demo", show_border=True) term.draw_paragraph(p) term.next_event(5000) # wait for key press or 5 seconds ``` -------------------------------- ### Draw List, Table, and Gauge Widgets Source: https://github.com/holo-q/ratatui-py/blob/main/README.md Demonstrates the creation and drawing of multiple Ratatui widgets: `List`, `Table`, and `Gauge`. Each widget is configured with its specific properties and then drawn onto the terminal at defined positions. ```python from ratatui_py import Terminal, List, Table, Gauge, Style, FFI_COLOR with Terminal() as term: lst = List() for i in range(5): lst.append_item(f"Item {i}") lst.set_selected(2) lst.set_block_title("List", True) tbl = Table() tbl.set_headers(["A", "B", "C"]) tbl.append_row(["1", "2", "3"]) tbl.append_row(["x", "y", "z"]) tbl.set_block_title("Table", True) g = Gauge().ratio(0.42).label("42%") g.set_block_title("Gauge", True) term.draw_list(lst, (0,0,20,6)) term.draw_table(tbl, (0,6,20,6)) term.draw_gauge(g, (0,12,20,3)) ``` -------------------------------- ### Record Ratatui-Py Dashboard with Asciinema Source: https://github.com/holo-q/ratatui-py/blob/main/README.md Records the Ratatui-Py dashboard, ensuring smooth and flicker-free output. It sets specific dimensions (80x24) and an idle time limit for the recording. The `RATATUI_PY_RECORDING` and `RATATUI_PY_FPS` environment variables are used to configure the recording behavior. ```bash # Record the dashboard only (80x24), smooth and flicker‑free ascinema rec -q --cols 80 --rows 24 --idle-time-limit 2 \ -c 'RATATUI_PY_RECORDING=1 RATATUI_PY_FPS=60 uv run ratatui-dashboard' \ docs/assets/dashboard.cast --overwrite ``` -------------------------------- ### Bind Actions to Key Combinations with Keymap in Python Source: https://context7.com/holo-q/ratatui-py/llms.txt Illustrates how to create a keymap to bind specific functions or actions to key combinations (e.g., Ctrl+S for save, 'q' or Esc for quit). It uses the Keymap, KeyCode, and KeyMods classes for flexible input handling. ```python from ratatui_py import Terminal, Keymap, KeyCode, KeyMods, Paragraph def handle_save(): print("Saving...") def handle_quit(): print("Quitting...") return False with Terminal() as term: w, h = term.size() # Create keymap km = Keymap() km.bind(KeyCode.Char, KeyMods.CTRL, lambda e: handle_save() if e.ch == ord('s') else None) km.bind(KeyCode.Char, KeyMods.NONE, lambda e: handle_quit() if e.ch == ord('q') else None) km.bind(KeyCode.Esc, KeyMods.NONE, lambda e: handle_quit()) while True: p = Paragraph.from_text("Press Ctrl+S to save, q or Esc to quit") p.set_block_title("Keymap Demo", True) term.draw_paragraph(p, (0, 0, w, h)) evt = term.next_event_typed(100) if evt and km.handle(evt) is False: break ``` -------------------------------- ### Run Lint, Type Check, and Tests Source: https://github.com/holo-q/ratatui-py/blob/main/CONTRIBUTING.md Commands to execute code quality checks including linting with Ruff, type checking with Mypy, and running tests with Pytest. These commands help ensure code consistency and correctness. ```shell ruff check . mypy src pytest -q ``` -------------------------------- ### Application Runner with Event Loop and State Management Source: https://context7.com/holo-q/ratatui-py/llms.txt Utilizes the `App` helper to create an event-driven terminal application. It defines rendering logic, event handling (including quitting and incrementing a counter), and a tick handler for periodic updates. The application runs with a specified state dictionary and tick interval. ```python from ratatui_py import App, Terminal, Paragraph def render(term: Terminal, state: dict) -> None: w, h = term.size() count = state.get('count', 0) p = Paragraph.from_text(f"Counter: {count}\nPress q to quit, space to increment.") p.set_block_title("Demo", True) term.draw_paragraph(p, (0, 0, w, h)) def on_event(term: Terminal, evt: dict, state: dict) -> bool: if evt.get("kind") == "key": ch = evt.get("ch", 0) if ch in (ord('q'), ord('Q')): return False # stop the app elif ch == ord(' '): state['count'] = state.get('count', 0) + 1 return True # continue running def on_tick(term: Terminal, state: dict) -> None: # Called every tick_ms milliseconds state['ticks'] = state.get('ticks', 0) + 1 app = App( render=render, on_event=on_event, on_tick=on_tick, tick_ms=250, clear_each_frame=False ) app.run({'count': 0, 'ticks': 0}) ``` -------------------------------- ### Create Terminal Session with Spans Source: https://github.com/holo-q/ratatui-py/blob/main/README.md Shows how to create a raw and cleared terminal session and render text with per-span styling, including custom colors and bold attributes. It utilizes `terminal_session`, `Style`, and `rgb` for flexible text formatting. ```python from ratatui_py import terminal_session, Paragraph, Style, rgb with terminal_session(raw=True, alt=True, clear=True) as term: spans = [("Hello ", Style()), ("world", Style(fg=rgb(0,180,255)).bold())] p = Paragraph.new_empty().append_lines_spans([spans]) term.draw_paragraph(p, (0,0,*term.size())) term.next_event(1000) ``` -------------------------------- ### Draw Canvas with Shapes and Logo Source: https://github.com/holo-q/ratatui-py/blob/main/README.md Shows how to use the `Canvas` widget for drawing custom shapes like rectangles and lines with specified styles and colors. It also demonstrates drawing the Ratatui logo if the terminal height permits. ```python from ratatui_py import Terminal, Canvas, Style, rgb with Terminal() as term: w, h = term.size() cv = Canvas(0.0, 100.0, 0.0, 100.0) cv.add_rect(10,10,80,60, Style(fg=rgb(0,255,255))) cv.add_line(10,10,90,70, Style(fg=rgb(255,128,0))) term.draw_canvas(cv, (0,0,w,h)) if h >= 12: term.draw_logo((0, h-12, w, 12)) ``` -------------------------------- ### Create Rich Text with Styled Spans in Python Source: https://context7.com/holo-q/ratatui-py/llms.txt Demonstrates how to create styled text within a paragraph using multiple spans, including bold, italic, underlined, and RGB color formatting. It utilizes the Paragraph and Style classes from ratatui_py. ```python from ratatui_py import Terminal, Paragraph, Style, Color, Mod, rgb with Terminal() as term: w, h = term.size() # Create paragraph with styled spans p = Paragraph.new_empty() # Add styled spans on same line p.append_span("Bold ", Style().bold()) p.append_span("Italic ", Style().italic()) p.append_span("Underlined ", Style().underlined()) p.line_break() # Add colored text p.append_span("Red ", Style(fg=Color.Red)) p.append_span("Green ", Style(fg=Color.Green)) p.append_span("Blue", Style(fg=Color.Blue)) p.line_break() # RGB colors and combinations p.append_span( "Custom Color Bold Italic", Style(fg=rgb(255, 128, 0), bg=rgb(50, 50, 50)).bold().italic() ) p.set_block_title("Styled Text", True) term.draw_paragraph(p, (0, 0, w, h)) term.next_event(5000) ``` -------------------------------- ### Bind keys to actions using Keymap and KeyCode Source: https://github.com/holo-q/ratatui-py/blob/main/README.md The Keymap utility facilitates the binding of key combinations (KeyCode and KeyMods) to specific handler functions. This allows for intuitive keyboard navigation and command execution within the terminal application. ```python from ratatui_py import Terminal, Keymap, KeyCode, KeyMods km = Keymap() km.bind(KeyCode.Left, KeyMods.NONE, lambda e: print('←')) with Terminal() as term: evt = term.next_event_typed(100) if evt: km.handle(evt) ``` -------------------------------- ### Use Rect, margin_rect, and split_v_rect for UI layout Source: https://github.com/holo-q/ratatui-py/blob/main/README.md The ratatui_py.util module provides Rect, Point, and Size dataclasses for defining UI areas. Helpers like margin_rect and split_v_rect allow for easy manipulation and division of these Rect objects, supporting both Rect objects and tuples as input. ```python from ratatui_py import Rect, margin_rect, split_v_rect area = Rect(0, 0, 80, 24) body = margin_rect(area, all=1) left, right = split_v_rect(body, 0.4, 0.6, gap=1) ``` -------------------------------- ### Full Terminal Session with Raw Mode and Alt Screen Source: https://context7.com/holo-q/ratatui-py/llms.txt Configures a terminal session with raw mode enabled, alternate screen usage, and screen clearing for complete display control. It then renders a styled paragraph with colored text spans and draws it to a specific rectangle on the terminal. ```python from ratatui_py import terminal_session, Paragraph, Style, rgb # Session with raw mode, alternate screen, and clear with terminal_session(raw=True, alt=True, clear=True) as term: w, h = term.size() # Create styled paragraph with colored spans spans = [ ("Hello ", Style()), ("world", Style(fg=rgb(0, 180, 255)).bold()) ] p = Paragraph.new_empty().append_lines_spans([spans]) # Draw to specific rectangle (x, y, width, height) term.draw_paragraph(p, (0, 0, w, h)) term.next_event(1000) ``` -------------------------------- ### Convert Asciinema Cast to GIF with asciinema-agg Source: https://github.com/holo-q/ratatui-py/blob/main/README.md Converts a recorded asciinema cast file (`.cast`) into a GIF format, suitable for previews on platforms like GitHub READMEs. It allows specifying the desired frames per second (FPS) and idle time for the GIF. ```bash # Using asciinema-agg (install locally or use its container image) ascinema-agg --fps 30 --idle 2 docs/assets/dashboard.cast docs/assets/dashboard.gif ``` -------------------------------- ### Compose Widgets in a Frame Context for Flicker-Free Updates in Python Source: https://context7.com/holo-q/ratatui-py/llms.txt Demonstrates using the `term.frame()` context manager to compose multiple widgets (Paragraph, List, Gauge) within a single frame for flicker-free rendering. This is crucial for smooth terminal UI updates. ```python from ratatui_py import Terminal, Paragraph, List, Gauge, Rect with Terminal() as term: w, h = term.size() # Create widgets p = Paragraph.from_text("Header Section") p.set_block_title("Header", True) lst = List() lst.append_item("Item 1") lst.append_item("Item 2") lst.set_block_title("List", True) g = Gauge().ratio(0.75).label("75%") g.set_block_title("Progress", True) # Use frame context for batched draw with term.frame() as f: f.paragraph(p, Rect(0, 0, w, 3)) f.list(lst, Rect(0, 3, w // 2, h - 6)) f.gauge(g, Rect(0, h - 3, w, 3)) # f.ok is True if frame rendered successfully print(f"Frame rendered: {f.ok}") term.next_event(2000) ``` -------------------------------- ### Render Multiple Widgets: List, Table, and Gauge Source: https://context7.com/holo-q/ratatui-py/llms.txt Demonstrates rendering multiple Ratatui widgets—List, Table, and Gauge—within a single terminal frame. Each widget is configured with specific content, styling, and titles, and then drawn to designated rectangular areas on the terminal. ```python from ratatui_py import Terminal, List, Table, Gauge, Style, FFI_COLOR with Terminal() as term: w, h = term.size() # Create a list widget lst = List() for i in range(5): lst.append_item(f"Item {i}") lst.set_selected(2) lst.set_block_title("List", True) lst.set_highlight_symbol("> ") # Create a table widget tbl = Table() tbl.set_headers(["Column A", "Column B", "Column C"]) tbl.append_row(["1", "2", "3"]) tbl.append_row(["x", "y", "z"]) tbl.append_row(["foo", "bar", "baz"]) tbl.set_selected(1) tbl.set_block_title("Table", True) # Create a gauge widget g = Gauge().ratio(0.42).label("42%") g.set_block_title("Gauge", True) # Draw widgets in different regions (x, y, width, height) term.draw_list(lst, (0, 0, 20, 6)) term.draw_table(tbl, (0, 6, 40, 6)) term.draw_gauge(g, (0, 12, 40, 3)) term.next_event(5000) ``` -------------------------------- ### Batch Add Styled Lines to Paragraph in Python Source: https://context7.com/holo-q/ratatui-py/llms.txt Shows how to efficiently add multiple styled lines to a paragraph at once using the `append_lines_spans` method. This is useful for adding pre-formatted text content in batches. ```python from ratatui_py import Terminal, Paragraph, Style, Color with Terminal() as term: w, h = term.size() p = Paragraph.new_empty() # Add multiple lines with spans lines = [ [("Line 1 ", Style(fg=Color.Red)), ("continued", Style(fg=Color.Green))], [("Line 2 ", Style(fg=Color.Blue)), ("with style", Style().bold())], [("Line 3 ", Style().italic()), ("final", Style().underlined())] ] p.append_lines_spans(lines) p.set_block_title("Batch Spans", True) term.draw_paragraph(p, (0, 0, w, h)) term.next_event(5000) ``` -------------------------------- ### Enable Rich Diagnostics with Ratatui-Py Source: https://github.com/holo-q/ratatui-py/blob/main/README.md Enables comprehensive diagnostics for Ratatui-Py applications, particularly useful for debugging issues without disrupting terminal scrollback. The `RATATUI_PY_DEBUG=1` environment variable activates these diagnostics. ```bash # rich diagnostics without alt screen RATATUI_PY_DEBUG=1 uv run ratatui-demos ``` -------------------------------- ### Background Tasks for GIL-Releasing Work in Python Source: https://context7.com/holo-q/ratatui-py/llms.txt Utilize BackgroundTask for operations that release the Global Interpreter Lock (GIL), such as FFI, I/O, or NumPy operations. This allows for responsive UIs by running work in a separate thread. It depends on the ratatui_py library and the `time` module. ```python from ratatui_py import Terminal, Paragraph, BackgroundTask import time def compute_worker(task): """Worker that releases GIL (e.g., FFI, I/O, NumPy)""" result = 0 for i in range(100): if task.stopped(): break result += i time.sleep(0.01) # simulate I/O (releases GIL) return result with Terminal() as term: w, h = term.size() # Start background task task = BackgroundTask(compute_worker, loop=False) task.start(daemon=True) # Render loop for _ in range(100): result = task.peek() text = f"Computing...\nResult: {result if result else 'waiting'}" p = Paragraph.from_text(text) p.set_block_title("Background Task", True) term.draw_paragraph(p, (0, 0, w, h)) evt = term.next_event(50) if evt and evt.get("kind") == "key": break task.stop(join=True, timeout=1.0) ``` -------------------------------- ### Python Terminal Layout Splitting with Margin and Split Functions in Ratatui-Py Source: https://context7.com/holo-q/ratatui-py/llms.txt Demonstrates how to manage terminal layout using margin and split functions provided by ratatui-py. This code divides the terminal area into sections with specified gaps and percentages, then renders paragraphs in each section. Requires ratatui-py. ```python from ratatui_py import Terminal, Paragraph, margin, split_v, split_h with Terminal() as term: w, h = term.size() area = (0, 0, w, h) # Add margins around the area body = margin(area, all=1) # Split vertically into left (40%) and right (60%) with 1-char gap left, right = split_v(body, 0.4, 0.6, gap=1) # Split left area horizontally into 3 rows top, middle, bottom = split_h(left, 0.2, 0.5, 0.3, gap=1) # Create paragraphs p1 = Paragraph.from_text("Top Section").set_block_title("Top", True) p2 = Paragraph.from_text("Middle Section").set_block_title("Middle", True) p3 = Paragraph.from_text("Bottom Section").set_block_title("Bottom", True) p4 = Paragraph.from_text("Right Panel").set_block_title("Right", True) # Draw to each region term.draw_paragraph(p1, top) term.draw_paragraph(p2, middle) term.draw_paragraph(p3, bottom) term.draw_paragraph(p4, right) term.next_event(5000) ``` -------------------------------- ### Handle Keyboard and Mouse Events with Typed API in Python Source: https://context7.com/holo-q/ratatui-py/llms.txt Demonstrates how to capture and process various user input events, including keyboard presses (keys, modifiers, special keys) and mouse actions (position, type), using the `next_event_typed` method. This allows for interactive terminal applications. ```python from ratatui_py import Terminal, Paragraph, KeyCode, KeyMods with Terminal() as term: w, h = term.size() messages = [] while True: # Render current state text = "\n".join(messages[-10:]) # last 10 messages text += "\n\nPress keys, move mouse, or 'q' to quit" p = Paragraph.from_text(text) p.set_block_title("Event Logger", True) term.draw_paragraph(p, (0, 0, w, h)) # Get next event with typed API evt = term.next_event_typed(100) if evt is None: continue if evt.kind == "key": if evt.code == KeyCode.Esc or (evt.code == KeyCode.Char and evt.ch == ord('q')): break elif evt.code == KeyCode.Left: messages.append("Left arrow pressed") elif evt.code == KeyCode.Right: messages.append("Right arrow pressed") elif evt.mods & KeyMods.CTRL: messages.append(f"Ctrl+{chr(evt.ch)}") else: messages.append(f"Key: {chr(evt.ch) if evt.ch > 31 else f'code={evt.code}'}") elif evt.kind == "mouse": messages.append(f"Mouse: ({evt.x}, {evt.y}) kind={evt.mouse_kind}") elif evt.kind == "resize": w, h = evt.width, evt.height messages.append(f"Resized to {w}x{h}") ``` -------------------------------- ### Headless Widget Rendering in Python Source: https://context7.com/holo-q/ratatui-py/llms.txt Render widgets like Paragraph, List, Table, and Gauge to strings without a TTY, useful for testing. This function requires the widget object and terminal dimensions. It depends on the ratatui_py library. ```python from ratatui_py import Paragraph, List, Table, Gauge from ratatui_py import headless_render_paragraph, headless_render_list from ratatui_py import headless_render_table, headless_render_gauge # Render paragraph to string p = Paragraph.from_text("Hello\nWorld") p.set_block_title("Test", True) output = headless_render_paragraph(40, 10, p) print(output) # Render list lst = List() lst.append_item("Item 1") lst.append_item("Item 2") lst.set_block_title("List", True) output = headless_render_list(40, 10, lst) assert "Item 1" in output # Render table tbl = Table() tbl.set_headers(["A", "B"]) tbl.append_row(["1", "2"]) output = headless_render_table(40, 10, tbl) assert "A" in output and "B" in output # Render gauge g = Gauge().ratio(0.5).label("50%") output = headless_render_gauge(40, 5, g) assert "50%" in output ``` -------------------------------- ### Handle typed events with Terminal and KeyCode Source: https://github.com/holo-q/ratatui-py/blob/main/README.md The Terminal class provides methods for interacting with the terminal, including fetching typed events. The KeyCode enum helps in identifying specific key presses, enabling conditional logic for user input. ```python from ratatui_py import Terminal, KeyCode with Terminal() as term: evt = term.next_event_typed(100) if evt and evt.kind == 'key' and evt.code == KeyCode.Left: ... # move selection ``` -------------------------------- ### Draw multiple paragraphs within a terminal frame Source: https://github.com/holo-q/ratatui-py/blob/main/README.md The Terminal class's frame context manager allows batched drawing operations. Paragraph widgets can be rendered to specific Rect areas within the frame, ensuring all updates are applied atomically. ```python from ratatui_py import Terminal, Paragraph, Rect with Terminal() as term: p1 = Paragraph.from_text("Left") p2 = Paragraph.from_text("Right") with term.frame() as f: f.paragraph(p1, Rect(0, 0, 20, 3)) f.paragraph(p2, Rect(20, 0, 20, 3)) ``` -------------------------------- ### Run CPU-bound work in a separate process with ProcessTask Source: https://github.com/holo-q/ratatui-py/blob/main/README.md The ProcessTask utility allows running CPU-bound work in a separate process to bypass the Python GIL. It provides mechanisms for receiving jobs, publishing results, and cooperative shutdown. This is ideal for pure-Python CPU-intensive tasks. ```python from ratatui_py import ProcessTask def worker(ctx): params = None while not ctx.should_stop(): msg = ctx.recv_latest(timeout=0.01) if msg is not None: params = msg if params is None: continue result = do_heavy_compute(params) # pure CPU ok here ctx.publish(result) task = ProcessTask(worker, loop=True) task.start() task.submit({"zoom": 1.25}) # In your render loop: latest = task.peek() # On shutdown: task.stop(join=True, terminate=True) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.