Ratatui API Overview
The ratatui crate exposes a small set of modules. Learning what each one owns makes the reference documentation on docs.rs much easier to navigate.
| Module / item | What it contains |
|---|---|
ratatui::run, init, restore | One-call terminal setup and teardown with a panic hook |
Terminal, Frame | The drawing entry point and the per-frame handle passed to your closure |
layout | Layout, Constraint, Rect, Direction, Flex, Margin |
widgets | Built-in widgets plus the Widget and StatefulWidget traits |
text | Span, Line and Text for styled content |
style | Style, Color, Modifier and the Stylize shorthand trait |
buffer | Buffer and Cell: the grid widgets render into |
backend | Backend trait, CrosstermBackend, TestBackend |
symbols | Border sets, bar and block characters, Braille and chart markers |
crossterm | Re-export of the crossterm crate when the feature is enabled |
Terminal Initialization
A Ratatui app must put the terminal into raw mode, switch to the alternate screen, and undo both on exit, including when the program panics. Three helpers cover almost every case:
ratatui::run(|terminal| ...)sets up, runs your closure and restores. It is the simplest option.ratatui::init()returns aDefaultTerminal; pair it withratatui::restore()when you need code between setup and teardown.ratatui::try_init()returns aResultinstead of panicking if setup fails.
use ratatui::crossterm::event::{self, Event, KeyCode};
use ratatui::widgets::Paragraph;
use ratatui::DefaultTerminal;
fn main() -> std::io::Result<()> {
let mut terminal = ratatui::init();
let result = run(&mut terminal);
ratatui::restore();
result
}
fn run(terminal: &mut DefaultTerminal) -> std::io::Result<()> {
loop {
terminal.draw(|frame| {
frame.render_widget(Paragraph::new("Hello from Ratatui (q to quit)"), frame.area());
})?;
if let Event::Key(key) = event::read()? {
if key.code == KeyCode::Char('q') {
return Ok(());
}
}
}
}For full control, for example an inline viewport that renders below the shell prompt instead of taking over the screen, build the terminal yourself with Terminal::with_options and a Viewport. Remember to enable and disable raw mode manually in that case.
Layout Management
Layout divides a Rect into smaller rectangles. Choose a direction with Layout::vertical or Layout::horizontal, pass one Constraint per area and destructure the result with .areas():
use ratatui::crossterm::event::{self, Event};
use ratatui::layout::{Constraint, Layout};
use ratatui::widgets::{Block, Paragraph};
use ratatui::Frame;
fn main() -> std::io::Result<()> {
ratatui::run(|terminal| {
terminal.draw(render)?;
event::read().map(|_: Event| ())
})
}
fn render(frame: &mut Frame) {
let [header, body, footer] = Layout::vertical([
Constraint::Length(3),
Constraint::Min(0),
Constraint::Length(1),
])
.areas(frame.area());
let [sidebar, main] =
Layout::horizontal([Constraint::Percentage(30), Constraint::Fill(1)]).areas(body);
frame.render_widget(Block::bordered().title(" Header "), header);
frame.render_widget(Block::bordered().title(" Sidebar "), sidebar);
frame.render_widget(Block::bordered().title(" Main "), main);
frame.render_widget(Paragraph::new("Press any key to exit"), footer);
}┌ Header ──────────────────────────────────┐ │ │ └──────────────────────────────────────────┘ ┌ Sidebar ──┐┌ Main ───────────────────────┐ │ ││ │ │ ││ │ │ ││ │ │ ││ │ └───────────┘└─────────────────────────────┘ Press any key to exit
| Constraint | Meaning |
|---|---|
Length(n) | Exactly n cells |
Percentage(p) | p percent of the available space |
Ratio(a, b) | a/b of the available space |
Min(n) / Max(n) | At least / at most n cells |
Fill(w) | Takes leftover space, shared by weight w |
Use .spacing(n) for gaps, .margin(n) for padding and .flex(Flex::Center) to position areas when constraints leave room. Read our layouts and constraints guide for responsive patterns.
Widgets
A widget is any type that implements Widget: it receives a Rect and a mutable Buffer and writes cells. Built-in widgets are created with builder methods every frame. Widgets that need persistent data between frames, such as the selected row of a table, implement StatefulWidget and take a separate state value (TableState, ListState, ScrollbarState).
Layout and text
Block, Paragraph, Clear
Collections
List, Table, Tabs, Scrollbar
Data visualization
Chart, BarChart, Sparkline, Canvas
Progress and dates
Gauge, LineGauge, Monthly calendar
Each widget is explained with a compiled example on the Ratatui widgets reference.
Rendering
terminal.draw(|frame| ...) gives you a Frame. Call frame.area() for the full drawable area, then frame.render_widget(widget, area) or frame.render_stateful_widget(widget, area, &mut state). When the closure returns, Ratatui diffs the new buffer against the previous one and flushes only the changes. You can also place the cursor with frame.set_cursor_position(), which text-input widgets rely on.
use ratatui::crossterm::event::{self, Event, KeyCode, KeyEventKind};
use ratatui::style::{Color, Modifier, Style};
use ratatui::widgets::{Block, List, ListState};
use ratatui::DefaultTerminal;
fn main() -> std::io::Result<()> {
ratatui::run(run)
}
fn run(terminal: &mut DefaultTerminal) -> std::io::Result<()> {
let items = ["Inbox", "Drafts", "Sent", "Archive", "Trash"];
let mut state = ListState::default().with_selected(Some(0));
loop {
terminal.draw(|frame| {
let list = List::new(items)
.block(Block::bordered().title(" Folders "))
.highlight_style(Style::new().bg(Color::Cyan).fg(Color::Black).add_modifier(Modifier::BOLD))
.highlight_symbol("> ");
frame.render_stateful_widget(list, frame.area(), &mut state);
})?;
if let Event::Key(key) = event::read()? {
if key.kind != KeyEventKind::Press {
continue;
}
match key.code {
KeyCode::Down | KeyCode::Char('j') => state.select_next(),
KeyCode::Up | KeyCode::Char('k') => state.select_previous(),
KeyCode::Char('q') => return Ok(()),
_ => {}
}
}
}
}Text and Styling
Styled text is built from three layers: a Span is a string with one style, a Line is a row of spans, and Text is a list of lines. The Stylize trait adds shorthand methods such as .bold(), .red() or .on_blue() to strings, spans and widgets.
use ratatui::crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind};
use ratatui::layout::Alignment;
use ratatui::style::Stylize;
use ratatui::text::Line;
use ratatui::widgets::{Block, Paragraph};
use ratatui::{DefaultTerminal, Frame};
#[derive(Default)]
struct App {
counter: i64,
exit: bool,
}
impl App {
fn run(&mut self, terminal: &mut DefaultTerminal) -> std::io::Result<()> {
while !self.exit {
terminal.draw(|frame| self.render(frame))?;
if let Event::Key(key) = event::read()? {
if key.kind == KeyEventKind::Press {
self.handle_key(key);
}
}
}
Ok(())
}
fn handle_key(&mut self, key: KeyEvent) {
match key.code {
KeyCode::Left | KeyCode::Char('j') => self.counter -= 1,
KeyCode::Right | KeyCode::Char('k') => self.counter += 1,
KeyCode::Char('q') | KeyCode::Esc => self.exit = true,
_ => {}
}
}
fn render(&self, frame: &mut Frame) {
let instructions = Line::from(vec![
" Decrement ".into(), "<Left>".blue().bold(),
" Increment ".into(), "<Right>".blue().bold(),
" Quit ".into(), "<Q> ".blue().bold(),
]);
let block = Block::bordered()
.title(Line::from(" Counter App ".bold()).centered())
.title_bottom(instructions.centered());
let text = Line::from(vec!["Value: ".into(), self.counter.to_string().yellow()]);
let paragraph = Paragraph::new(text)
.alignment(Alignment::Center)
.block(block);
frame.render_widget(paragraph, frame.area());
}
}
fn main() -> std::io::Result<()> {
ratatui::run(|terminal| App::default().run(terminal))
}Events and Input
Ratatui does not read input. With the default backend you use the re-exported crossterm API: event::read() blocks until an event arrives, while event::poll(timeout) lets you run timers. Always check KeyEventKind::Press so Windows does not deliver each key twice, and handle Event::Resize if you cache anything size-dependent. The Ratatui and crossterm guide covers mouse capture and async input.
Testing Ratatui Interfaces
TestBackend stores the rendered buffer in memory, so you can draw a frame in a unit test and compare it with expected text. This catches layout regressions without a real terminal.
use ratatui::backend::TestBackend;
use ratatui::widgets::{Block, Paragraph};
use ratatui::Terminal;
#[test]
fn renders_greeting() {
let mut terminal = Terminal::new(TestBackend::new(20, 3)).unwrap();
terminal
.draw(|frame| {
let p = Paragraph::new("Hi!").block(Block::bordered());
frame.render_widget(p, frame.area());
})
.unwrap();
terminal.backend().assert_buffer_lines([
"┌──────────────────┐",
"│Hi! │",
"└──────────────────┘",
]);
}Official Documentation and Resources
Official website
Tutorials, concepts, recipes and release highlights maintained by the project.
Source and examples
The repository's examples folder contains runnable demos for every widget.