Introduction
crossterm is a pure Rust library that provides cross-platform terminal manipulation capabilities. It offers a single API for cursor control, text styling, input event handling, and raw mode across Windows (including legacy cmd.exe), macOS, and Linux terminals. It is the low-level foundation used by popular Rust TUI frameworks like Ratatui.
What crossterm Does
- Controls cursor position, visibility, and shape across all major platforms
- Applies text colors, background colors, bold, italic, underline, and other attributes
- Reads keyboard, mouse, and resize events synchronously or asynchronously
- Manages terminal modes including raw mode and alternate screen buffers
- Provides both command-based (queued) and immediate execution models
Architecture Overview
crossterm abstracts platform-specific terminal APIs behind a unified command interface. On Unix systems it uses ANSI escape sequences written to stdout. On Windows it uses the Console API for legacy terminals and ANSI sequences for Windows Terminal. Commands can be executed immediately with execute!() or queued with queue!() for batch flushing. The event system uses platform-native polling (epoll on Linux, kqueue on macOS, WaitForMultipleObjects on Windows).
Self-Hosting & Configuration
- Add crossterm as a dependency in Cargo.toml
- No C dependencies or build scripts; compiles as pure Rust
- Enable the event-stream feature for async event reading with tokio or async-std
- Use the serde feature to serialize/deserialize events and styles
- Compatible with Rust stable; no nightly features required
Key Features
- Pure Rust with no C bindings or unsafe dependencies
- Works on Windows (cmd.exe and Windows Terminal), macOS, and Linux
- Supports both synchronous and async (tokio/async-std) event streams
- Command pattern with queue!() and execute!() macros for efficient output
- Foundation library for Ratatui, the most popular Rust TUI framework
Comparison with Similar Tools
- termion — Unix-only Rust terminal library; crossterm adds Windows support
- ncurses/pancurses — C-based curses bindings; crossterm is pure Rust without FFI
- console (Rust) — focused on high-level styling; crossterm provides lower-level terminal control
- tcell (Go) — similar cross-platform terminal library but for the Go ecosystem
- prompt_toolkit (Python) — Python terminal toolkit; crossterm serves the Rust ecosystem
FAQ
Q: Does crossterm work on Windows cmd.exe? A: Yes. It uses the Windows Console API for legacy terminals and ANSI sequences for modern Windows Terminal.
Q: Is crossterm used by Ratatui? A: Yes. Ratatui uses crossterm as its default backend for terminal rendering.
Q: Can I read mouse events? A: Yes. Enable mouse capture with crossterm::event::EnableMouseCapture and read mouse events from the event stream.
Q: Does crossterm support async event handling? A: Yes. Enable the event-stream feature to use EventStream with tokio or async-std.