Convert Figma logo to code with AI

crossterm-rs logocrossterm

Cross platform terminal library rust

3,170
273
3,170
148

Top Related Projects

4,212

Rust library to create a Good Game Easily

2,094

Mirror of https://gitlab.redox-os.org/redox-os/termion

10,830

Build terminal user interfaces and dashboards using Rust

4,237

A Text User Interface library for the Rust programming language

Quick Overview

Crossterm is a cross-platform terminal manipulation library for Rust. It provides a uniform interface for working with terminals across different operating systems, allowing developers to create console applications with advanced features like cursor manipulation, color support, and event handling.

Pros

  • Cross-platform compatibility (Windows, macOS, Linux)
  • Rich set of terminal manipulation features
  • Easy to use and well-documented API
  • Actively maintained and regularly updated

Cons

  • Limited to terminal-based applications
  • May have slight performance overhead compared to platform-specific libraries
  • Some advanced features might not be available on all platforms
  • Learning curve for developers new to terminal manipulation concepts

Code Examples

  1. Printing colored text:
use crossterm::{
    execute,
    style::{Color, Print, ResetColor, SetForegroundColor},
};
use std::io::stdout;

fn main() -> crossterm::Result<()> {
    execute!(
        stdout(),
        SetForegroundColor(Color::Red),
        Print("This is red text"),
        ResetColor
    )
}
  1. Moving the cursor:
use crossterm::{
    execute,
    cursor::{MoveTo, MoveUp},
};
use std::io::stdout;

fn main() -> crossterm::Result<()> {
    execute!(
        stdout(),
        MoveTo(10, 5),
        Print("Moved to (10, 5)"),
        MoveUp(2),
        Print("Moved up 2 lines")
    )
}
  1. Handling keyboard events:
use crossterm::{
    event::{read, Event, KeyCode},
    terminal::{disable_raw_mode, enable_raw_mode},
};

fn main() -> crossterm::Result<()> {
    enable_raw_mode()?;

    loop {
        if let Event::Key(event) = read()? {
            match event.code {
                KeyCode::Char('q') => break,
                KeyCode::Char(c) => println!("You pressed: {}", c),
                _ => {}
            }
        }
    }

    disable_raw_mode()
}

Getting Started

To use Crossterm in your Rust project, add it to your Cargo.toml:

[dependencies]
crossterm = "0.26"

Then, in your Rust file:

use crossterm::{
    execute,
    style::{Color, Print, ResetColor, SetForegroundColor},
};
use std::io::stdout;

fn main() -> crossterm::Result<()> {
    execute!(
        stdout(),
        SetForegroundColor(Color::Green),
        Print("Hello, Crossterm!"),
        ResetColor
    )
}

This example prints "Hello, Crossterm!" in green text. Run your program to see the result in the terminal.

Competitor Comparisons

4,212

Rust library to create a Good Game Easily

Pros of ggez

  • Provides a complete game development framework with graphics, audio, and input handling
  • Offers higher-level abstractions for game-specific functionality
  • Includes built-in support for asset loading and resource management

Cons of ggez

  • Larger scope and more dependencies, potentially increasing complexity
  • May have a steeper learning curve for simple terminal-based applications
  • Less suitable for non-game applications or basic console utilities

Code Comparison

ggez example:

use ggez::{Context, GameResult};
use ggez::graphics::{self, Color};
use ggez::event::{self, EventHandler};

struct MainState {}

impl EventHandler for MainState {
    fn update(&mut self, _ctx: &mut Context) -> GameResult {
        Ok(())
    }

    fn draw(&mut self, ctx: &mut Context) -> GameResult {
        graphics::clear(ctx, Color::WHITE);
        graphics::present(ctx)?;
        Ok(())
    }
}

crossterm example:

use crossterm::{
    execute,
    style::{Color, Print, ResetColor, SetForegroundColor},
};

fn main() -> std::io::Result<()> {
    execute!(
        stdout(),
        SetForegroundColor(Color::Blue),
        Print("Hello, World!"),
        ResetColor
    )
}

The code examples highlight the different focus areas of each library. ggez provides a structured game loop and graphics handling, while crossterm offers low-level terminal control and styling.

2,094

Mirror of https://gitlab.redox-os.org/redox-os/termion

