A Rust library for building interactive prompts
inquire is a library for building interactive prompts on terminals.
It provides several different prompts in order to interactively ask the user for information via the CLI. With inquire, you can use:
Text] to get text input from the user, with built-in autocompletion support;Editor]* to get longer text inputs by opening a text editor for the user;DateSelect]* to get a date input from the user, selected via an interactive calendar;Select] to ask the user to select one option from a given list;MultiSelect] to ask the user to select an arbitrary number of options from a given list;Confirm] for simple yes/no confirmation prompts;CustomType] for text prompts that you would like to parse to a custom type, such as numbers or UUIDs;Password] for secretive text prompts.crossterm (default), termion or console.Text] prompts;Password] prompts;Select] and [MultiSelect] prompts;Confirm] and [CustomType] prompts;Editor] prompts;Examples can be found in the examples directory. Run them to see basic behavior:
cargo run --example expense_tracker -p inquire-examplesPut this line in your Cargo.toml, under [dependencies].
inquire = "0.9.4"* This prompt type is gated under a feature flag, e.g.:
inquire = { version = "0.9.4", features = ["date"] }There are several features that are shared among different types of prompts. This section will give an overview on each of them.
All prompts allow you to set a custom RenderConfig, a struct that contains lots of style customization options.
With RenderConfig, you can customize foreground color, background color and attributes (e.g. bold) of most components that are part of a prompt. Additionally, you can also customize the content of special tokens, such as prompt prefixes, highlighted-option prefixes, selected and unselected checkboxes, etc. If you do not want to re-set the render config object for each new prompt you create, you can call inquire::set_global_render_config to set a global RenderConfig object to be used as the default one for all future prompts.
This allows you to have greater control over the style of your application while continuing to have a clean API to create prompts as smoothly as possible.
In the render_config.rs example, you can take a look at the capabilities of this API. The example is exactly the same one as expense_tracker.rs, but with several style aspects customized. Take a look at their differences:
Almost all prompts provide an API to set custom validators.
The validators provided to a given prompt are called whenever the user submits their input. These validators vary by prompt type, receiving different types of variables as arguments, such as &str, &[ListOption], or NaiveDate, but their return type are always the same: Result<Validation, CustomUserError>.
The Validation type is an enum that indicates whether the user input is valid, in which you should return Ok(Validation::Invalid), or invalid, where you should return Ok(Validation::Invalid(ErrorMessage)). The ErrorMessage type is another enum, containing the Default and Custom(String) variants, indicating the message to indicate the user that their input is invalid.
With an Invalid result, it is recommended that you set the ErrorMessage field to a custom message containing helpful feedback to the user, e.g. "This field should contain at least 5 characters".
The CustomUserError type is an alias to Box<dyn std::error::Error + Send + Sync + 'static>. Added to support validators with fallible operations, such as HTTP requests or database queries. If the validator returns Err(CustomUserError), the prompt will return Err(InquireError::Custom(CustomUserError)) as its result, containing the error you returned wrapped around the enums mentioned.
The validators are typed as a reference to dyn Fn. This allows both functions and closures to be used as validators, but it also means that the functions can not hold any mutable references.
Finally, inquire has a feature called macros that is included by default. When the feature is on, several shorthand macros for the builtin validators are exported at the root-level of the library. Check their documentation to see more details, they provide full-featured examples.
In the demo you can see the behavior of an input not passing the requirements in the amount prompt, when the error message "Please type a valid number" is displayed. Full disclosure, this error message was displayed due to a parsing, not validation, error, but the user experience is the same for both cases.
If you'd like to see more examples, the date.rs and multiselect.rs files contain custom validators.
Currently, there are like 3 major libraries to manipulate terminals: crossterm, console and termion.
Binary Rust applications that intend to manipulate terminals will probably pick any one of these 3 to power underlying abstractions. inquire chose to support crossterm by default in order to support many features on Windows out-of-the-box.
However, if your application already uses a dependency other than crossterm, such as console or termion, you can enable another terminal via feature flags. It is also important to disable inquire's default features as it comes with crossterm enabled by default. Such as this:
inquire = { version = "0.9.4", default-features = false, features = ["termion", "date"] }or this:
inquire = { version = "0.9.4", default-features = false, features = ["console", "date"] }Formatting is the process of transforming the user input into a readable output displayed after the user submits their response. By default, this is in some cases just echoing back the input itself, such as in Text prompts. Other prompts have different formatting rules by default, for example DateSelect which formats the selected date into something like "August 5, 2021".
All prompts provide an API to set custom formatters. By setting a formatter, you can customize how the user's response is displayed to them. For example, you might want to format a selected date into a new format such as "05/08/2021".
Custom formatters receive the input as an argument, with varying types such as &str, chrono::NaiveDate, and return a String containing the output to be displayed to the user. Check the docs for specific examples.
In the demo you can see this behavior in action with the amount (CustomType) prompt, where a custom formatter adds a '$' character prefix to the input.
Parsing features are related to two prompts: [Confirm] and [CustomType]. They return to you a value (of types bool or any custom type you might want) parsed from the user's text input. In both cases, you can either use default parsers that are already built-in or provide custom ones adhering to the function signatures.
The default bool parser returns true if the input is either "y" or "yes", in a case-insensitive comparison. Similarly, the parser returns false if the input is either "n" or "no".
The default parser for [CustomType] prompts calls the parse::<T>() method on the input string. This means that if you want to create a [CustomType] with default settings, the wanted return type must implement the FromStr trait.
In the demo you can see this behavior in action with the amount (CustomType) prompt.
Scoring is applicable to two prompts: [Select] and [MultiSelect]. They provide the user the ability to sort and filter the list of options based on their text input. This is specially useful when there are a lot of options for the user to choose from, allowing them to quickly find their expected options.
Scoring functions receive four arguments: the current user input, the option, the option string value and the option index. They must return a Option<i64> value indicating whether the option should be part of the results or not.
The default scoring function calculates a match value with the current user input and each option using SkimV2 from fuzzy_matcher, resulting in fuzzy searching and filtering, returning Some(<score>_i64) if SkimV2 detects a match.
In the demo you can see this behavior in action with the account (Select) and tags (MultiSelect) prompts.
Error handling when using inquire is pretty simple. Instantiating prompt structs is not fallible by design, in order to avoid requiring chaining of map and and_then methods to subsequent configuration method calls such as with_help_message(). All fallible operations are exposable only when you call prompt() on the instantiated prompt struct.
prompt calls return a Result containing either your expected response value or an Err of type InquireError. An InquireError has the following variants:
Select], [MultiSelect] and [DateSelect] prompts, where specific settings might be incompatible. All other prompts always have valid configurations by design.inquire to keep the library simple.Ctrl-C or ESC.To see all of the keybindings registered by prompts, check t
No open issues yet, or sync has not completed.