inquire

repository·main·Indexed 25 days ago

https://github.com/mikaelmello/inquire

A Rust library for building interactive, highly customizable terminal prompts for CLI applications. It provides various prompt types including Text, Select, MultiSelect, Confirm, Password, CustomType, and gated types like Editor and DateSelect. Features include custom validators, formatters, scoring functions for filtering, and support for multiple terminal back-ends such as crossterm, console, and termion.

Tokens
20.1K
Snippets
44
Records
86
Agent score
80%

What's inside inquire

  1. Available prompt types in `inquire`

    main

    The library provides several interactive prompt types for CLI applications:

    • Text: Text input with built-in autocompletion.
    • Editor*: Long text input via an external text editor (requires date feature flag).
    • DateSelect*: Date input via an interactive calendar (requires date feature flag).
    • Select: Single option selection from a list.
    • MultiSelect: Multiple option selection from a list.
    • Confirm: Simple yes/no confirmation.
    • CustomType: Text input parsed into a custom type (e.g., numbers, UUIDs).
    • Password: Secretive text input for sensitive data.
  2. Configure terminal back-ends

    main

    By default, inquire uses crossterm to support Windows and UNIX. If your application already uses console or termion, you should disable default features and enable the specific backend to avoid dependency conflicts.

    To use termion:

    inquire = { version = "0.9.4", default-features = false, features = ["termion", "date"] }

    To use console:

    inquire = { version = "0.9.4", default-features = false, features = ["console", "date"] }
  3. Use custom formatters for user input

    main

    Formatters transform the user's input into a readable string displayed after submission. For example, you can use a formatter to add a currency symbol to a number or change a date format.

    Custom formatters receive the input (e.g., &str or chrono::NaiveDate) and must return a String.

  4. Configure global or local rendering (color themes)

    main

    You can customize the visual style of prompts using RenderConfig. This allows you to change foreground/background colors, attributes (like bold), and special tokens (like checkboxes or prefixes).

    To avoid setting the configuration for every individual prompt, you can use inquire::set_global_render_config to apply a default style to all future prompts in your application.

  5. Handle prompt cancellation and interruption

    main

    All inquire prompts support two types of termination via key bindings:

    1. Cancel (esc): Used when a prompt is skippable. You can use prompt_skippable to wrap the return type into an Option. This catches the CanceledOperation error and transforms it into Ok(None).
    2. Interrupt (ctrl + c): A "stop-the-world" operation. Library users should treat this as a command to terminate the application.
  6. Use `Selectable` derive macro for enums

    main

    You can automatically generate Select and MultiSelect prompts for your enum types by using the Selectable derive macro from the inquire-derive crate. This allows you to call .select() or .multi_select() directly on the enum type.

    #[derive(Debug, Copy, Clone, Selectable)]
    enum Color {
        Red,
        Green,
        Blue,
    }
    
    fn main() -> InquireResult<()> {
        let color = Color::select("Choose a color:").prompt()?;
        Ok(())
    }
  7. Use the Selectable derive macro on enums

    main

    The Selectable macro allows you to turn an enum into an interactive prompt. Your enum must implement Debug, Display, Copy, and Clone, and must be 'static.

    Once derived, the macro provides two methods:

    • select(msg: &str): Returns a Select builder for single selection.
    • multi_select(msg: &str): Returns a MultiSelect builder for multiple selection.

    Both methods return builders that can be customized (e.g., using .with_help_message() or .with_page_size()) before calling .prompt().

    use inquire_derive::Selectable;
    use std::fmt::{Display, Formatter};
    
    #[derive(Debug, Copy, Clone, Selectable)]
    enum Color {
        Red,
        Green,
        Blue,
    }
    
    impl Display for Color {
        fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
            write!(f, "{:?}", self)
        }
    }
    
    // Single selection usage:
    let color = Color::select("Choose a color:").prompt()?;
    
    // Multi-selection usage with customization:
    let colors = Color::multi_select("Choose colors:")
        .with_default(&[0, 1])
        .with_help_message("Space to select, Enter to confirm")
        .prompt()?;
  8. Generate Select and MultiSelect prompts for Enums using Selectable

    main

    You can use the Selectable derive macro from the inquire-derive crate to automatically generate Select and MultiSelect prompts for your enum types. This avoids manual mapping of enum variants to strings.

    Dependencies required in Cargo.toml:

    inquire = "0.9.4"
    inquire-derive = "0.9.0"
    #[derive(Debug, Copy, Clone, Selectable)]
    enum Color {
        Red,
        Green,
        Blue,
    }
    
    fn main() -> InquireResult<()> {
        let colors = Color::multi_select("Choose colors:").prompt()?;
        println!("Selected: {:?}", colors);
        Ok(())
    }