Pros of Termion

  • Lightweight and focused on Unix-like systems
  • Simpler API for basic terminal operations
  • Closer integration with Redox OS ecosystem

Cons of Termion

  • Limited cross-platform support (primarily Unix-like systems)
  • Less frequent updates and maintenance compared to Crossterm
  • Fewer advanced features for complex terminal manipulation

Code Comparison

Termion example:

use termion::{color, style};

println!("{}Red text{}", color::Fg(color::Red), color::Fg(color::Reset));
println!("{}Bold text{}", style::Bold, style::Reset);

Crossterm example:

use crossterm::{style::{Color, Stylize}, Result};

println!("{}", "Red text".red());
println!("{}", "Bold text".bold());

Both libraries provide similar functionality for basic terminal operations, but Crossterm offers a more ergonomic API and broader cross-platform support. Termion is more lightweight and Unix-focused, while Crossterm aims for wider compatibility and more advanced features. The choice between them depends on the specific requirements of your project, such as target platforms and desired terminal manipulation capabilities.

10,830

Build terminal user interfaces and dashboards using Rust

Pros of tui-rs

  • Provides a higher-level abstraction for building terminal user interfaces
  • Offers a rich set of widgets and layout options for complex TUI applications
  • Supports custom styling and theming for UI elements

Cons of tui-rs

  • Steeper learning curve due to its more complex API
  • May have slightly higher overhead for simple terminal interactions
  • Requires additional setup compared to direct terminal manipulation

Code Comparison

tui-rs:

let mut terminal = Terminal::new(backend)?;
terminal.draw(|f| {
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .margin(1)
        .constraints([Constraint::Percentage(10), Constraint::Percentage(80), Constraint::Percentage(10)].as_ref())
        .split(f.size());
    // ... (widget rendering code)
})?;

crossterm:

execute!(
    stdout(),
    SetForegroundColor(Color::Blue),
    SetBackgroundColor(Color::Red),
    Print("Styled text"),
    ResetColor
)?;

tui-rs is better suited for complex terminal user interfaces with multiple widgets and layouts, while crossterm provides more direct control over terminal operations and is simpler for basic terminal interactions.

4,237

A Text User Interface library for the Rust programming language

Pros of Cursive

  • Higher-level abstraction for building TUIs, offering pre-built widgets and layouts
  • More comprehensive UI toolkit with built-in theming and styling options
  • Easier to create complex, interactive interfaces with less code

Cons of Cursive

  • Steeper learning curve due to more complex API and concepts
  • Less flexibility for low-level terminal manipulation
  • Potentially higher resource usage for simple applications

Code Comparison

Crossterm (basic output):

use crossterm::{execute, style::Print};
use std::io::stdout;

fn main() -> crossterm::Result<()> {
    execute!(stdout(), Print("Hello, World!"))?;
    Ok(())
}

Cursive (basic UI):

use cursive::views::{Dialog, TextView};

fn main() {
    let mut siv = cursive::default();
    siv.add_layer(Dialog::around(TextView::new("Hello, World!"))
        .title("My App")
        .button("Quit", |s| s.quit()));
    siv.run();
}

Crossterm focuses on low-level terminal control, while Cursive provides a higher-level UI framework. Crossterm is more suitable for simple CLI tools or as a foundation for custom TUI libraries, whereas Cursive is better for quickly building complex, interactive terminal applications with rich user interfaces.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Donate Travis Latest Version MIT docs Lines of Code Join us on Discord

Cross-platform Terminal Manipulation Library

Crossterm is a pure-rust, terminal manipulation library that makes it possible to write cross-platform text-based interfaces (see features). It supports all UNIX and Windows terminals down to Windows 7 (not all terminals are tested, see Tested Terminals for more info).

Table of Contents

