### Run Example Source: https://github.com/mikaelmello/inquire/blob/main/README.md Execute the example provided in the Inquire crate to observe its basic behavior. ```bash cargo run --example expense_tracker -p inquire-examples ``` -------------------------------- ### Run Derive Macro Examples Source: https://github.com/mikaelmello/inquire/blob/main/inquire-derive/CRATE_README.md Execute the provided cargo commands to run the example applications demonstrating the `enum_select_derive` and `enum_comprehensive` functionalities. ```bash cargo run --example enum_select_derive ``` ```bash cargo run --example enum_comprehensive ``` -------------------------------- ### Create and Prompt DateSelect Source: https://github.com/mikaelmello/inquire/blob/main/README.md Demonstrates how to create a DateSelect prompt with custom default, min/max dates, and week start day. Includes basic error handling for the prompt. ```rust let date = DateSelect::new("When do you want to travel?") .with_default(chrono::NaiveDate::from_ymd(2021, 8, 1)) .with_min_date(chrono::NaiveDate::from_ymd(2021, 8, 1)) .with_max_date(chrono::NaiveDate::from_ymd(2021, 12, 31)) .with_week_start(chrono::Weekday::Mon) .with_help_message("Possible flights will be displayed according to the selected date") .prompt(); match date { Ok(_) => println!("No flights available for this date."), Err(_) => println!("There was an error in the system."), } ``` -------------------------------- ### Install Inquire Crate with Date Feature Source: https://github.com/mikaelmello/inquire/blob/main/README.md To use the DateSelect prompt, enable the 'date' feature flag in your Cargo.toml. ```toml inquire = { version = "0.9.4", features = ["date"] } ``` -------------------------------- ### CustomType Prompt for Struct Construction (chrono::NaiveDate) Source: https://context7.com/mikaelmello/inquire/llms.txt Demonstrates direct struct construction for CustomType when the target type does not implement FromStr, using chrono::NaiveDate as an example. Requires custom parser and formatter functions. ```rust use chrono::NaiveDate; use inquire::ui::RenderConfig; use inquire::CustomType; // Direct struct construction for a type without FromStr (chrono::NaiveDate) let date_prompt: CustomType = CustomType { message: "Enter birth date (dd/mm/yyyy):", starting_input: None, default: None, placeholder: Some("25/07/1990"), help_message: "Format: DD/MM/YYYY".into(), error_message: "Invalid date. Use DD/MM/YYYY.".into(), formatter: &|d| d.format("%B %-e, %Y").to_string(), default_value_formatter: &|d| d.format("%d/%m/%Y").to_string(), parser: &|s| NaiveDate::parse_from_str(s, "%d/%m/%Y").map_err(|_| ()), validators: vec![], render_config: RenderConfig::default(), }; let dob = date_prompt.prompt()?; println!("Born: {dob}"); ``` -------------------------------- ### Single Select with Custom Options and Formatting Source: https://context7.com/mikaelmello/inquire/llms.txt Use `Select` for single-option lists with fuzzy filtering. Customize page size, starting cursor, navigation mode, and output formatting. `raw_prompt()` returns index and value. ```rust use inquire::{Select, list_option::ListOption}; #[derive(Debug)] struct Country { name: &'static str, code: &'static str } impl std::fmt::Display for Country { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "{} ({})", self.name, self.code) } } let countries = vec![ Country { name: "Brazil", code: "BR" }, Country { name: "Canada", code: "CA" }, Country { name: "France", code: "FR" }, Country { name: "Germany", code: "DE" }, Country { name: "United States", code: "US" }, ]; // Use raw_prompt to get both index and value let ListOption { index, value } = Select::new("Select your country:", countries) .with_page_size(5) .with_starting_cursor(2) // pre-highlight France .with_vim_mode(true) // hjkl navigation .with_formatter(&|opt| format!("✔ {}", opt.value)) .raw_prompt()?; println!("Index {}: {}", index, value.name); ``` ```rust // Skippable variant let maybe = Select::new("Optional:", vec!["A", "B", "C"]) .prompt_skippable()?; // Option<&str> ``` -------------------------------- ### DateSelect Prompt with Calendar Navigation and Validation Source: https://context7.com/mikaelmello/inquire/llms.txt Provides an interactive calendar for selecting dates, supporting keyboard navigation, min/max boundaries, week start configuration, and custom validation for weekdays. Requires the 'date' feature. ```rust // Cargo.toml: inquire = { version = "0.9.4", features = ["date"] } use chrono::{NaiveDate, Weekday, Datelike}; use inquire::{DateSelect, validator::Validation}; let booking_date = DateSelect::new("Select appointment date:") .with_starting_date(NaiveDate::from_ymd_opt(2025, 1, 1).unwrap()) .with_min_date(NaiveDate::from_ymd_opt(2025, 1, 1).unwrap()) .with_max_date(NaiveDate::from_ymd_opt(2025, 12, 31).unwrap()) .with_week_start(Weekday::Mon) .with_validator(|d: NaiveDate| { if d.weekday() == Weekday::Sat || d.weekday() == Weekday::Sun { Ok(Validation::Invalid("Weekends are not available.".into())) } else { Ok(Validation::Valid) } }) .with_formatter(&|d| d.format("%A, %B %-e, %Y").to_string()) .with_help_message("Weekdays only; arrows to navigate, enter to select") .prompt()?; println!("Appointment: {}", booking_date.format("%A, %B %-e, %Y")); ``` -------------------------------- ### Simple Select Prompt in Rust Source: https://github.com/mikaelmello/inquire/blob/main/README.md Demonstrates how to create a basic Select prompt with a list of string options. Ensure the options vector is non-empty to avoid configuration errors. ```rust let options: Vec<&str> = vec!["Banana", "Apple", "Strawberry", "Grapes", "Lemon", "Tangerine", "Watermelon", "Orange", "Pear", "Avocado", "Pineapple"]; let ans: Result<&str, InquireError> = Select::new("What's your favorite fruit?", options).prompt(); match ans { Ok(choice) => println!("{}! That's mine too!", choice), Err(_) => println!("There was an error, please try again"), } ``` -------------------------------- ### Basic Password Prompt in Rust Source: https://github.com/mikaelmello/inquire/blob/main/README.md Demonstrates how to create and prompt for a password using the `Password::new()` constructor. Handles potential errors during the prompt. ```rust let name = Password::new("Encryption key:").prompt(); match name { Ok(_) => println!("This doesn't look like a key."), Err(_) => println!("An error happened when asking for your key, try again later."), } ``` -------------------------------- ### Create and Prompt with CustomType Source: https://github.com/mikaelmello/inquire/blob/main/README.md Demonstrates creating a `CustomType` prompt for an f64 value, including custom formatter, error message, and help message. The prompt is then displayed to the user, and the result is handled. ```rust let amount = CustomType::::new("How much do you want to donate?") .with_formatter(&|i| format!("${:.2}", i)) .with_error_message("Please type a valid number") .with_help_message("Type the amount in US dollars using a decimal point as a separator") .prompt(); match amount { Ok(_) => println!("Thanks a lot for donating that much money!"), Err(_) => println!("We could not process your donation"), } ``` -------------------------------- ### Basic and Advanced Text Input Prompts in Rust Source: https://context7.com/mikaelmello/inquire/llms.txt Demonstrates simple and feature-rich text input prompts using the `inquire` crate. Includes usage of validators, placeholders, default values, autocomplete, and skippable prompts. ```rust use inquire::{Text, required, min_length}; // Simple usage let name = Text::new("What is your name?").prompt()?; // Full-featured usage with validator, placeholder, default, and simple autocomplete let frameworks = vec!["React", "Vue", "Svelte", "Angular"]; let framework = Text::new("Favorite framework:") .with_placeholder("e.g. React") .with_default("React") .with_help_message("Type to filter suggestions") .with_validator(required!()) .with_validator(min_length!(2, "Must be at least 2 characters")) .with_autocomplete(move |input: &str| -> Result, _> { Ok(frameworks .iter() .filter(|f| f.to_lowercase().contains(&input.to_lowercase())) .map(|f| f.to_string()) .collect()) }) .with_formatter(&|s| format!("→ {s}")) .with_page_size(5) .prompt()?; println!("You chose: {framework}"); // If user presses ESC, use prompt_skippable: let optional = Text::new("Optional comment:").prompt_skippable()?; ``` -------------------------------- ### Basic Text Prompt in Rust Source: https://github.com/mikaelmello/inquire/blob/main/README.md Use Text::new() to create a standard prompt. The prompt() method displays the message and returns the user's input as a Result. ```rust let name = Text::new("What is your name?").prompt(); match name { Ok(name) => println!("Hello {}", name), Err(_) => println!("An error happened when asking for your name, try again later."), } ``` -------------------------------- ### Confirm with Default and Help Message Source: https://context7.com/mikaelmello/inquire/llms.txt Use `Confirm` for simple yes/no prompts. Set a default value and provide a help message for user guidance. ```rust use inquire::Confirm; // Simple confirm with default let proceed = Confirm::new("Do you want to continue?") .with_default(true) .with_help_message("This action cannot be undone") .prompt()?; if proceed { println!("Proceeding..."); } ``` -------------------------------- ### Set Global Render Configuration Source: https://github.com/mikaelmello/inquire/blob/main/README.md Use `inquire::set_global_render_config` to set a default RenderConfig for all prompts. This avoids re-setting the configuration for each new prompt. ```rust inquire::set_global_render_config(render_config); ``` -------------------------------- ### Customize Prompt Appearance with RenderConfig Source: https://context7.com/mikaelmello/inquire/llms.txt Use RenderConfig to control colors, styles, and symbols for prompt elements. Apply themes globally with set_global_render_config() or per-prompt with .with_render_config(). ```rust use inquire::{ Text, set_global_render_config, ui::{Attributes, Color, RenderConfig, StyleSheet, Styled}, }; fn build_theme() -> RenderConfig<'static> { let mut cfg = RenderConfig::default(); // Prompt prefix symbol and color cfg.prompt_prefix = Styled::new("❯").with_fg(Color::LightCyan); // Highlighted item in lists cfg.highlighted_option_prefix = Styled::new("▶").with_fg(Color::LightGreen); // Checkboxes for MultiSelect cfg.selected_checkbox = Styled::new("☑").with_fg(Color::LightGreen); cfg.unselected_checkbox = Styled::new("☐").with_fg(Color::DarkGrey); // Scroll indicators cfg.scroll_up_prefix = Styled::new("⇡"); cfg.scroll_down_prefix = Styled::new("⇣"); // Answer display style cfg.answer = StyleSheet::new() .with_fg(Color::LightYellow) .with_attr(Attributes::BOLD); // Help message style cfg.help_message = StyleSheet::new().with_fg(Color::DarkGrey); // Error message prefix cfg.error_message = cfg.error_message .with_prefix(Styled::new("✖").with_fg(Color::LightRed)); cfg } fn main() { // Set globally for all prompts set_global_render_config(build_theme()); let name = Text::new("Your name:").prompt().unwrap(); println!("Hello, {name}!"); } ``` -------------------------------- ### Manually Instantiate CustomType for Dates Source: https://github.com/mikaelmello/inquire/blob/main/README.md Shows how to manually instantiate a `CustomType` prompt for `chrono::NaiveDate` when the default parser or formatter is insufficient. This allows for custom parsing logic and specific date formatting. ```rust let amount_prompt: CustomType = CustomType { message: "When will you travel?", formatter: &|val| val.format("%d/%m/%Y").to_string(), default: None, error_message: "Please type a valid date in the expected format.".into(), help_message: "The date should be in the dd/mm/yyyy format.".into(), parser: &|i| match chrono::NaiveDate::parse_from_str(i, "%d/%m/%Y") { Ok(val) => Ok(val), Err(_) => Err(()), }, }; ``` -------------------------------- ### Multi-line Input with External Editor Source: https://context7.com/mikaelmello/inquire/llms.txt Use the `Editor` prompt to open the user's default terminal editor for multi-line input. Supports predefined text, file extensions for syntax highlighting, and custom validators. Requires the `editor` feature. ```rust // Cargo.toml: inquire = { version = "0.9.4", features = ["editor"] } use std::ffi::OsStr; use inquire::{Editor, validator::Validation, required}; let commit_message = Editor::new("Commit message:") .with_predefined_text("feat: ") .with_file_extension(".md") .with_editor_command(OsStr::new("vim")) .with_validator(required!("Commit message cannot be empty")) .with_validator(|s: &str| { if s.lines().next().map(|l| l.len()).unwrap_or(0) > 72 { Ok(Validation::Invalid("First line must be ≤72 characters".into())) } else { Ok(Validation::Valid) } }) .with_formatter(&|_| String::from("")) .with_help_message("Press 'e' to open editor, Enter to submit") .prompt()?; println!("Commit recorded."); ``` -------------------------------- ### Enable Feature Flags for Inquire Source: https://github.com/mikaelmello/inquire/blob/main/inquire/CRATE_README.md To use feature-gated prompts like 'date' and 'editor', specify them in your Cargo.toml. ```toml inquire = { version = "0.9.4", features = ["date", "editor"] } ``` -------------------------------- ### Add Inquire to Cargo.toml Source: https://github.com/mikaelmello/inquire/blob/main/inquire/CRATE_README.md Include the inquire crate in your project's dependencies by adding this to your Cargo.toml file. ```toml inquire = "0.9.4" ``` -------------------------------- ### Custom Autocomplete Logic for Text Prompts in Rust Source: https://context7.com/mikaelmello/inquire/llms.txt Shows how to implement the `Autocomplete` trait for custom suggestion and completion logic in `inquire` text prompts. The `get_suggestions` method provides options on keystroke, and `get_completion` handles tab completion. ```rust use inquire::{ autocompletion::{Autocomplete, Replacement}, CustomUserError, Text, }; #[derive(Clone, Default)] struct CountryCompleter { countries: Vec<&'static str>, } impl Autocomplete for CountryCompleter { fn get_suggestions(&mut self, input: &str) -> Result, CustomUserError> { Ok(self.countries .iter() .filter(|c| c.to_lowercase().starts_with(&input.to_lowercase())) .map(|c| c.to_string()) .collect()) } fn get_completion( &mut self, _input: &str, highlighted_suggestion: Option, ) -> Result { // Accept the highlighted suggestion, or do nothing Ok(highlighted_suggestion) } } let completer = CountryCompleter { countries: vec!["Brazil", "Canada", "France", "Germany", "United States"], }; let country = Text::new("Country:") .with_autocomplete(completer) .prompt()?; println!("Selected: {country}"); ``` -------------------------------- ### Customize Select Prompts Source: https://github.com/mikaelmello/inquire/blob/main/inquire-derive/CRATE_README.md Customize the behavior and appearance of single and multi-select prompts generated by the `Selectable` derive macro using methods like `with_help_message` and `with_page_size`. ```rust let color = Color::select("Choose a color:") .with_help_message("Use arrow keys to navigate") .with_page_size(5) .prompt()?; ``` ```rust let colors = Color::multi_select("Choose colors:") .with_default(&[0, 1]) // Pre-select first two options .with_help_message("Space to select, Enter to confirm") .prompt()?; ``` -------------------------------- ### Confirm with Custom Parser and Formatter Source: https://context7.com/mikaelmello/inquire/llms.txt Customize `Confirm` prompts by providing a custom parser for non-standard yes/no inputs and a formatter for localized output. ```rust use inquire::{Confirm, parser::BoolParser, formatter::BoolFormatter}; // Custom parser accepting Spanish yes/no let parser: BoolParser = &|ans| match ans.to_lowercase().as_str() { "si" | "s" => Ok(true), "no" | "n" => Ok(false), _ => Err(()), }; let formatter: BoolFormatter = &|b| if b { "Sí".into() } else { "No".into() }; let confirmed = Confirm::new("¿Continuar?") .with_parser(parser) .with_formatter(formatter) .with_error_message("Escriba 'si' o 'no'") .prompt()?; println!("Respuesta: {}", if confirmed { "Sí" } else { "No" }); ``` -------------------------------- ### Create and Prompt a Confirm Question in Rust Source: https://github.com/mikaelmello/inquire/blob/main/README.md Use the Confirm prompt for simple yes/no questions. It wraps CustomType prompts with sensible defaults for boolean questions. The default parser accepts 'y', 'n', 'yes', 'no' case-insensitively. Custom validators are not supported as the input is always parsed to true or false. ```rust let ans = Confirm::new("Do you live in Brazil?") .with_default(false) .with_help_message("This data is stored for good reasons") .prompt(); match ans { Ok(true) => println!("That's awesome!"), Ok(false) => println!("That's too bad, I've heard great things about it."), Err(_) => println!("Error with questionnaire, try again later"), } ``` -------------------------------- ### Use One-liner Prompt Helpers Source: https://context7.com/mikaelmello/inquire/llms.txt Convenience free functions like prompt_text, prompt_secret, and prompt_f64 wrap common single-line prompt calls. These require the 'one-liners' feature, which is enabled by default. ```rust use inquire:: prompt_confirmation, prompt_text, prompt_secret, prompt_f64, error::InquireResult, ; fn main() -> InquireResult<()> { // Equivalent to Text::new(...).prompt() let name = prompt_text("What is your name?")?; // Equivalent to Password::new(...).prompt() let token = prompt_secret("GitHub token:")?; // Equivalent to CustomType::::new(...).prompt() let weight = prompt_f64("Weight (kg):")?; // Equivalent to Confirm::new(...).prompt() let confirmed = prompt_confirmation("Save changes?")?; if confirmed { println!("Saving {name}'s data (weight={weight:.1}kg, token length={})", token.len()); } Ok(()) } ``` -------------------------------- ### Derive Macro for Enum Select Prompt in Rust Source: https://github.com/mikaelmello/inquire/blob/main/README.md Shows how to use the `Selectable` derive macro from `inquire-derive` to automatically generate a Select prompt for an enum. Add `inquire` and `inquire-derive` to your Cargo.toml. ```toml inquire = "0.9.4" inquire-derive = "0.9.0" ``` ```rust #[derive(Debug, Copy, Clone, Selectable)] enum Color { Red, Green, Blue, } fn main() -> InquireResult<()> { let color = Color::select("Choose a color:").prompt()?; println!("Selected: {}", color); Ok(()) } ``` -------------------------------- ### Use Selectable Derive Macro for Enums Source: https://github.com/mikaelmello/inquire/blob/main/inquire/CRATE_README.md Automatically generate Select and MultiSelect prompts for enum types by adding the 'inquire-derive' crate and using the 'Selectable' derive macro. ```rust use inquire_derive::Selectable; use inquire::InquireResult; #[derive(Debug, Copy, Clone, Selectable)] enum Color { Red, Green, Blue, } fn main() -> InquireResult<()> { let color = Color::select("Choose a color:").prompt()?; Ok(()) } ``` -------------------------------- ### Add inquire-derive to Cargo.toml Source: https://github.com/mikaelmello/inquire/blob/main/inquire-derive/CRATE_README.md Include `inquire` and `inquire-derive` in your project's dependencies to use the derive macros. ```toml inquire = "0.9.4" inquire-derive = "0.9.4" ``` -------------------------------- ### Generate Enum Prompts with Selectable Derive Macro Source: https://context7.com/mikaelmello/inquire/llms.txt The Selectable derive macro from inquire-derive automatically generates .select() and .multi_select() methods for Copy + Clone enums that implement Display. This simplifies creating Select and MultiSelect prompts. ```rust // Cargo.toml: // inquire = "0.9.4" // inquire-derive = "0.9.0" use std::fmt; use inquire::error::InquireResult; use inquire_derive::Selectable; #[derive(Debug, Copy, Clone, Selectable)] enum Region { NorthAmerica, Europe, AsiaPacific, LatinAmerica, } impl fmt::Display for Region { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Region::NorthAmerica => write!(f, "North America"), Region::Europe => write!(f, "Europe"), Region::AsiaPacific => write!(f, "Asia Pacific"), Region::LatinAmerica => write!(f, "Latin America"), } } } fn main() -> InquireResult<()> { // Single-select: returns Region let primary: Region = Region::select("Primary region:").prompt()?; println!("Primary: {primary}"); // Multi-select: returns Vec let regions: Vec = Region::multi_select("Additional regions:") .with_help_message("Space to toggle, enter to confirm") .prompt()?; println!("All regions: {:?}", regions); Ok(()) } ``` -------------------------------- ### Password Prompt with Masking, Toggle, and Validation Source: https://context7.com/mikaelmello/inquire/llms.txt Securely collect password input with masking, an option to toggle visibility, custom confirmation, and robust validation rules. The formatter can obscure the input for display. ```rust use inquire::{Password, PasswordDisplayMode, validator::Validation}; let password = Password::new("Create password:") .with_display_mode(PasswordDisplayMode::Masked) // show * for each char .with_display_toggle_enabled() // Ctrl+R reveals input .with_custom_confirmation_message("Confirm password:") .with_custom_confirmation_error_message("Passwords do not match. Try again.") .with_validator(|input: &str| { let has_upper = input.chars().any(|c| c.is_uppercase()); let has_digit = input.chars().any(|c| c.is_numeric()); let has_special = input.chars().any(|c| "!@#$%^&*".contains(c)); if input.len() < 8 { Ok(Validation::Invalid("Must be at least 8 characters.".into())) } else if !has_upper || !has_digit || !has_special { Ok(Validation::Invalid("Must include uppercase, digit, and special char.".into())) } else { Ok(Validation::Valid) } }) .with_formatter(&|_| String::from("[hidden]")) .with_help_message("Min 8 chars, uppercase, digit, and special character") .prompt()?; println!("Password accepted."); ``` -------------------------------- ### Enable Console Terminal Back-end Source: https://github.com/mikaelmello/inquire/blob/main/README.md To use the console terminal back-end, disable default features and enable the 'console' feature flag in your Cargo.toml. ```toml inquire = { version = "0.9.4", default-features = false, features = ["console", "date"] } ``` -------------------------------- ### Answer Formatting for Prompts Source: https://context7.com/mikaelmello/inquire/llms.txt Customize the display of submitted answers using formatters. Different formatter types exist for various prompt types, including `StringFormatter`, `BoolFormatter`, `OptionFormatter`, `MultiOptionFormatter`, `CustomTypeFormatter`, and `DateFormatter`. ```rust use inquire::{ Text, Confirm, Select, MultiSelect, CustomType, formatter::{StringFormatter, BoolFormatter, OptionFormatter, MultiOptionFormatter}, list_option::ListOption, }; // StringFormatter: capitalize first letter let name_fmt: StringFormatter = &|s| { let mut c = s.chars(); c.next().map(|f| f.to_uppercase().to_string() + c.as_str()).unwrap_or_default() }; let name = Text::new("Name:").with_formatter(name_fmt).prompt()?; // BoolFormatter: localized output let bool_fmt: BoolFormatter = &|b| if b { "Oui".into() } else { "Non".into() }; let ok = Confirm::new("Confirmer?").with_formatter(bool_fmt).prompt()?; // OptionFormatter: show index let opt_fmt: OptionFormatter<&str> = &|opt| format!("[{}] {}", opt.index + 1, opt.value); let choice = Select::new("Pick:", vec!["Alpha", "Beta", "Gamma"]) .with_formatter(opt_fmt) .prompt()?; // MultiOptionFormatter: count summary let multi_fmt: MultiOptionFormatter<&str> = &|opts| format!("{} item(s) selected", opts.len()); let items = MultiSelect::new("Items:", vec!["A", "B", "C", "D"]) .with_formatter(multi_fmt) .prompt()?; // CustomTypeFormatter: currency let amount = CustomType::::new("Amount:") .with_formatter(&|v| format!("€{:.2}", v)) .prompt()?; ``` -------------------------------- ### Handle Inquire Errors and Cancellations Source: https://context7.com/mikaelmello/inquire/llms.txt Match on InquireError variants to handle different error conditions, including user cancellation, interruptions, and I/O errors. Use `prompt_skippable()` to gracefully handle optional inputs where cancellation should result in `None`. ```rust use inquire::{Text, Select, error::{InquireError, InquireResult}}; fn ask_name() -> InquireResult { Text::new("Name:").prompt() } fn main() { match ask_name() { Ok(name) => println!("Hello, {name}!"), Err(InquireError::OperationCanceled) => println!("Prompt was cancelled (ESC)."), Err(InquireError::OperationInterrupted) => println!("Interrupted (Ctrl+C)."), Err(InquireError::NotTTY) => eprintln!("Not running in a terminal."), Err(InquireError::IO(e)) => eprintln!("I/O error: {e}"), Err(InquireError::InvalidConfiguration(msg)) => eprintln!("Config error: {msg}"), Err(InquireError::Custom(e)) => eprintln!("Validator error: {e}"), } // Using prompt_skippable to handle ESC gracefully let role = Select::new("Role:", vec!["Admin", "User", "Guest"]) .prompt_skippable() // InquireResult> .unwrap_or(None); println!("Role: {}", role.unwrap_or("(none selected)")); } ``` -------------------------------- ### Enable Termion Terminal Back-end Source: https://github.com/mikaelmello/inquire/blob/main/README.md To use the termion terminal back-end, disable default features and enable the 'termion' feature flag in your Cargo.toml. ```toml inquire = { version = "0.9.4", default-features = false, features = ["termion", "date"] } ``` -------------------------------- ### CustomType Prompt for f64 with Formatting and Validation Source: https://context7.com/mikaelmello/inquire/llms.txt Use CustomType to parse user input into an f64 with custom currency formatting and range validation. Ensure the type implements FromStr and ToString. ```rust use inquire::{CustomType, validator::Validation}; // f64 with currency formatter and range validator let amount = CustomType::::new("Donation amount (USD):") .with_placeholder("e.g. 25.00") .with_default(10.0) .with_formatter(&|v| format!("${:.2}", v)) .with_error_message("Please enter a valid number") .with_help_message("Minimum $1.00, maximum $10,000.00") .with_validator(|v: &f64| { if *v < 1.0 { Ok(Validation::Invalid("Minimum donation is $1.00".into())) } else if *v > 10_000.0 { Ok(Validation::Invalid("Maximum donation is $10,000.00".into())) } else { Ok(Validation::Valid) } }) .prompt()?; println!("Thank you for donating ${:.2}!", amount); ``` -------------------------------- ### Password Prompt without Confirmation Source: https://context7.com/mikaelmello/inquire/llms.txt Use Password prompt for single-shot secret input without requiring a confirmation step. Supports hidden display mode. ```rust use inquire::{Password, PasswordDisplayMode}; // Single-shot without confirmation let token = Password::new("API Token:") .without_confirmation() .with_display_mode(PasswordDisplayMode::Hidden) .prompt()?; ``` -------------------------------- ### MultiSelect with Validation and Custom Formatting Source: https://context7.com/mikaelmello/inquire/llms.txt Use `MultiSelect` for zero or more selections. Supports pre-selected defaults, custom validators, and configurable filtering behavior. The formatter can customize the display of selected options. ```rust use inquire::{MultiSelect, list_option::ListOption, validator::{Validation, MultiOptionValidator}}; let tags = vec!["rust", "async", "cli", "web", "database", "testing", "embedded"]; // Validator limiting selection to 1–3 items let validator = |opts: &[ListOption<&&str>]| { match opts.len() { 0 => Ok(Validation::Invalid("Select at least one tag.".into())), 1..=3 => Ok(Validation::Valid), _ => Ok(Validation::Invalid("Select at most 3 tags.".into())), } }; let selected = MultiSelect::new("Choose tags:", tags) .with_default(&[0, 2]) // pre-select "rust" and "cli" .with_page_size(5) .with_keep_filter(false) // clear filter after each selection .with_validator(validator) .with_formatter(&|opts| { opts.iter().map(|o| format!("#{{}}", o.value)).collect::>().join(" ") }) .prompt()?; println!("Selected: {:?}", selected); ``` -------------------------------- ### Input Validation with Built-in Macros and Custom Closures Source: https://context7.com/mikaelmello/inquire/llms.txt Implement input validation using built-in macros like `required!`, `min_length!`, `max_length!`, and `length!`, or custom closure validators. Supports `StringValidator`, `DateValidator`, `MultiOptionValidator`, and `CustomTypeValidator` traits. ```rust use inquire::{ Text, MultiSelect, required, min_length, max_length, length, validator::{Validation, StringValidator, MultiOptionValidator}, list_option::ListOption, error::CustomUserError, }; // Built-in macros let username = Text::new("Username:") .with_validator(required!()) .with_validator(min_length!(3, "At least 3 characters")) .with_validator(max_length!(20, "At most 20 characters")) .prompt()?; // Custom closure validator with async-compatible error type let email = Text::new("Email:") .with_validator(|input: &str| -> Result { if input.contains('@') && input.contains('.') { Ok(Validation::Valid) } else { Ok(Validation::Invalid("Enter a valid email address".into())) } }) .prompt()?; // MultiOptionValidator on MultiSelect let skills = MultiSelect::new("Skills:", vec!["Rust", "Go", "Python", "Java", "C++"]) .with_validator(|opts: &[ListOption<&&str>]| { if opts.is_empty() { Ok(Validation::Invalid("Please select at least one skill.".into())) } else { Ok(Validation::Valid) } }) .prompt()?; println!("User: {username}, Email: {email}, Skills: {:?}", skills); ``` -------------------------------- ### Derive Selectable for Enums Source: https://github.com/mikaelmello/inquire/blob/main/inquire-derive/CRATE_README.md Apply the `Selectable` derive macro to your enum to enable single and multi-select prompts. Ensure the enum implements `Display`, `Debug`, `Copy`, `Clone`, and is `'static`. ```rust 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) } } // Now you can use: // let color = Color::select("Choose a color:").prompt()?; // let colors = Color::multi_select("Choose colors:").prompt()?; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.