Struct inquire::Text

source ·
pub struct Text<'a> {
    pub message: &'a str,
    pub initial_value: Option<&'a str>,
    pub default: Option<&'a str>,
    pub placeholder: Option<&'a str>,
    pub help_message: Option<&'a str>,
    pub formatter: StringFormatter<'a>,
    pub autocompleter: Option<Box<dyn Autocomplete>>,
    pub validators: Vec<Box<dyn StringValidator>>,
    pub page_size: usize,
    pub render_config: RenderConfig<'a>,
}
Expand description

Standard text prompt that returns the user string input.

This is the standard the standard kind of prompt you would expect from a library like this one. It displays a message to the user, prompting them to type something back. The user’s input is then stored in a String and returned to the prompt caller.

§Configuration options

  • Prompt message: Main message when prompting the user for input, "What is your name?" in the example below.
  • Help message: Message displayed at the line below the prompt.
  • Default value: Default value returned when the user submits an empty response.
  • Initial value: Initial value of the prompt’s text input, in case you want to display the prompt with something already filled in.
  • Placeholder: Short hint that describes the expected value of the input.
  • Validators: Custom validators to the user’s input, displaying an error message if the input does not pass the requirements.
  • Formatter: Custom formatter in case you need to pre-process the user input before showing it as the final answer.
  • Suggester: Custom function that returns a list of input suggestions based on the current text input. See more on “Autocomplete” below.

§Default behaviors

Default behaviors for each one of Text configuration options:

  • The input formatter just echoes back the given input.
  • No validators are called, accepting any sort of input including empty ones.
  • No default values or help messages.
  • No autocompletion features set-up.
  • Prompt messages are always required when instantiating via new().

§Autocomplete

With Text inputs, it is also possible to set-up an autocompletion system to provide a better UX when necessary.

You can call with_autocomplete() and provide a value that implements the Autocomplete trait. The Autocomplete trait has two provided methods: get_suggestions and get_completion.

  • get_suggestions is called whenever the user’s text input is modified, e.g. a new letter is typed, returning a Vec<String>. The Vec<String> is the list of suggestions that the prompt displays to the user according to their text input. The user can then navigate through the list and if they submit while highlighting one of these suggestions, the suggestion is treated as the final answer.
  • get_completion is called whenever the user presses the autocompletion hotkey (tab by default), with the current text input and the text of the currently highlighted suggestion, if any, as parameters. This method should return whether any text replacement (an autocompletion) should be made. If the prompt receives a replacement to be made, it substitutes the current text input for the string received from the get_completion call.

For example, in the complex_autocompletion.rs example file, the FilePathCompleter scans the file system based on the current text input, storing a list of paths that match the current text input.

Every time get_suggestions is called, the method returns the list of paths that match the user input. When the user presses the autocompletion hotkey, the FilePathCompleter checks whether there is any path selected from the list, if there is, it decides to replace the current text input for it. The interesting piece of functionality is that if there isn’t a path selected from the list, the FilePathCompleter calculates the longest common prefix amongst all scanned paths and updates the text input to an unambiguous new value. Similar to how terminals work when traversing paths.

§Example

use inquire::Text;

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."),
}

Fields§

§message: &'a str

Message to be presented to the user.

§initial_value: Option<&'a str>

Initial value of the prompt’s text input.

If you want to set a default value for the prompt, returned when the user’s submission is empty, see default.

§default: Option<&'a str>

Default value, returned when the user input is empty.

§placeholder: Option<&'a str>

Short hint that describes the expected value of the input.

§help_message: Option<&'a str>

Help message to be presented to the user.

§formatter: StringFormatter<'a>

Function that formats the user input and presents it to the user as the final rendering of the prompt.

§autocompleter: Option<Box<dyn Autocomplete>>

Autocompleter responsible for handling suggestions and input completions.

§validators: Vec<Box<dyn StringValidator>>

Collection of validators to apply to the user input.

Validators are executed in the order they are stored, stopping at and displaying to the user only the first validation error that might appear.

The possible error is displayed to the user one line above the prompt.

§page_size: usize

Page size of the suggestions displayed to the user, when applicable.

§render_config: RenderConfig<'a>

RenderConfig to apply to the rendered interface.

