### Flex Start - Example 1 Source: https://docs.rs/ratatui/0.30.2/ratatui/layout/enum.Flex.html?search=u32+-%3E+bool Demonstrates the 'Start' Flex alignment with Percentage, Length, and Fixed constraints. ```text <------------------------------------80 px-------------------------------------> ┌────16 px─────┐┌──────20 px───────┐┌──────20 px───────┐ │Percentage(20)││ Length(20) ││ Fixed(20) │ └──────────────┘└──────────────────┘└──────────────────┘ ``` -------------------------------- ### Flex Start - Example 2 Source: https://docs.rs/ratatui/0.30.2/ratatui/layout/enum.Flex.html?search=u32+-%3E+bool Illustrates the 'Start' Flex alignment with two Max constraints. ```text <------------------------------------80 px-------------------------------------> ┌──────20 px───────┐┌──────20 px───────┐ │ Max(20) ││ Max(20) │ └──────────────────┘└──────────────────┘ ``` -------------------------------- ### Flex Start - Example 3 Source: https://docs.rs/ratatui/0.30.2/ratatui/layout/enum.Flex.html?search=u32+-%3E+bool Shows the 'Start' Flex alignment with a single Max constraint. ```text <------------------------------------80 px-------------------------------------> ┌──────20 px───────┐ │ Max(20) │ └──────────────────┘ ``` -------------------------------- ### Initialize Terminal with TermwizBackend Source: https://docs.rs/ratatui/0.30.2/ratatui/backend/struct.TermwizBackend.html Example of initializing a new TermwizBackend and a Ratatui Terminal. This setup automatically enables raw mode and switches to the alternate screen. Use this when you want the backend to manage terminal state. ```rust use ratatui::Terminal; use ratatui::backend::TermwizBackend; let backend = TermwizBackend::new()?; let mut terminal = Terminal::new(backend)?; terminal.clear()?; terminal.draw(|frame| { // -- snip -- })?; ``` -------------------------------- ### Example Searches Source: https://docs.rs/ratatui/0.30.2/ratatui/widgets/struct.List.html?search= Demonstrates example search queries for exploring Rust types and conversions. These examples can help users find relevant functions and types. ```text Example searches: * std::vec * u32 -> bool * Option, (T -> U) -> Option ``` -------------------------------- ### Size Examples Source: https://docs.rs/ratatui/0.30.2/ratatui/layout/struct.Size.html?search=u32+-%3E+bool Examples demonstrating the creation and usage of the Size struct. ```rust use ratatui_core::layout::{Rect, Size}; let size = Size::new(80, 24); assert_eq!(size.area(), 1920); let size = Size::from((80, 24)); let size = Size::from(Rect::new(0, 0, 80, 24)); assert_eq!(size.area(), 1920); ``` -------------------------------- ### Flex Start: Mixed Constraints Source: https://docs.rs/ratatui/0.30.2/ratatui/prelude/layout/enum.Flex.html?search=std%3A%3Avec Illustrates the 'Start' alignment with a mix of Percentage, Length, and Fixed constraints. ```text <------------------------------------80 px-------------------------------------> ┌────16 px─────┐┌──────20 px───────┐┌──────20 px───────┐ │Percentage(20)││ Length(20) ││ Fixed(20) │ └──────────────┘└──────────────────┘└──────────────────┘ ``` -------------------------------- ### CrosstermBackend Initialization and Terminal Setup Source: https://docs.rs/ratatui/0.30.2/ratatui/backend/struct.CrosstermBackend.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E This example demonstrates how to create a CrosstermBackend using stdout or stderr, initialize a Terminal with it, enable raw mode, enter alternate screen, and perform basic terminal operations before disabling raw mode and leaving the alternate screen. ```rust use std::io::{stderr, stdout}; use crossterm::ExecutableCommand; use crossterm::terminal::{ EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode, }; use ratatui::Terminal; use ratatui::backend::CrosstermBackend; let mut backend = CrosstermBackend::new(stdout()); // or let backend = CrosstermBackend::new(stderr()); let mut terminal = Terminal::new(backend)?; enable_raw_mode()?; stdout().execute(EnterAlternateScreen)?; terminal.clear()?; terminal.draw(|frame| { // -- snip -- })?; stdout().execute(LeaveAlternateScreen)?; disable_raw_mode()?; ``` -------------------------------- ### CrosstermBackend Initialization and Terminal Setup Source: https://docs.rs/ratatui/0.30.2/ratatui/backend/struct.CrosstermBackend.html?search= This example demonstrates how to initialize a CrosstermBackend with stdout or stderr, set up raw mode, enter alternate screen, clear the terminal, and draw content using the Terminal struct. It also shows how to leave alternate screen and disable raw mode. ```rust use std::io::{stderr, stdout}; use crossterm::ExecutableCommand; use crossterm::terminal::{ EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode, }; use ratatui::Terminal; use ratatui::backend::CrosstermBackend; let mut backend = CrosstermBackend::new(stdout()); // or let backend = CrosstermBackend::new(stderr()); let mut terminal = Terminal::new(backend)?; enable_raw_mode()?; stdout().execute(EnterAlternateScreen)?; terminal.clear()?; terminal.draw(|frame| { // -- snip -- })?; stdout().execute(LeaveAlternateScreen)?; disable_raw_mode()?; ``` -------------------------------- ### Example Searches Source: https://docs.rs/ratatui/0.30.2/ratatui/style/palette/tailwind/constant.GRAY.html?search=std%3A%3Avec These are example search queries that can be used to find relevant documentation or code. ```text std::vec ``` ```text u32 -> bool ``` ```text Option, (T -> U) -> Option ``` -------------------------------- ### Flex Legacy - Example 1 Source: https://docs.rs/ratatui/0.30.2/ratatui/layout/enum.Flex.html?search=u32+-%3E+bool An example illustrating 'Legacy' Flex behavior with Min and Max constraints. ```text <------------------------------------80 px-------------------------------------> ┌──────────────────────────60 px───────────────────────────┐┌──────20 px───────┐ │ Min(20) ││ Max(20) │ └──────────────────────────────────────────────────────────┘└──────────────────┘ ``` -------------------------------- ### Simple ratatui run example Source: https://docs.rs/ratatui/0.30.2/ratatui/fn.run.html?search= A basic example demonstrating the use of `ratatui::run` with application logic contained directly within the closure. This is suitable for straightforward applications. ```rust use crossterm::event; fn main() -> Result<(), Box> { ratatui::run(|terminal| { loop { terminal.draw(|frame| frame.render_widget("Hello, world!", frame.area()))?; if event::read()?.is_key_press() { break Ok(()) } } }) } ``` -------------------------------- ### Setting Flex Behavior (Start) Source: https://docs.rs/ratatui/0.30.2/ratatui/layout/struct.Layout.html?search=std%3A%3Avec Configures the layout to align items to the start of the available space using `Flex::Start`. ```rust use ratatui_core::layout::Constraint::*; use ratatui_core::layout::{Flex, Layout}; let layout = Layout::horizontal([Length(20), Length(20), Length(20)]).flex(Flex::Start); ``` -------------------------------- ### Ratio Constraint Example Source: https://docs.rs/ratatui/0.30.2/ratatui/prelude/enum.Constraint.html?search=u32+-%3E+bool Demonstrates the `Ratio` constraint for dividing space proportionally. The examples show how different ratios result in different element sizes. ```rust use ratatui_core::layout::Constraint; // Create a layout with specified lengths for each element let constraints = [Constraint::Ratio(1, 2), Constraint::Ratio(1, 2)]; ``` -------------------------------- ### Example Search: u32 -> bool Source: https://docs.rs/ratatui/0.30.2/ratatui/style/palette/tailwind/constant.FUCHSIA.html?search= Illustrates an example search query for a type transformation from 'u32' to 'bool'. This is useful for finding functions or methods that perform such conversions. ```text u32 -> bool ``` -------------------------------- ### TermionBackend Initialization and Terminal Setup Source: https://docs.rs/ratatui/0.30.2/ratatui/backend/struct.TermionBackend.html?search= Demonstrates how to initialize the TermionBackend with stdout or stderr, and set up a Terminal instance. It also shows clearing the screen and drawing content. ```rust use std::io::{stderr, stdout}; use ratatui::Terminal; use ratatui::backend::TermionBackend; use ratatui::termion::raw::IntoRawMode; use ratatui::termion::screen::IntoAlternateScreen; let writer = stdout().into_raw_mode()?.into_alternate_screen()?; let mut backend = TermionBackend::new(writer); // or let writer = stderr().into_raw_mode()?.into_alternate_screen()?; let backend = TermionBackend::new(stderr()); let mut terminal = Terminal::new(backend)?; terminal.clear()?; terminal.draw(|frame| { // -- snip -- })?; ``` -------------------------------- ### Get Terminal Size Example Source: https://docs.rs/ratatui/0.30.2/ratatui/prelude/backend/trait.Backend.html?search= Shows how to retrieve the dimensions (width and height) of the terminal screen. ```rust use ratatui::{backend::Backend, layout::Size}; assert_eq!(backend.size()?, Size::new(80, 25)); ``` -------------------------------- ### Get Terminal Size Example Source: https://docs.rs/ratatui/0.30.2/ratatui/prelude/backend/trait.Backend.html Shows how to retrieve the current dimensions (width and height) of the terminal screen. Requires `Backend` and `Size` to be in scope. ```rust use ratatui::{backend::Backend, layout::Size}; // Example usage would follow here, e.g.: // let size = backend.size()?; // println!("Terminal size: {}x{}", size.width, size.height); ``` -------------------------------- ### Size Examples Source: https://docs.rs/ratatui/0.30.2/ratatui/layout/struct.Size.html Demonstrates creating a Size from new, a tuple, and a Rect, and computing its area. Ensure `ratatui_core::layout` is imported. ```rust use ratatui_core::layout::{Rect, Size}; let size = Size::new(80, 24); assert_eq!(size.area(), 1920); let size = Size::from((80, 24)); let size = Size::from(Rect::new(0, 0, 80, 24)); assert_eq!(size.area(), 1920); ``` -------------------------------- ### Typical Application Flow with ratatui::run Source: https://docs.rs/ratatui/0.30.2/ratatui/struct.Terminal.html Demonstrates the typical application flow using ratatui::run, which handles terminal setup and teardown. This is the recommended approach for fullscreen applications. ```rust ratatui::run(|terminal| { let mut should_quit = false; while !should_quit { terminal.draw(|frame| { frame.render_widget("Hello, World!", frame.area()); })?; // Handle events, update application state, and set `should_quit = true` to exit. } Ok(()) })?; ``` -------------------------------- ### Get Iterator Elements Satisfying a Predicate with Indices Source: https://docs.rs/ratatui/0.30.2/ratatui/prelude/layout/struct.Rows.html?search=std%3A%3Avec Returns an iterator adaptor that yields the indices of all elements satisfying a predicate, counted from the start of the iterator. ```rust fn positions

