[go: up one dir, main page]

Module init

Source
Available on crate feature crossterm only.
Expand description

Terminal initialization and restoration functions.

This module provides a set of convenience functions for initializing and restoring terminal state when creating Ratatui applications. These functions handle the common setup and teardown tasks required for terminal user interfaces.

All functions in this module use the CrosstermBackend by default, which provides excellent cross-platform compatibility and is the recommended backend for most applications. The DefaultTerminal type alias encapsulates this choice, providing a ready-to-use terminal configuration that works well across different operating systems. For more information about backend choices and alternatives, see the backend module.

Once you have initialized a terminal using the functions in this module, you can use it to draw the UI and handle events. For more information about building widgets for your application, see the widgets module.

Note: All functions and types in this module are re-exported at the crate root for convenience, so you can call ratatui::run(), ratatui::init(), etc. instead of ratatui::init::run(), ratatui::init::init(), etc.

§Available Types and Functions

§Types

  • DefaultTerminal - A type alias for Terminal<CrosstermBackend<Stdout>>, providing a reasonable default terminal configuration for most applications. All initialization functions return this type.

§Functions

The module provides several related functions that handle different initialization scenarios:

  • run - Initializes a terminal, runs a closure, and automatically restores the terminal state. This is the simplest way to run a Ratatui application and handles all setup and cleanup automatically.
  • init - Creates a terminal with reasonable defaults including alternate screen and raw mode. Panics on failure.
  • try_init - Same as init but returns a Result instead of panicking.
  • init_with_options - Creates a terminal with custom TerminalOptions, enabling raw mode but not alternate screen. Panics on failure.
  • try_init_with_options - Same as init_with_options but returns a Result instead of panicking.
  • 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.

§Usage Guide

For the simplest setup with automatic cleanup, use run:

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(());
            }
        }
    })
}

For standard full-screen applications with manual control over initialization and cleanup:

// 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()?;

For applications that need custom terminal behavior (inline rendering, custom viewport sizes, or applications that don’t want alternate screen buffer):

use ratatui::{TerminalOptions, Viewport};

let options = TerminalOptions {
    viewport: Viewport::Inline(10),
};

// Using init_with_options() - panics on failure
let mut terminal = ratatui::init_with_options(options);
// ... app logic ...
ratatui::restore();

// 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)?;
// ... app logic ...
ratatui::try_restore()?;

For cleanup, use restore in most cases where you want to attempt restoration but don’t need to handle errors (they are printed to stderr). Use try_restore when you need to handle restoration errors, perhaps to retry or provide user feedback.

Once you have a terminal set up, continue with the main loop to draw the UI and handle events. See the main crate documentation for comprehensive examples of complete applications.

§Key Differences

FunctionAlternate ScreenRaw ModeError HandlingUse Case
runAuto-cleanupSimple apps
initPanicStandard full-screen apps
try_initResultStandard apps with error handling
init_with_optionsPanicCustom viewport apps
try_init_with_optionsResultCustom viewport with error handling

§Panic Hook

All initialization functions install a panic hook that automatically restores the terminal state before panicking. This ensures that even if your application panics, the terminal will be left in a usable state.

Important: Call the initialization functions after installing any other panic hooks to ensure the terminal is restored before other hooks run.

Functions§

init
Initialize a terminal with reasonable defaults for most applications.
init_with_options
Initialize a terminal with the given options and reasonable defaults.
restore
Restores the terminal to its original state.
run
Run a closure with a terminal initialized with reasonable defaults for most applications.
try_init
Try to initialize a terminal using reasonable defaults for most applications.
try_init_with_options
Try to initialize a terminal with the given options and reasonable defaults.
try_restore
Restore the terminal to its original state.

Type Aliases§

DefaultTerminal
A type alias for the default terminal type.