Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for Alt-Left/Right and Alt-Backspace editing #9

Merged
merged 2 commits into from
Jan 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/password.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,12 @@ impl PromptInteraction<String> for Password {
Some(&mut self.input)
}

fn allow_word_editing(&self) -> bool {
// Disallow word editing for password prompts so as not to reveal
// password structure.
false
}

fn on(&mut self, event: &Event) -> State<String> {
let Event::Key(key) = event;

Expand Down
46 changes: 46 additions & 0 deletions src/prompt/cursor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,27 @@ pub struct StringCursor {
cursor: usize,
}

/// Returns the indices of the first character of each word in the given string,
/// as well as the indices of the start and end of the string. The returned
/// indices are sorted in ascending order.
fn word_jump_indices(value: &[char]) -> Vec<usize> {
let mut indices = vec![0];
let mut in_word = false;

for (i, ch) in value.iter().enumerate() {
if ch.is_whitespace() {
in_word = false;
} else if !in_word {
indices.push(i);
in_word = true;
}
}

indices.push(value.len());

indices
}

impl StringCursor {
pub fn is_empty(&self) -> bool {
self.value.is_empty()
Expand All @@ -34,6 +55,20 @@ impl StringCursor {
}
}

pub fn move_left_by_word(&mut self) {
let jumps = word_jump_indices(&self.value);
let ix = jumps.binary_search(&self.cursor).unwrap_or_else(|i| i);
self.cursor = jumps[ix.saturating_sub(1)];
}

pub fn move_right_by_word(&mut self) {
let jumps = word_jump_indices(&self.value);
let ix = jumps
.binary_search(&self.cursor)
.map_or_else(|i| i, |i| i + 1);
self.cursor = jumps[std::cmp::min(ix, jumps.len().saturating_sub(1))];
}

pub fn move_home(&mut self) {
self.cursor = 0;
}
Expand Down Expand Up @@ -63,6 +98,17 @@ impl StringCursor {
}
}

pub fn delete_word_to_the_left(&mut self) {
if self.cursor > 0 {
let jumps = word_jump_indices(&self.value);
let ix = jumps.binary_search(&self.cursor).unwrap_or_else(|x| x);
let start = jumps[std::cmp::max(ix - 1, 0)];
let end = self.cursor;
self.value.drain(start..end);
self.cursor = start;
}
}

pub fn extend(&mut self, string: &str) {
self.value.extend(string.chars());
}
Expand Down
24 changes: 24 additions & 0 deletions src/prompt/interaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,12 @@ pub trait PromptInteraction<T> {
None
}

/// Whether features like Alt-Backspace and Alt-ArrowLeft/Right are allowed.
/// Word editing is disabled for password prompts, for example.
fn allow_word_editing(&self) -> bool {
true
}

/// Starts the interaction with the user via stderr.
fn interact(&mut self) -> io::Result<T> {
self.interact_on(&mut Term::stderr())
Expand Down Expand Up @@ -96,6 +102,7 @@ pub trait PromptInteraction<T> {
Ok(Key::Escape) => state = State::Cancel,

Ok(key) => {
let word_editing = self.allow_word_editing();
if let Some(cursor) = self.input() {
match key {
Key::Char(chr) if !chr.is_ascii_control() => cursor.insert(chr),
Expand All @@ -105,6 +112,23 @@ pub trait PromptInteraction<T> {
Key::ArrowRight => cursor.move_right(),
Key::Home => cursor.move_home(),
Key::End => cursor.move_end(),

// Alt-Backspace
Key::Char('\u{17}') if word_editing => cursor.delete_word_to_the_left(),

// Alt-ArrowLeft
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Basically, Ctrl-Left/Ctrl-Right behave similarly in Bash, could Ctrl be enabled as well? Thanks!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes... but i propose doing so in a separate PR :)

Key::UnknownEscSeq(ref chars)
if word_editing && chars.as_slice() == ['b'] =>
{
cursor.move_left_by_word()
}
// Alt-ArrowRight
Key::UnknownEscSeq(ref chars)
if word_editing && chars.as_slice() == ['f'] =>
{
cursor.move_right_by_word()
}

_ => {}
}
}
Expand Down