(self, predicate: P) -> Positions where Self: Sized, P: FnMut(Self::Item) -> bool, ``` -------------------------------- ### Get Terminal Size Example Source: https://docs.rs/ratatui/0.30.2/ratatui/prelude/trait.Backend.html Shows how to retrieve the current dimensions (width and height) of the terminal screen using the `size` method, returning a `Size` struct. ```rust use ratatui::{backend::Backend, layout::Size}; ``` -------------------------------- ### Direct Command Execution Example Source: https://docs.rs/ratatui/0.30.2/ratatui/backend/struct.TerminaBackend.html Demonstrates direct execution of commands using `execute`. This is suitable for immediate output where no buffering is needed. ```rust fn main() -> io::Result<()> { // will be executed directly io::stdout() .execute(Print("sum:\n".to_string()))? .execute(Print(format!("1 + 1= {} ", 1 + 1)))?; Ok(()) // ==== Output ==== // sum: // 1 + 1 = 2 } ``` -------------------------------- ### Set and Get Cursor Position Example Source: https://docs.rs/ratatui/0.30.2/ratatui/backend/trait.Backend.html Shows how to set the cursor to a specific position on the terminal screen and then verify its position using `get_cursor_position`. The origin (0, 0) is the top-left corner. ```rust use ratatui::{backend::Backend, layout::Position}; backend.set_cursor_position(Position { x: 10, y: 20 })?; assert_eq!(backend.get_cursor_position()?, Position { x: 10, y: 20 }); ``` -------------------------------- ### Example Usage of TerminaBackend Source: https://docs.rs/ratatui/0.30.2/ratatui/backend/struct.TerminaBackend.html?search= Demonstrates how to create and use TerminaBackend with a Terminal. It involves setting up the terminal, creating the backend, and then initializing a Ratatui Terminal with this backend. ```rust use ratatui::Terminal; use ratatui::backend::TerminaBackend; use ratatui::termina::{PlatformTerminal, Terminal as _}; let mut output = PlatformTerminal::new()?; output.enter_raw_mode()?; let backend = TerminaBackend::new(output); let mut terminal = Terminal::new(backend)?; terminal.draw(|frame| { // -- snip -- })?; ``` -------------------------------- ### Stateful List Rendering Source: https://docs.rs/ratatui/0.30.2/ratatui/widgets/struct.List.html Demonstrates how to render a stateful List widget. The `ListState` must be stored outside the render function. This example shows basic setup with a block, highlight style, and symbol. ```rust use ratatui::Frame; use ratatui::layout::Rect; use ratatui::style::{Style, Stylize}; use ratatui::widgets::{Block, List, ListState}; // This should be stored outside of the function in your application state. let mut state = ListState::default(); let items = ["Item 1", "Item 2", "Item 3"]; let list = List::new(items) .block(Block::bordered().title("List")) .highlight_style(Style::new().reversed()) .highlight_symbol(">>") .repeat_highlight_symbol(true); frame.render_stateful_widget(list, area, &mut state); ``` -------------------------------- ### Padding Constructor Examples Source: https://docs.rs/ratatui/0.30.2/ratatui/widgets/struct.Padding.html Demonstrates various ways to create Padding instances using static methods. ```rust use ratatui::widgets::Padding; Padding::uniform(1); Padding::horizontal(2); Padding::left(3); Padding::proportional(4); Padding::symmetric(5, 6); ``` -------------------------------- ### Manual Terminal Initialization and Restoration with `try_init` and `try_restore` Source: https://docs.rs/ratatui/0.30.2/ratatui/init/index.html Demonstrates manual terminal setup and teardown using `try_init()` which returns a Result for custom error handling, and `try_restore()` for error-aware cleanup. ```rust // Using try_init() - returns Result for custom error handling let mut terminal = ratatui::try_init()?; // ... app logic ... ratatui::try_restore()?; ``` -------------------------------- ### Get Terminal Size with Ratatui Backend Source: https://docs.rs/ratatui/0.30.2/ratatui/backend/trait.Backend.html?search=u32+-%3E+bool Demonstrates how to retrieve the dimensions (width and height in columns and rows) of the terminal screen using the `size` method. The example asserts the size to be 80 columns by 25 rows. ```rust use ratatui::{backend::Backend, layout::Size}; assert_eq!(backend.size()?, Size::new(80, 25)); ``` -------------------------------- ### Padding Constructor Examples Source: https://docs.rs/ratatui/0.30.2/ratatui/widgets/struct.Padding.html?search= Demonstrates various ways to create Padding instances using static methods. Use these to configure padding for widgets. ```rust use ratatui::widgets::Padding; Padding::uniform(1); ``` ```rust use ratatui::widgets::Padding; Padding::horizontal(2); ``` ```rust use ratatui::widgets::Padding; Padding::left(3); ``` ```rust use ratatui::widgets::Padding; Padding::proportional(4); ``` ```rust use ratatui::widgets::Padding; Padding::symmetric(5, 6); ``` -------------------------------- ### Example: Execute Print Command Source: https://docs.rs/ratatui/0.30.2/ratatui/backend/struct.TerminaBackend.html?search=u32+-%3E+bool Demonstrates executing a `Print` command to display text on the terminal. ```rust use std::io; use crossterm::{ExecutableCommand, style::Print}; ``` -------------------------------- ### TerminaBackend Initialization Example Source: https://docs.rs/ratatui/0.30.2/ratatui/backend/struct.TerminaBackend.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to create and use a TerminaBackend with a termina::Terminal. Ensure raw mode is enabled and the terminal is initialized before drawing. ```rust use ratatui::Terminal; use ratatui::backend::TerminaBackend; use ratatui::termina::{PlatformTerminal, Terminal as _}; let mut output = PlatformTerminal::new()?; output.enter_raw_mode()?; let backend = TerminaBackend::new(output); let mut terminal = Terminal::new(backend)?; terminal.draw(|frame| { // -- snip -- })?; ``` -------------------------------- ### init_with_options Source: https://docs.rs/ratatui/0.30.2/index.html Initializes the terminal with specified options and default settings using the crossterm backend. ```APIDOC ## init_with_options ### Description Initializes a terminal with the given options and reasonable defaults. ### Method N/A (Function Call) ### Parameters - **options**: (type) - Description of options not provided in source. ### Request Example N/A ### Response N/A ``` -------------------------------- ### Flex Start: Max Constraints Source: https://docs.rs/ratatui/0.30.2/ratatui/prelude/layout/enum.Flex.html?search=std%3A%3Avec Shows the 'Start' alignment when using only Max constraints. ```text <------------------------------------80 px-------------------------------------> ┌──────20 px───────┐┌──────20 px───────┐ │ Max(20) ││ Max(20) │ └──────────────────┘└──────────────────┘ ``` -------------------------------- ### List Widget Creation and Configuration Source: https://docs.rs/ratatui/0.30.2/ratatui/widgets/struct.List.html?search=u32+-%3E+bool Demonstrates how to create a List widget, set its items, wrap it in a Block, and apply various styles and highlight symbols. ```APIDOC ## List Widget API This section details the available methods for creating and configuring the `List` widget. ### `List::new(items: T) -> List<'a>` Creates a new list from `ListItem`s. - **items** (T): Accepts any value that can be converted into an iterator of `Into`. ### `List::items(self, items: T) -> List<'a>` Sets the items for the list. - **items** (T): Accepts any value that can be converted into an iterator of `Into`. ### `List::block(self, block: Block<'a>) -> List<'a>` Wraps the list with a custom `Block` widget. - **block** (Block<'a>): The `Block` to be created around the `List`. ### `List::style(self, style: S) -> List<'a>` Sets the base style of the widget. - **style** (S): Any type convertible to `Style`. ### `List::highlight_symbol(self, highlight_symbol: L) -> List<'a>` Sets the symbol to be displayed in front of the selected item. - **highlight_symbol** (L): Any type convertible to `Line`. ### `List::highlight_style(self, style: S) -> List<'a>` Sets the style of the selected item. - **style** (S): Any type convertible to `Style`. ### `List::repeat_highlight_symbol(self, repeat: bool) -> List<'a>` Sets whether to repeat the highlight symbol and style over selected multi-line items. - **repeat** (bool): Whether to repeat the highlight symbol. ``` -------------------------------- ### MergeStrategy Enum Examples Source: https://docs.rs/ratatui/0.30.2/ratatui/prelude/symbols/merge/enum.MergeStrategy.html?search=std%3A%3Avec Demonstrates the basic usage of different MergeStrategy variants with example symbols. ```rust assert_eq!(MergeStrategy::Replace.merge("│", "━"), "━"); assert_eq!(MergeStrategy::Exact.merge("│", "─"), "┼"); assert_eq!(MergeStrategy::Fuzzy.merge("┘", "╔"), "╬"); ``` -------------------------------- ### Inline UI Initialization with Custom Options (Result on Failure) Source: https://docs.rs/ratatui/0.30.2/ratatui/init/index.html?search=u32+-%3E+bool Demonstrates initializing a terminal for an inline UI with custom options using `try_init_with_options`, returning a `Result` for error handling. This allows for custom error management during setup and teardown. ```rust // Using try_init_with_options() - returns Result for custom error handling let options = TerminalOptions { viewport: Viewport::Inline(10), }; let mut terminal = ratatui::try_init_with_options(options)?; terminal.draw(|frame| { frame.render_widget("Inline UI", frame.area()); })?; ratatui::try_restore()?; ``` -------------------------------- ### Max Constraint Example 2 Source: https://docs.rs/ratatui/0.30.2/ratatui/prelude/layout/enum.Constraint.html?search= Presents a Max constraint example with a maximum size of 10px. ```rust [Percentage(0), Max(10)] ``` -------------------------------- ### Basic Terminal Initialization and Restoration Source: https://docs.rs/ratatui/0.30.2/src/ratatui/init.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Use `ratatui::init()` for standard full-screen applications where panics are acceptable. `ratatui::restore()` is used for cleanup. ```rust // Using init() - panics on failure let mut terminal = ratatui::init(); // ... app logic ... ratatui::restore(); // Using try_init() - returns Result for custom error handling let mut terminal = ratatui::try_init()?; // ... app logic ... ratatui::try_restore()?; # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### Flex Legacy - Example 2 Source: https://docs.rs/ratatui/0.30.2/ratatui/layout/enum.Flex.html?search=u32+-%3E+bool An example showing 'Legacy' Flex behavior with only a Max constraint. ```text <------------------------------------80 px-------------------------------------> ┌────────────────────────────────────80 px─────────────────────────────────────┐ │ Max(20) │ └──────────────────────────────────────────────────────────────────────────────┘ ``` -------------------------------- ### Get Type ID Source: https://docs.rs/ratatui/0.30.2/ratatui/backend/struct.CrosstermBackend.html Gets the `TypeId` of a given type. This is useful for runtime type identification. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Simple "Hello World" TUI Application Source: https://docs.rs/ratatui/0.30.2/index.html Create a basic "Hello World" terminal application using Ratatui and Crossterm. This example demonstrates the core `run` function for initializing the terminal, drawing content, and handling basic input. ```rust use crossterm::event; fn main() -> std::io::Result<()> { ratatui::run(|mut terminal| { loop { terminal.draw(|frame| frame.render_widget("Hello World!", frame.area()))?; if event::read()?.is_key_press() { break Ok(()) } } }) } ``` -------------------------------- ### Flex Legacy: Max Constraint Example Source: https://docs.rs/ratatui/0.30.2/ratatui/prelude/layout/enum.Flex.html?search=std%3A%3Avec An example demonstrating the allocation of space when only a Max constraint is used. ```text <------------------------------------80 px-------------------------------------> ┌────────────────────────────────────80 px─────────────────────────────────────┐ │ Max(20) │ └──────────────────────────────────────────────────────────────────────────────┘ ``` -------------------------------- ### Min Constraint Example 2 Source: https://docs.rs/ratatui/0.30.2/ratatui/prelude/layout/enum.Constraint.html?search= Shows another Min constraint example where the minimum size is 10px. ```rust [Percentage(100), Min(10)] ``` -------------------------------- ### Creating a Style Source: https://docs.rs/ratatui/0.30.2/ratatui/prelude/struct.Style.html?search=u32+-%3E+bool Demonstrates how to create and apply a Style using its default constructor and methods to set foreground, background, and modifiers. ```APIDOC ## Creating a Style ### Description Styles can be created using `Style::default()` and then chaining methods to set properties like foreground color, background color, and modifiers. ### Usage ```rust use ratatui_core::style::{Color, Modifier, Style}; let my_style = Style::default() .fg(Color::Black) .bg(Color::Green) .add_modifier(Modifier::ITALIC | Modifier::BOLD); ``` ``` -------------------------------- ### Basic List Widget Configuration Source: https://docs.rs/ratatui/0.30.2/ratatui/widgets/struct.List.html Demonstrates how to create and configure a List widget with basic styling, highlighting, and direction. This snippet requires importing necessary components from ratatui. ```rust use ratatui::Frame; use ratatui::layout::Rect; use ratatui::style::{Style, Stylize}; use ratatui::widgets::{Block, List, ListDirection, ListItem}; let items = ["Item 1", "Item 2", "Item 3"]; let list = List::new(items) .block(Block::bordered().title("List")) .style(Style::new().white()) .highlight_style(Style::new().italic()) .highlight_symbol(">>") .repeat_highlight_symbol(true) .direction(ListDirection::BottomToTop); frame.render_widget(list, area); ``` -------------------------------- ### Size Struct Examples Source: https://docs.rs/ratatui/0.30.2/ratatui/layout/struct.Size.html?search=u32+-%3E+bool Demonstrates creating and using the Size struct, including area calculation and conversion from tuples and Rect. ```rust use ratatui_core::layout::{Rect, Size}; let size = Size::new(80, 24); assert_eq!(size.area(), 1920); let size = Size::from((80, 24)); let size = Size::from(Rect::new(0, 0, 80, 24)); assert_eq!(size.area(), 1920); ``` -------------------------------- ### ratatui::init_with_options Source: https://docs.rs/ratatui/0.30.2/src/ratatui/init.rs.html Initializes a terminal with specified options and reasonable defaults, panicking on failure. It does not automatically enter the alternate screen buffer. ```APIDOC ## ratatui::init_with_options ### Description Initializes a terminal with the given `TerminalOptions` and reasonable defaults. This function is similar to `init` but allows customization of `Viewport` and does not automatically enter the alternate screen buffer. It enables raw mode and installs a panic hook. It panics if initialization fails. ### Arguments * `options` (`TerminalOptions`): The options to configure the terminal, including the `Viewport`. ### Returns A `DefaultTerminal` instance. ### Panics Panics if raw mode cannot be enabled or if the terminal fails to initialize due to issues like calculating terminal size. ### Examples ```rust,no_run use ratatui::{TerminalOptions, Viewport}; let options = TerminalOptions { viewport: Viewport::Inline(5), }; let terminal = ratatui::init_with_options(options); ``` ``` -------------------------------- ### WidgetRef Example Usage Source: https://docs.rs/ratatui/0.30.2/src/ratatui/widgets/widget_ref.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Example demonstrating how to use the `WidgetRef` trait with custom widgets and collections of boxed widgets. ```APIDOC ## WidgetRef Example ### Description This example shows how to implement and use the `WidgetRef` trait for custom widgets. It also demonstrates rendering widgets by reference and storing them in a collection of boxed widgets. ### Code Example ```rust use ratatui::widgets::WidgetRef; use ratatui_core::buffer::Buffer; use ratatui_core::layout::Rect; use ratatui_core::text::Line; use ratatui_core::widgets::Widget; struct Greeting; struct Farewell; impl WidgetRef for Greeting { fn render_ref(&self, area: Rect, buf: &mut Buffer) { Line::raw("Hello").render(area, buf); } } // Only needed for backwards compatibility impl Widget for Greeting { fn render(self, area: Rect, buf: &mut Buffer) { self.render_ref(area, buf); } } impl WidgetRef for Farewell { fn render_ref(&self, area: Rect, buf: &mut Buffer) { Line::raw("Goodbye").right_aligned().render(area, buf); } } // Only needed for backwards compatibility impl Widget for Farewell { fn render(self, area: Rect, buf: &mut Buffer) { self.render_ref(area, buf); } } fn render(area: Rect, buf: &mut Buffer) { let greeting = Greeting; let farewell = Farewell; // These calls do not consume the widgets, so they can be used again later greeting.render_ref(area, buf); farewell.render_ref(area, buf); // A collection of widgets with different types let widgets: Vec> = vec![Box::new(greeting), Box::new(farewell)]; for widget in widgets { widget.render_ref(area, buf); } } ``` ``` -------------------------------- ### init and restore Source: https://docs.rs/ratatui/0.30.2/ratatui/init/index.html?search=u32+-%3E+bool Provides manual control over terminal setup and teardown. `init` panics on failure, while `try_init` returns a `Result`. `restore` prints errors to stderr, and `try_restore` returns a `Result`. ```APIDOC ## init / try_init / restore / try_restore ### Description These functions allow for manual control over terminal initialization and restoration. `init` and `restore` are simpler to use but may panic or print errors to stderr. `try_init` and `try_restore` provide `Result` types for more robust error handling. ### `init()` and `restore()` #### `init()` Creates a terminal with reasonable defaults including alternate screen and raw mode. Panics on failure. ```rust let mut terminal = ratatui::init(); // ... app logic ... ratatui::restore(); ``` ### `try_init()` and `try_restore()` #### `try_init()` Same as `init` but returns a `Result` instead of panicking. ```rust let mut terminal = ratatui::try_init()?; // ... app logic ... ratatui::try_restore()?; ``` #### `restore()` Restores the terminal to its original state. Prints errors to stderr but does not panic. #### `try_restore()` Same as `restore` but returns a `Result` instead of printing errors. ``` -------------------------------- ### Create and Configure a Dataset Source: https://docs.rs/ratatui/0.30.2/ratatui/widgets/struct.Dataset.html?search=std%3A%3Avec Demonstrates how to create a Dataset, set its name, data points, marker, graph type, and apply a color style. This is useful for defining a single data series within a chart. ```rust use ratatui::style::Stylize; use ratatui::symbols::Marker; use ratatui::widgets::{Dataset, GraphType}; let dataset = Dataset::default() .name("dataset 1") .data(&[(1., 1.), (5., 5.)]) .marker(Marker::Braille) .graph_type(GraphType::Line) .red(); ``` -------------------------------- ### HEAVY_QUADRUPLE_DASHED Border Example Source: https://docs.rs/ratatui/0.30.2/ratatui/prelude/symbols/border/constant.HEAVY_QUADRUPLE_DASHED.html?search= An example visualization of the border style provided by the HEAVY_QUADRUPLE_DASHED constant. This set uses thick quadruple-dashed lines. ```text ┏┉┉┉┉┉┓ ┋xxxxx┋ ┋xxxxx┋ ┗┉┉┉┉┉┛ ``` -------------------------------- ### Min Constraint Example Source: https://docs.rs/ratatui/0.30.2/ratatui/prelude/enum.Constraint.html The Min variant ensures an element is at least a specified size. This example shows how it interacts with a Percentage constraint. ```rust let constraints = [Constraint::Percentage(100), Constraint::Min(20)]; ``` -------------------------------- ### Table Creation and Configuration Source: https://docs.rs/ratatui/0.30.2/ratatui/widgets/struct.Table.html Demonstrates how to create a Table widget, set its rows, column widths, spacing, and apply various styling options including headers, footers, and highlight styles. ```APIDOC ## Table::new ### Description Creates a new `Table` with the given rows and column widths. ### Method `Table::new(rows: impl IntoIterator, widths: impl IntoIterator) ### Parameters * `rows`: An iterator of `Row` objects to display in the table. * `widths`: An iterator of `Constraint` objects defining the width of each column. ## Table::default ### Description Creates an empty `Table` with default settings. Rows can be added later using `Table::rows`. ### Method `Table::default() ## Table::rows ### Description Sets the rows of the `Table`. ### Method `Table::rows(rows: impl IntoIterator) ### Parameters * `rows`: An iterator of `Row` objects to display in the table. ## Table::header ### Description Sets the header row of the `Table`, which is always visible at the top. ### Method `Table::header(header: Row) ### Parameters * `header`: A `Row` object to be used as the table header. ## Table::footer ### Description Sets the footer row of the `Table`, which is always visible at the bottom. ### Method `Table::footer(footer: Row) ### Parameters * `footer`: A `Row` object to be used as the table footer. ## Table::widths ### Description Sets the width constraints for each column in the `Table`. ### Method `Table::widths(widths: impl IntoIterator) ### Parameters * `widths`: An iterator of `Constraint` objects defining the width of each column. ## Table::column_spacing ### Description Sets the spacing between each column in the `Table`. ### Method `Table::column_spacing(spacing: u16) ### Parameters * `spacing`: The amount of space between columns. ## Table::block ### Description Wraps the `Table` widget in a `Block` widget, allowing for borders, titles, etc. ### Method `Table::block(block: Block) ### Parameters * `block`: A `Block` widget to wrap the table. ## Table::style ### Description Sets the base style for the `Table` widget. ### Method `Table::style(style: Style) ### Parameters * `style`: The `Style` to apply to the table. ## Table::row_highlight_style ### Description Sets the style for the currently highlighted row. ### Method `Table::row_highlight_style(style: Style) ### Parameters * `style`: The `Style` to apply to the highlighted row. ## Table::column_highlight_style ### Description Sets the style for the currently highlighted column. ### Method `Table::column_highlight_style(style: Style) ### Parameters * `style`: The `Style` to apply to the highlighted column. ## Table::cell_highlight_style ### Description Sets the style for the currently highlighted cell. ### Method `Table::cell_highlight_style(style: Style) ### Parameters * `style`: The `Style` to apply to the highlighted cell. ## Table::highlight_symbol ### Description Sets the symbol to be displayed in front of the selected row. ### Method `Table::highlight_symbol(symbol: &str) ### Parameters * `symbol`: The string symbol to display for highlighting. ## Table::highlight_spacing ### Description Sets when to show the highlight spacing. ### Method `Table::highlight_spacing(spacing: u16) ### Parameters * `spacing`: The spacing value for highlighting. ``` -------------------------------- ### Stateful Widget Example with List Source: https://docs.rs/ratatui/0.30.2/ratatui/prelude/trait.StatefulWidget.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to create and use a custom stateful widget that manages a list of items. It shows how to initialize the state, update it (e.g., select next/previous item), and render the widget using `Frame::render_stateful_widget`. ```rust use std::io; use ratatui::{ backend::TestBackend, widgets::{List, ListItem, ListState, StatefulWidget, Widget}, Terminal, }; // Let's say we have some events to display. struct Events { // `items` is the state managed by your application. items: Vec, // `state` is the state that can be modified by the UI. It stores the index of the selected // item as well as the offset computed during the previous draw call (used to implement // natural scrolling). state: ListState, } impl Events { fn new(items: Vec) -> Events { Events { items, state: ListState::default(), } } pub fn set_items(&mut self, items: Vec) { self.items = items; // We reset the state as the associated items have changed. This effectively reset // the selection as well as the stored offset. self.state = ListState::default(); } // Select the next item. This will not be reflected until the widget is drawn in the // `Terminal::draw` callback using `Frame::render_stateful_widget`. pub fn next(&mut self) { let i = match self.state.selected() { Some(i) => { if i >= self.items.len() - 1 { 0 } else { i + 1 } } None => 0, }; self.state.select(Some(i)); } // Select the previous item. This will not be reflected until the widget is drawn in the // `Terminal::draw` callback using `Frame::render_stateful_widget`. pub fn previous(&mut self) { let i = match self.state.selected() { Some(i) => { if i == 0 { self.items.len() - 1 } else { i - 1 } } None => 0, }; self.state.select(Some(i)); } // Unselect the currently selected item if any. The implementation of `ListState` makes // sure that the stored offset is also reset. pub fn unselect(&mut self) { self.state.select(None); } } let mut events = Events::new(vec![String::from("Item 1"), String::from("Item 2")]); loop { terminal.draw(|f| { // The items managed by the application are transformed to something // that is understood by ratatui. let items: Vec = events .items .iter() .map(|i| ListItem::new(i.as_str())) .collect(); // The `List` widget is then built with those items. let list = List::new(items); // Finally the widget is rendered using the associated state. `events.state` is // effectively the only thing that we will "remember" from this draw call. f.render_stateful_widget(list, f.size(), &mut events.state); }); // In response to some input events or an external http request or whatever: events.next(); } ``` -------------------------------- ### Max Constraint Example Source: https://docs.rs/ratatui/0.30.2/ratatui/prelude/enum.Constraint.html The Max variant limits an element to a maximum size. This example shows it applied to a layout where other elements might take up more space. ```rust let constraints = [Constraint::Percentage(0), Constraint::Max(20)]; ``` -------------------------------- ### Creating a New TermwizBackend Instance Source: https://docs.rs/ratatui/0.30.2/ratatui/backend/struct.TermwizBackend.html?search= Shows the basic instantiation of a TermwizBackend. This method automatically enables raw mode and enters the alternate screen. ```rust use ratatui::backend::TermwizBackend; let backend = TermwizBackend::new()?; ``` -------------------------------- ### Typical Terminal Usage with ratatui::run Source: https://docs.rs/ratatui/0.30.2/ratatui/prelude/struct.Terminal.html Demonstrates the typical usage pattern for a fullscreen application using `ratatui::run`. This helper function initializes the terminal, runs a callback with a `Terminal` instance, and handles setup and restoration of terminal modes. ```rust ratatui::run(|terminal| { let mut should_quit = false; while !should_quit { terminal.draw(|frame| { frame.render_widget("Hello, World!", frame.area()); })?; // Handle events, update application state, and set `should_quit = true` to exit. } Ok(()) })?; ``` -------------------------------- ### No_std Compatible Widget Example Source: https://docs.rs/ratatui/0.30.2/ratatui/widgets/index.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E An example of a basic widget implemented with `no_std` compatibility. It demonstrates the necessary imports and attributes for use in environments without the standard library. ```rust #![no_std] extern crate alloc; use alloc::string::String; use ratatui_core::buffer::Buffer; use ratatui_core::layout::Rect; use ratatui_core::text::Line; use ratatui_core::widgets::Widget; struct MyWidget { content: String, } ``` -------------------------------- ### Canvas Marker Examples Source: https://docs.rs/ratatui/0.30.2/ratatui/widgets/canvas/struct.Canvas.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Shows how to set different marker types for drawing points on the Canvas. Each example uses a different marker from the `ratatui::symbols::Marker` enum. ```rust use ratatui::symbols; use ratatui::widgets::canvas::Canvas; Canvas::default() .marker(symbols::Marker::Braille) .paint(|ctx| {}); ``` ```rust use ratatui::symbols; use ratatui::widgets::canvas::Canvas; Canvas::default() .marker(symbols::Marker::HalfBlock) .paint(|ctx| {}); ``` ```rust use ratatui::symbols; use ratatui::widgets::canvas::Canvas; Canvas::default() .marker(symbols::Marker::Dot) .paint(|ctx| {}); ``` ```rust use ratatui::symbols; use ratatui::widgets::canvas::Canvas; Canvas::default() .marker(symbols::Marker::Block) .paint(|ctx| {}); ``` -------------------------------- ### Position Examples Source: https://docs.rs/ratatui/0.30.2/ratatui/layout/struct.Position.html Illustrates various ways to create and manipulate Position instances. ```APIDOC ## §Examples ```rust use ratatui_core::layout::{Offset, Position, Rect}; // the following are all equivalent let position = Position { x: 1, y: 2 }; let position = Position::new(1, 2); let position = Position::from((1, 2)); let position = Position::from(Rect::new(1, 2, 3, 4)); // position can be converted back into the components when needed let (x, y) = position.into(); // movement by offsets let position = Position::new(5, 5) + Offset::new(2, -3); assert_eq!(position, Position::new(7, 2)); ``` ``` -------------------------------- ### Example Search: std::vec Source: https://docs.rs/ratatui/0.30.2/ratatui/style/palette/tailwind/constant.FUCHSIA.html?search= Demonstrates an example search query for 'std::vec'. This is a common pattern for searching within Rust's standard library documentation. ```text std::vec ``` -------------------------------- ### Create a Block with All Borders Shown Source: https://docs.rs/ratatui/0.30.2/ratatui/widgets/struct.Block.html This example asserts that calling `Block::bordered()` is equivalent to creating a new block and explicitly setting all borders. ```rust use ratatui::widgets::{Block, Borders}; assert_eq!(Block::bordered(), Block::new().borders(Borders::ALL)); ``` -------------------------------- ### Ratio Constraint Example (Two Elements) Source: https://docs.rs/ratatui/0.30.2/ratatui/prelude/enum.Constraint.html The Ratio variant divides space based on a given ratio. This example splits the available space equally between two elements. ```rust let constraints = [Constraint::Ratio(1, 2); 2]; ``` -------------------------------- ### Basic Terminal Initialization and Restoration Source: https://docs.rs/ratatui/0.30.2/src/ratatui/init.rs.html Use `init()` for standard full-screen applications where panics are acceptable. `restore()` is called afterwards for cleanup. ```rust let mut terminal = ratatui::init(); // ... app logic ... ratatui::restore(); ``` -------------------------------- ### Buffer Cell Access (Safe) Source: https://docs.rs/ratatui/0.30.2/ratatui/prelude/struct.Buffer.html Provides safe methods to get and get mutable references to cells within the buffer using a position, returning None if the position is out of bounds. ```APIDOC ## Buffer::cell ### Description Returns a reference to the `Cell` at the given position or `None` if the position is outside the `Buffer`’s area. This method accepts any value that can be converted to `Position` (e.g. `(x, y)` or `Position::new(x, y)`). For a method that panics when the position is outside the buffer instead of returning `None`, use `Buffer[]`. ### Signature `pub fn cell

(&self, position: P) -> Option<&Cell> where P: Into` ### Examples ``` use ratatui_core::buffer::{Buffer, Cell}; use ratatui_core::layout::{Position, Rect}; let mut buffer = Buffer::empty(Rect::new(0, 0, 10, 10)); assert_eq!(buffer.cell(Position::new(0, 0)), Some(&Cell::default())); assert_eq!(buffer.cell(Position::new(10, 10)), None); assert_eq!(buffer.cell((0, 0)), Some(&Cell::default())); assert_eq!(buffer.cell((10, 10)), None); ``` ## Buffer::cell_mut ### Description Returns a mutable reference to the `Cell` at the given position or `None` if the position is outside the `Buffer`’s area. This method accepts any value that can be converted to `Position` (e.g. `(x, y)` or `Position::new(x, y)`). For a method that panics when the position is outside the buffer instead of returning `None`, use `Buffer[]`. ### Signature `pub fn cell_mut

(&mut self, position: P) -> Option<&mut Cell> where P: Into` ### Examples ``` use ratatui_core::buffer::{Buffer, Cell}; use ratatui_core::layout::{Position, Rect}; use ratatui_core::style::{Color, Style}; let mut buffer = Buffer::empty(Rect::new(0, 0, 10, 10)); if let Some(cell) = buffer.cell_mut(Position::new(0, 0)) { cell.set_symbol("A"); } if let Some(cell) = buffer.cell_mut((0, 0)) { cell.set_style(Style::default().fg(Color::Red)); } ``` ``` -------------------------------- ### Any Source: https://docs.rs/ratatui/0.30.2/ratatui/prelude/layout/struct.Margin.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Gets the `TypeId` of the object. ```APIDOC ## type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. ### Method type_id ### Returns TypeId: The type identifier of the object. ``` -------------------------------- ### Inline Terminal Initialization with Options Source: https://docs.rs/ratatui/0.30.2/src/ratatui/init.rs.html?search=std%3A%3Avec Use `init_with_options` for UIs that do not use the normal fullscreen path, such as inline UIs. `restore()` is used for cleanup. ```rust use crossterm::event::{self, Event, KeyCode, KeyEventKind}; use ratatui::widgets::Widget; use ratatui::{TerminalOptions, Viewport}; let options = TerminalOptions { viewport: Viewport::Inline(10), }; let mut terminal = ratatui::init_with_options(options); terminal.insert_before(1, |buf| { "> Ready".render(buf.area, buf); })?; loop { terminal.draw(|frame| { frame.render_widget("Inline UI lives below earlier terminal output", frame.area()); })?; if matches!( event::read()?, Event::Key(key) if key.kind == KeyEventKind::Press && key.code == KeyCode::Char('q') ) { break; } } ratatui::restore(); ``` ```rust let options = TerminalOptions { viewport: Viewport::Inline(10), }; let mut terminal = ratatui::try_init_with_options(options)?; terminal.draw(|frame| { frame.render_widget("Inline UI", frame.area()); })?; ratatui::try_restore()?; # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### Example Search: Option, (T -> U) -> Option Source: https://docs.rs/ratatui/0.30.2/ratatui/style/palette/tailwind/constant.FUCHSIA.html?search= Shows an example search query for a functional transformation involving Option types. This pattern is used to find operations that map a function over an Option. ```text Option, (T -> U) -> Option ``` -------------------------------- ### TestBackend::new Source: https://docs.rs/ratatui/0.30.2/ratatui/backend/struct.TestBackend.html?search= Creates a new TestBackend with the specified width and height. This is useful for setting up a testing environment with a defined screen size. ```APIDOC ## TestBackend::new ### Description Creates a new `TestBackend` with the specified width and height. ### Method `TestBackend::new(width: u16, height: u16) -> TestBackend` ### Parameters * **width** (u16) - The width of the backend buffer. * **height** (u16) - The height of the backend buffer. ### Returns A new `TestBackend` instance. ### Example ```rust use ratatui::backend::TestBackend; let mut backend = TestBackend::new(10, 2); ``` ``` -------------------------------- ### Fill Constraint Example (Multiple Fills) Source: https://docs.rs/ratatui/0.30.2/ratatui/prelude/enum.Constraint.html The Fill variant distributes excess space proportionally among elements marked with Fill. This example shows three Fill elements with different weights. ```rust let constraints = [Constraint::Fill(1), Constraint::Fill(2), Constraint::Fill(3)]; ```