Skip to content

Commit

Permalink
Pass selected autocomplete option through the completer
Browse files Browse the repository at this point in the history
When using 'enter' to select an autocomplete suggestion, use the
autocompleter get_completion method to get the completed text before
accepting it instead of accepting just the suggestion. This allows the
completer to offer partial suggestions instead of having to offer the
full input each time.
  • Loading branch information
tpoliaw committed Dec 6, 2023
1 parent 1c7ece7 commit 6e72fcb
Showing 1 changed file with 13 additions and 9 deletions.
22 changes: 13 additions & 9 deletions inquire/src/prompts/text/prompt.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::cmp::min;
use std::{cmp::min, borrow::Cow};

use crate::{
autocompletion::{NoAutoCompletion, Replacement},
Expand Down Expand Up @@ -131,26 +131,30 @@ impl<'a> TextPrompt<'a> {
}
}

fn get_current_answer(&self) -> &str {
fn get_current_answer(&mut self) -> Cow<'_, str> {
// If there is a highlighted suggestion, assume user wanted it as
// the answer.
if let Some(suggestion) = self.get_highlighted_suggestion() {
return suggestion;
let opt = self.get_highlighted_suggestion();
if let Some(opt) = opt {
if let Ok(Some(value)) = self.autocompleter.get_completion(self.input.content(), Some(opt.into())) {
return value.into();
}
}

// Empty input with default values override any validators.
if self.input.content().is_empty() {
if let Some(val) = self.default {
return val;
return val.into();
}
}

self.input.content()
self.input.content().into()
}

fn validate_current_answer(&self) -> InquireResult<Validation> {
fn validate_current_answer(&mut self) -> InquireResult<Validation> {
let answer = self.get_current_answer().into_owned();
for validator in &self.validators {
match validator.validate(self.get_current_answer()) {
match validator.validate(&answer) {
Ok(Validation::Valid) => {}
Ok(Validation::Invalid(msg)) => return Ok(Validation::Invalid(msg)),
Err(err) => return Err(InquireError::Custom(err)),
Expand Down Expand Up @@ -194,7 +198,7 @@ where
}
};

Ok(result)
Ok(result.map(|r|r.into()))
}

fn handle(&mut self, action: TextPromptAction) -> InquireResult<ActionResult> {
Expand Down

0 comments on commit 6e72fcb

Please sign in to comment.