Note: The default render config considers if the NO_COLOR environment variable is set to decide whether to render the colored config or the empty one.

When overriding the config in a prompt, NO_COLOR is no longer considered and your config is treated as the only source of truth. If you want to customize colors and still support NO_COLOR, you will have to do this on your end.

Implementations§

source§

impl<'a> Text<'a>

source

pub const DEFAULT_FORMATTER: StringFormatter<'a> = DEFAULT_STRING_FORMATTER

Default formatter, set to DEFAULT_STRING_FORMATTER

source

pub const DEFAULT_PAGE_SIZE: usize = 7usize

Default page size, equal to the global default page size [config::DEFAULT_PAGE_SIZE]

source

pub const DEFAULT_VALIDATORS: Vec<Box<dyn StringValidator>> = _

Default validators added to the Text prompt, none.

source

pub const DEFAULT_HELP_MESSAGE: Option<&'a str> = None

Default help message.

source

pub fn new(message: &'a str) -> Self

Creates a Text with the provided message and default options.

source

pub fn with_help_message(self, message: &'a str) -> Self

Sets the help message of the prompt.

source

pub fn with_initial_value(self, message: &'a str) -> Self

Sets the initial value of the prompt’s text input.

If you want to set a default value for the prompt, returned when the user’s submission is empty, see with_default.

source

pub fn with_default(self, message: &'a str) -> Self

Sets the default input.

source

pub fn with_placeholder(self, placeholder: &'a str) -> Self

Sets the placeholder.

source

pub fn with_autocomplete<AC>(self, ac: AC) -> Self
where AC: Autocomplete + 'static,

Sets a new autocompleter

source

pub fn with_formatter(self, formatter: StringFormatter<'a>) -> Self

Sets the formatter.

source

pub fn with_page_size(self, page_size: usize) -> Self

Sets the page size

source

pub fn with_validator<V>(self, validator: V) -> Self
where V: StringValidator + 'static,

Adds a validator to the collection of validators. You might want to use this feature in case you need to require certain features from the user’s answer, such as defining a limit of characters.

Validators are executed in the order they are stored, stopping at and displaying to the user only the first validation error that might appear.

The possible error is displayed to the user one line above the prompt.

source

pub fn with_validators(self, validators: &[Box<dyn StringValidator>]) -> Self

Adds the validators to the collection of validators in the order they are given. You might want to use this feature in case you need to require certain features from the user’s answer, such as defining a limit of characters.

Validators are executed in the order they are stored, stopping at and displaying to the user only the first validation error that might appear.

The possible error is displayed to the user one line above the prompt.

source

pub fn with_render_config(self, render_config: RenderConfig<'a>) -> Self

Sets the provided color theme to this prompt.

Note: The default render config considers if the NO_COLOR environment variable is set to decide whether to render the colored config or the empty one.

When overriding the config in a prompt, NO_COLOR is no longer considered and your config is treated as the only source of truth. If you want to customize colors and still support NO_COLOR, you will have to do this on your end.

source

pub fn prompt_skippable(self) -> InquireResult<Option<String>>

Parses the provided behavioral and rendering options and prompts the CLI user for input according to the defined rules.

This method is intended for flows where the user skipping/cancelling the prompt - by pressing ESC - is considered normal behavior. In this case, it does not return Err(InquireError::OperationCanceled), but Ok(None).

Meanwhile, if the user does submit an answer, the method wraps the return type with Some.

source

pub fn prompt(self) -> InquireResult<String>

Parses the provided behavioral and rendering options and prompts the CLI user for input according to the defined rules.

Trait Implementations§

source§

impl<'a> Clone for Text<'a>

source§

fn clone(&self) -> Text<'a>

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<'a> From<&'a str> for Text<'a>

source§

fn from(val: &'a str) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

impl<'a> Freeze for Text<'a>

§

impl<'a> !RefUnwindSafe for Text<'a>

§

impl<'a> !Send for Text<'a>

§

impl<'a> !Sync for Text<'a>

§

impl<'a> Unpin for Text<'a>

§

impl<'a> !UnwindSafe for Text<'a>

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> DynClone for T
where T: Clone,

source§

fn __clone_box(&self, _: Private) -> *mut ()

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.