### Automatic Terminal Setup Source: https://docs.rs/ratatui/0.30.0/ratatui/init/index.html?search= Use the run function for the simplest setup, which handles automatic terminal initialization and cleanup. ```rust fn main() -> std::io::Result<()> { ratatui::run(|terminal| { loop { terminal.draw(|frame| frame.render_widget("Hello, world!", frame.area()))?; if crossterm::event::read()?.is_key_press() { break Ok(()); } } }) } ``` -------------------------------- ### Start Flex Alignment Examples Source: https://docs.rs/ratatui/0.30.0/ratatui/layout/enum.Flex.html Visual representations of items aligned to the start of the container using the Start variant. ```text <------------------------------------80 px-------------------------------------> ┌────16 px─────┐┌──────20 px───────┐┌──────20 px───────┐ │Percentage(20)││ Length(20) ││ Fixed(20) │ └──────────────┘└──────────────────┘└──────────────────┘ <------------------------------------80 px-------------------------------------> ┌──────20 px───────┐┌──────20 px───────┐ │ Max(20) ││ Max(20) │ └──────────────────┘└──────────────────┘ <------------------------------------80 px-------------------------------------> ┌──────20 px───────┐ │ Max(20) │ └──────────────────┘ ``` -------------------------------- ### Basic Usage Source: https://docs.rs/ratatui/0.30.0/ratatui/fn.try_init.html?search= Example of initializing the terminal using try_init. ```rust let terminal = ratatui::try_init()?; ``` -------------------------------- ### Search example for Option mapping Source: https://docs.rs/ratatui/0.30.0/ratatui/style/palette/tailwind/constant.YELLOW.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Example search query demonstrating functional mapping syntax. ```rust Option, (T -> U) -> Option ``` -------------------------------- ### Initialize Padding Examples Source: https://docs.rs/ratatui/0.30.0/ratatui/widgets/struct.Padding.html Demonstrates various ways to initialize Padding using its static methods. ```rust use ratatui::widgets::Padding; Padding::uniform(1); Padding::horizontal(2); Padding::left(3); Padding::proportional(4); Padding::symmetric(5, 6); ``` -------------------------------- ### Legacy constraint examples Source: https://docs.rs/ratatui/0.30.0/ratatui/prelude/layout/enum.Flex.html?search=u32+-%3E+bool Examples showing how constraints interact under the Legacy flex strategy. ```text <------------------------------------80 px-------------------------------------> ┌──────────────────────────60 px───────────────────────────┐┌──────20 px───────┐ │ Min(20) ││ Max(20) │ └──────────────────────────────────────────────────────────┘└──────────────────┘ <------------------------------------80 px-------------------------------------> ┌────────────────────────────────────80 px─────────────────────────────────────┐ │ Max(20) │ └──────────────────────────────────────────────────────────────────────────────┘ ``` -------------------------------- ### Buffer Diffing Multi-width Character Examples Source: https://docs.rs/ratatui/0.30.0/ratatui/buffer/struct.Buffer.html?search=std%3A%3Avec Examples illustrating how the diffing algorithm handles multi-width characters during buffer updates. ```text (Index:) `01` Prev: `コ` Next: `aa` Updates: `0: a, 1: a' ``` ```text (Index:) `01` Prev: `a ` Next: `コ` Updates: `0: コ` (double width symbol at index 0 - skip index 1) ``` ```text (Index:) `012` Prev: `aaa` Next: `aコ` Updates: `0: a, 1: コ` (double width symbol at index 1 - skip index 2) ``` -------------------------------- ### List Widget Usage Source: https://docs.rs/ratatui/0.30.0/ratatui/widgets/struct.List.html?search=u32+-%3E+bool Example demonstrating how to instantiate and configure a List widget with various fluent setters. ```APIDOC ## List Widget ### Description A widget to display several items among which one can be selected. It supports automatic height determination and can be rendered in reverse order. ### Fluent Setters - **highlight_style**: Sets the style of the selected item. - **highlight_symbol**: Sets the symbol to be displayed in front of the selected item. - **repeat_highlight_symbol**: Sets whether to repeat the symbol and style over selected multi-line items. - **direction**: Sets the list direction (e.g., TopToBottom, BottomToTop). ### Example ```rust 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")) .highlight_style(Style::new().italic()) .highlight_symbol(">>") .repeat_highlight_symbol(true) .direction(ListDirection::BottomToTop); ``` ``` -------------------------------- ### Initialize terminal with convenience functions Source: https://docs.rs/ratatui/0.30.0/ratatui/prelude/struct.Terminal.html Use the recommended high-level API to handle setup and teardown automatically. ```rust // Modern approach using convenience functions ratatui::run(|terminal| { terminal.draw(|frame| { let area = frame.area(); frame.render_widget(Paragraph::new("Hello World!"), area); })?; Ok(()) })?; ``` -------------------------------- ### Create a simple BarChart Source: https://docs.rs/ratatui/0.30.0/ratatui/widgets/struct.BarChart.html Shows the minimal setup required to initialize a BarChart with a collection of Bar instances. ```rust use ratatui::widgets::{Bar, BarChart}; BarChart::new([Bar::with_label("A", 10), Bar::with_label("B", 20)]); ``` -------------------------------- ### Initialize a Terminal with CrosstermBackend Source: https://docs.rs/ratatui/0.30.0/ratatui/prelude/backend/index.html Demonstrates the standard setup for a terminal using the Crossterm backend. ```rust use std::io::stdout; use ratatui::{backend::CrosstermBackend, Terminal}; let backend = CrosstermBackend::new(stdout()); let mut terminal = Terminal::new(backend)?; terminal.clear()?; terminal.draw(|frame| { // -- snip -- })?; ``` -------------------------------- ### Implement and use a stateful List widget Source: https://docs.rs/ratatui/0.30.0/ratatui/prelude/trait.StatefulWidget.html?search=std%3A%3Avec Example demonstrating how to manage application state with ListState and render it using 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); }); } ``` -------------------------------- ### Define and implement StatefulWidgetRef Source: https://docs.rs/ratatui/0.30.0/ratatui/widgets/trait.StatefulWidgetRef.html Example showing the definition of a custom widget implementing StatefulWidgetRef and the corresponding StatefulWidget implementation. ```rust use ratatui::widgets::StatefulWidgetRef; use ratatui_core::buffer::Buffer; use ratatui_core::layout::Rect; use ratatui_core::style::Stylize; use ratatui_core::text::Line; use ratatui_core::widgets::{StatefulWidget, Widget}; struct PersonalGreeting; impl StatefulWidgetRef for PersonalGreeting { type State = String; fn render_ref(&self, area: Rect, buf: &mut Buffer, state: &mut Self::State) { Line::raw(format!("Hello {}", state)).render(area, buf); } } impl StatefulWidget for PersonalGreeting { type State = String; fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) { (&self).render_ref(area, buf, state); } } fn render(area: Rect, buf: &mut Buffer) { let widget = PersonalGreeting; let mut state = "world".to_string(); widget.render(area, buf, &mut state); } ``` -------------------------------- ### MergeStrategy Usage Examples Source: https://docs.rs/ratatui/0.30.0/ratatui/prelude/symbols/merge/enum.MergeStrategy.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates basic usage of different merge strategies to combine symbols. ```rust assert_eq!(MergeStrategy::Replace.merge("│", "━"), "━"); assert_eq!(MergeStrategy::Exact.merge("│", "─"), "┼"); assert_eq!(MergeStrategy::Fuzzy.merge("┘", "╔"), "╬"); ``` -------------------------------- ### Construct and use Size Source: https://docs.rs/ratatui/0.30.0/ratatui/layout/struct.Size.html?search= Examples of creating Size instances from various sources and calculating the total area. ```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); ``` -------------------------------- ### Run Ratatui logo example Source: https://docs.rs/ratatui/0.30.0/ratatui/widgets/struct.RatatuiLogo.html?search= Command to run the Ratatui logo example from the repository. ```bash cargo run --example logo [size] ``` -------------------------------- ### Initialize a Terminal with TermionBackend Source: https://docs.rs/ratatui/0.30.0/ratatui/backend/struct.TermionBackend.html Demonstrates setting up a terminal using stdout or stderr with raw mode and alternate screen enabled. ```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 -- })?; ``` -------------------------------- ### Create a Hello World TUI application Source: https://docs.rs/ratatui/0.30.0/index.html A minimal example demonstrating how to initialize a terminal and render a widget using the Ratatui run loop. ```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(()); } } }) } ``` -------------------------------- ### Buffer Usage Examples Source: https://docs.rs/ratatui/0.30.0/ratatui/buffer/struct.Buffer.html?search=std%3A%3Avec Demonstrates how to initialize a buffer, index cells using positions or tuples, and set string content with styles. ```rust use ratatui_core::buffer::{Buffer, Cell}; use ratatui_core::layout::{Position, Rect}; use ratatui_core::style::{Color, Style}; let mut buf = Buffer::empty(Rect { x: 0, y: 0, width: 10, height: 5, }); // indexing using Position buf[Position { x: 0, y: 0 }].set_symbol("A"); assert_eq!(buf[Position { x: 0, y: 0 }].symbol(), "A"); // indexing using (x, y) tuple (which is converted to Position) buf[(0, 1)].set_symbol("B"); assert_eq!(buf[(0, 1)].symbol(), "x"); // getting an Option instead of panicking if the position is outside the buffer let cell = buf.cell_mut(Position { x: 0, y: 2 })?; cell.set_symbol("C"); let cell = buf.cell(Position { x: 0, y: 2 })?; assert_eq!(cell.symbol(), "C"); buf.set_string( 3, 0, "string", Style::default().fg(Color::Red).bg(Color::White), ); let cell = &buf[(5, 0)]; // cannot move out of buf, so we borrow it assert_eq!(cell.symbol(), "r"); assert_eq!(cell.fg, Color::Red); assert_eq!(cell.bg, Color::White); ``` -------------------------------- ### Create and Configure a Table Source: https://docs.rs/ratatui/0.30.0/ratatui/widgets/struct.Table.html Demonstrates initializing a Table with rows and column constraints, including styling, headers, footers, and selection highlights. ```rust use ratatui::layout::Constraint; use ratatui::style::{Style, Stylize}; use ratatui::widgets::{Block, Row, Table}; let rows = [Row::new(vec!["Cell1", "Cell2", "Cell3"])]; // Columns widths are constrained in the same way as Layout... let widths = [ Constraint::Length(5), Constraint::Length(5), Constraint::Length(10), ]; let table = Table::new(rows, widths) // ...and they can be separated by a fixed spacing. .column_spacing(1) // You can set the style of the entire Table. .style(Style::new().blue()) // It has an optional header, which is simply a Row always visible at the top. .header( Row::new(vec!["Col1", "Col2", "Col3"]) .style(Style::new().bold()) // To add space between the header and the rest of the rows, specify the margin .bottom_margin(1), ) // It has an optional footer, which is simply a Row always visible at the bottom. .footer(Row::new(vec!["Updated on Dec 28"])) // As any other widget, a Table can be wrapped in a Block. .block(Block::new().title("Table")) // The selected row, column, cell and its content can also be styled. .row_highlight_style(Style::new().reversed()) .column_highlight_style(Style::new().red()) .cell_highlight_style(Style::new().blue()) // ...and potentially show a symbol in front of the selection. .highlight_symbol(">>"); ``` -------------------------------- ### Exact Strategy Example Source: https://docs.rs/ratatui/0.30.0/ratatui/prelude/symbols/merge/enum.MergeStrategy.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Shows the Exact strategy, which attempts to find a composite unicode character or falls back to replacement. ```rust let strategy = MergeStrategy::Exact; assert_eq!(strategy.merge("│", "━"), "┿"); // exact match exists assert_eq!(strategy.merge("┘", "╔"), "╔"); // no exact match, falls back to Replace ``` -------------------------------- ### size Source: https://docs.rs/ratatui/0.30.0/ratatui/backend/struct.TermionBackend.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Gets the terminal size. ```APIDOC ## fn size(&self) -> Result ### Description Get the size of the terminal screen in columns/rows as a `Size`. ``` -------------------------------- ### init / try_init Source: https://docs.rs/ratatui/0.30.0/ratatui/init/index.html?search=u32+-%3E+bool Creates a terminal instance with default settings, including alternate screen and raw mode. ```APIDOC ## fn init() -> DefaultTerminal ## fn try_init() -> Result ### Description Initializes the terminal with default configurations. `init` will panic on failure, while `try_init` returns a Result. ``` -------------------------------- ### window_size Source: https://docs.rs/ratatui/0.30.0/ratatui/backend/struct.CrosstermBackend.html?search=u32+-%3E+bool Gets the terminal window size. ```APIDOC ## fn window_size(&mut self) -> Result ### Description Get the size of the terminal screen in columns/rows and pixels as a `WindowSize`. ``` -------------------------------- ### set_span Source: https://docs.rs/ratatui/0.30.0/ratatui/buffer/struct.Buffer.html?search=std%3A%3Avec Print a span, starting at the position (x, y). ```APIDOC ## pub fn set_span(&mut self, x: u16, y: u16, span: &Span<'_>, max_width: u16) -> (u16, u16) ### Description Print a span, starting at the position (x, y). ``` -------------------------------- ### set_line Source: https://docs.rs/ratatui/0.30.0/ratatui/buffer/struct.Buffer.html?search=std%3A%3Avec Print a line, starting at the position (x, y). ```APIDOC ## pub fn set_line(&mut self, x: u16, y: u16, line: &Line<'_>, max_width: u16) -> (u16, u16) ### Description Print a line, starting at the position (x, y). ``` -------------------------------- ### init / try_init Source: https://docs.rs/ratatui/0.30.0/ratatui/init/index.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates a terminal instance with default settings, including raw mode and alternate screen. ```APIDOC ## fn init() -> DefaultTerminal ## fn try_init() -> Result> ### Description Initializes the terminal with reasonable defaults. `init` will panic on failure, while `try_init` returns a Result. ``` -------------------------------- ### set_string Source: https://docs.rs/ratatui/0.30.0/ratatui/buffer/struct.Buffer.html?search=std%3A%3Avec Print a string, starting at the position (x, y). ```APIDOC ## pub fn set_string(&mut self, x: u16, y: u16, string: T, style: S) ### Description Print a string, starting at the position (x, y). `T` must implement `AsRef` and `S` must implement `Into