Features

  • Cross-platform
  • Multi-threaded (send, sync)
  • Detailed documentation
  • Few dependencies
  • Full control over writing and flushing output buffer
  • Is tty
  • Cursor
    • Move the cursor N times (up, down, left, right)
    • Move to previous / next line
    • Move to column
    • Set/get the cursor position
    • Store the cursor position and restore to it later
    • Hide/show the cursor
    • Enable/disable cursor blinking (not all terminals do support this feature)
  • Styled output
    • Foreground color (16 base colors)
    • Background color (16 base colors)
    • 256 (ANSI) color support (Windows 10 and UNIX only)
    • RGB color support (Windows 10 and UNIX only)
    • Text attributes like bold, italic, underscore, crossed, etc
  • Terminal
    • Clear (all lines, current line, from cursor down and up, until new line)
    • Scroll up, down
    • Set/get the terminal size
    • Exit current process
    • Alternate screen
    • Raw screen
    • Set terminal title
    • Enable/disable line wrapping
  • Event
    • Input Events
    • Mouse Events (press, release, position, button, drag)
    • Terminal Resize Events
    • Advanced modifier (SHIFT | ALT | CTRL) support for both mouse and key events and
    • futures Stream (feature 'event-stream')
    • Poll/read API

Tested Terminals

  • Console Host
    • Windows 10 (Pro)
    • Windows 8.1 (N)
  • Windows Terminal
    • Windows 10 x86_64 (Enterprise)
    • Windows 11 arm64 (Enterprise)
  • Ubuntu Desktop Terminal
    • Ubuntu 23.04 64-bit
    • Ubuntu 17.10
    • Pop!_OS ( Ubuntu ) 20.04
  • (Arch, Manjaro) KDE Konsole
  • (Arch, NixOS) Kitty
  • Linux Mint
  • (OpenSuse) Alacritty
  • (Chrome OS) Crostini
  • Apple
    • macOS Monterey 12.7.1 (Intel-Chip)
    • macOS Sonama 14.4 (M1 Max, Apple Silicon-Chip)

This crate supports all UNIX terminals and Windows terminals down to Windows 7; however, not all of the terminals have been tested. If you have used this library for a terminal other than the above list without issues, then feel free to add it to the above list - I really would appreciate it!

Getting Started

see the examples directory and documentation for more advanced examples.

Click to show Cargo.toml.
[dependencies]
crossterm = "0.27"

use std::io::{stdout, Write};

use crossterm::{
    execute,
    style::{Color, Print, ResetColor, SetBackgroundColor, SetForegroundColor},
    ExecutableCommand,
    event,
};

fn main() -> std::io::Result<()> {
    // using the macro
    execute!(
        stdout(),
        SetForegroundColor(Color::Blue),
        SetBackgroundColor(Color::Red),
        Print("Styled text here."),
        ResetColor
    )?;

    // or using functions
    stdout()
        .execute(SetForegroundColor(Color::Blue))?
        .execute(SetBackgroundColor(Color::Red))?
        .execute(Print("Styled text here."))?
        .execute(ResetColor)?;
    
    Ok(())
}

Checkout this list with all possible commands.

Feature Flags

[dependencies.crossterm]
version = "0.27"
features = ["event-stream"] 
FeatureDescription
event-streamfutures::Stream producing Result<Event>.
serde(De)serializing of events.
eventsReading input/system events (enabled by default)
filedescriptorUse raw filedescriptor for all events rather then mio dependency

To use crossterm as a very thin layer you can disable the events feature or use filedescriptor feature. This can disable mio / signal-hook / signal-hook-mio dependencies.

Dependency Justification

DependencyUsed forIncluded
bitflagsKeyModifiers, those are differ based on input.always
parking_lotlocking RwLocks with a timeout, const mutexes.always
libcUNIX terminal_size/raw modes/set_title and several other low level functionality.optional (events feature), UNIX only
Mioevent readiness polling, waking up polleroptional (events feature), UNIX only
signal-hooksignal-hook is used to handle terminal resize SIGNAL with Mio.optional (events feature),UNIX only
winapiUsed for low-level windows system calls which ANSI codes can't replacewindows only
futures-coreFor async stream of eventsonly with event-stream feature flag
serdeserializing and deserializing of eventsonly with serde feature flag

Other Resources

Used By

Contributing

We highly appreciate when anyone contributes to this crate. Before you do, please, read the Contributing guidelines.

Authors

  • Timon Post - Project Owner & creator

License

This project, crossterm and all its sub-crates: crossterm_screen, crossterm_cursor, crossterm_style, crossterm_input, crossterm_terminal, crossterm_winapi, crossterm_utils are licensed under the MIT License - see the LICENSE file for details.