inquire/prompts/text/mod.rs
1mod action;
2mod config;
3mod prompt;
4#[cfg(test)]
5#[cfg(feature = "crossterm")]
6mod test;
7
8pub use action::*;
9
10use crate::{
11 autocompletion::Autocomplete,
12 config::get_configuration,
13 error::{InquireError, InquireResult},
14 formatter::{StringFormatter, DEFAULT_STRING_FORMATTER},
15 prompts::prompt::Prompt,
16 terminal::get_default_terminal,
17 ui::{Backend, RenderConfig, TextBackend},
18 validator::StringValidator,
19};
20
21use self::prompt::TextPrompt;
22
23const DEFAULT_HELP_MESSAGE_WITH_AC: &str = "↑↓ to move, tab to autocomplete, enter to submit";
24
25/// Standard text prompt that returns the user string input.
26///
27/// 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.
28///
29///
30/// ## Configuration options
31///
32/// - **Prompt message**: Main message when prompting the user for input, `"What is your name?"` in the example below.
33/// - **Help message**: Message displayed at the line below the prompt.
34/// - **Default value**: Default value returned when the user submits an empty response.
35/// - **Initial value**: Initial value of the prompt's text input, in case you want to display the prompt with something already filled in.
36/// - **Placeholder**: Short hint that describes the expected value of the input.
37/// - **Validators**: Custom validators to the user's input, displaying an error message if the input does not pass the requirements.
38/// - **Formatter**: Custom formatter in case you need to pre-process the user input before showing it as the final answer.
39/// - **Suggester**: Custom function that returns a list of input suggestions based on the current text input. See more on "Autocomplete" below.
40///
41/// ## Default behaviors
42///
43/// Default behaviors for each one of `Text` configuration options:
44///
45/// - The input formatter just echoes back the given input.
46/// - No validators are called, accepting any sort of input including empty ones.
47/// - No default values or help messages.
48/// - No autocompletion features set-up.
49/// - Prompt messages are always required when instantiating via `new()`.
50///
51/// ## Autocomplete
52///
53/// With `Text` inputs, it is also possible to set-up an autocompletion system to provide a better UX when necessary.
54///
55/// 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`.
56///
57/// - `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.
58/// - `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.
59///
60/// 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.
61///
62/// 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.
63///
64/// # Example
65///
66/// ```no_run
67/// use inquire::Text;
68///
69/// let name = Text::new("What is your name?").prompt();
70///
71/// match name {
72/// Ok(name) => println!("Hello {}", name),
73/// Err(_) => println!("An error happened when asking for your name, try again later."),
74/// }
75/// ```
76#[derive(Clone)]
77pub struct Text<'a> {
78 /// Message to be presented to the user.
79 pub message: &'a str,
80
81 /// Initial value of the prompt's text input.
82 ///
83 /// If you want to set a default value for the prompt, returned when the user's submission is empty, see [`default`].
84 ///
85 /// [`default`]: Self::default
86 pub initial_value: Option<&'a str>,
87
88 /// Default value, returned when the user input is empty.
89 pub default: Option<&'a str>,
90
91 /// Short hint that describes the expected value of the input.
92 pub placeholder: Option<&'a str>,
93
94 /// Help message to be presented to the user.
95 pub help_message: Option<&'a str>,
96
97 /// Function that formats the user input and presents it to the user as the final rendering of the prompt.
98 pub formatter: StringFormatter<'a>,
99
100 /// Autocompleter responsible for handling suggestions and input completions.
101 pub autocompleter: Option<Box<dyn Autocomplete>>,
102
103 /// Collection of validators to apply to the user input.
104 ///
105 /// Validators are executed in the order they are stored, stopping at and displaying to the user
106 /// only the first validation error that might appear.
107 ///
108 /// The possible error is displayed to the user one line above the prompt.
109 pub validators: Vec<Box<dyn StringValidator>>,
110
111 /// Page size of the suggestions displayed to the user, when applicable.
112 pub page_size: usize,
113
114 /// RenderConfig to apply to the rendered interface.
115 ///
116 /// Note: The default render config considers if the NO_COLOR environment variable
117 /// is set to decide whether to render the colored config or the empty one.
118 ///
119 /// When overriding the config in a prompt, NO_COLOR is no longer considered and your
120 /// config is treated as the only source of truth. If you want to customize colors
121 /// and still support NO_COLOR, you will have to do this on your end.
122 pub render_config: RenderConfig<'a>,
123}
124
125impl<'a> Text<'a> {
126 /// Default formatter, set to [DEFAULT_STRING_FORMATTER](crate::formatter::DEFAULT_STRING_FORMATTER)
127 pub const DEFAULT_FORMATTER: StringFormatter<'a> = DEFAULT_STRING_FORMATTER;
128
129 /// Default page size, equal to the global default page size [config::DEFAULT_PAGE_SIZE]
130 pub const DEFAULT_PAGE_SIZE: usize = crate::config::DEFAULT_PAGE_SIZE;
131
132 /// Default validators added to the [Text] prompt, none.
133 pub const DEFAULT_VALIDATORS: Vec<Box<dyn StringValidator>> = vec![];
134
135 /// Default help message.
136 pub const DEFAULT_HELP_MESSAGE: Option<&'a str> = None;
137
138 /// Creates a [Text] with the provided message and default options.
139 pub fn new(message: &'a str) -> Self {
140 Self {
141 message,
142 placeholder: None,
143 initial_value: None,
144 default: None,
145 help_message: Self::DEFAULT_HELP_MESSAGE,
146 validators: Self::DEFAULT_VALIDATORS,
147 formatter: Self::DEFAULT_FORMATTER,
148 page_size: Self::DEFAULT_PAGE_SIZE,
149 autocompleter: None,
150 render_config: get_configuration(),
151 }
152 }
153
154 /// Sets the help message of the prompt.
155 pub fn with_help_message(mut self, message: &'a str) -> Self {
156 self.help_message = Some(message);
157 self
158 }
159
160 /// Sets the initial value of the prompt's text input.
161 ///
162 /// If you want to set a default value for the prompt, returned when the user's submission is empty, see [`with_default`].
163 ///
164 /// [`with_default`]: Self::with_default
165 pub fn with_initial_value(mut self, message: &'a str) -> Self {
166 self.initial_value = Some(message);
167 self
168 }
169
170 /// Sets the default input.
171 pub fn with_default(mut self, message: &'a str) -> Self {
172 self.default = Some(message);
173 self
174 }
175
176 /// Sets the placeholder.
177 pub fn with_placeholder(mut self, placeholder: &'a str) -> Self {
178 self.placeholder = Some(placeholder);
179 self
180 }
181
182 /// Sets a new autocompleter
183 pub fn with_autocomplete<AC>(mut self, ac: AC) -> Self
184 where
185 AC: Autocomplete + 'static,
186 {
187 self.autocompleter = Some(Box::new(ac));
188 self
189 }
190
191 /// Sets the formatter.
192 pub fn with_formatter(mut self, formatter: StringFormatter<'a>) -> Self {
193 self.formatter = formatter;
194 self
195 }
196
197 /// Sets the page size
198 pub fn with_page_size(mut self, page_size: usize) -> Self {
199 self.page_size = page_size;
200 self
201 }
202
203 /// Adds a validator to the collection of validators. You might want to use this feature
204 /// in case you need to require certain features from the user's answer, such as
205 /// defining a limit of characters.
206 ///
207 /// Validators are executed in the order they are stored, stopping at and displaying to the user
208 /// only the first validation error that might appear.
209 ///
210 /// The possible error is displayed to the user one line above the prompt.
211 pub fn with_validator<V>(mut self, validator: V) -> Self
212 where
213 V: StringValidator + 'static,
214 {
215 self.validators.push(Box::new(validator));
216 self
217 }
218
219 /// Adds the validators to the collection of validators in the order they are given.
220 /// You might want to use this feature in case you need to require certain features
221 /// from the user's answer, such as defining a limit of characters.
222 ///
223 /// Validators are executed in the order they are stored, stopping at and displaying to the user
224 /// only the first validation error that might appear.
225 ///
226 /// The possible error is displayed to the user one line above the prompt.
227 pub fn with_validators(mut self, validators: &[Box<dyn StringValidator>]) -> Self {
228 for validator in validators {
229 #[allow(suspicious_double_ref_op)]
230 self.validators.push(validator.clone());
231 }
232 self
233 }
234
235 /// Sets the provided color theme to this prompt.
236 ///
237 /// Note: The default render config considers if the NO_COLOR environment variable
238 /// is set to decide whether to render the colored config or the empty one.
239 ///
240 /// When overriding the config in a prompt, NO_COLOR is no longer considered and your
241 /// config is treated as the only source of truth. If you want to customize colors
242 /// and still support NO_COLOR, you will have to do this on your end.
243 pub fn with_render_config(mut self, render_config: RenderConfig<'a>) -> Self {
244 self.render_config = render_config;
245 self
246 }
247
248 /// Parses the provided behavioral and rendering options and prompts
249 /// the CLI user for input according to the defined rules.
250 ///
251 /// This method is intended for flows where the user skipping/cancelling
252 /// the prompt - by pressing ESC - is considered normal behavior. In this case,
253 /// it does not return `Err(InquireError::OperationCanceled)`, but `Ok(None)`.
254 ///
255 /// Meanwhile, if the user does submit an answer, the method wraps the return
256 /// type with `Some`.
257 pub fn prompt_skippable(self) -> InquireResult<Option<String>> {
258 match self.prompt() {
259 Ok(answer) => Ok(Some(answer)),
260 Err(InquireError::OperationCanceled) => Ok(None),
261 Err(err) => Err(err),
262 }
263 }
264
265 /// Parses the provided behavioral and rendering options and prompts
266 /// the CLI user for input according to the defined rules.
267 pub fn prompt(self) -> InquireResult<String> {
268 let (input_reader, terminal) = get_default_terminal()?;
269 let mut backend = Backend::new(input_reader, terminal, self.render_config)?;
270 self.prompt_with_backend(&mut backend)
271 }
272
273 pub(crate) fn prompt_with_backend<B: TextBackend>(
274 self,
275 backend: &mut B,
276 ) -> InquireResult<String> {
277 TextPrompt::from(self).prompt(backend)
278 }
279}