Skip to content

Commit

Permalink
feat: Allow abbreviating longer terms into shorter
Browse files Browse the repository at this point in the history
Previously, we only supported the abbreviation being shorter than its
expansion, e.g. `gs` -> `git status`. Now, the opposite is supported,
e.g. `exa` -> `ls`.

This solution can be enhanced when the feature "mixed_integer_ops" is
released in stable (tracking:
rust-lang/rust#87840).
  • Loading branch information
lupont committed Nov 5, 2022
1 parent 84c92a2 commit fc6b55d
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 5 deletions.
1 change: 0 additions & 1 deletion src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ impl Colors {

pub const PROMPT: &str = "$";

// FIXME: the second entry in the tuple cannot currently be shortes than the first
pub const ABBREVIATIONS: [(&str, &str); 3] = [
("gs", "git status"),
("pacs", "sudo pacman -S"),
Expand Down
16 changes: 12 additions & 4 deletions src/repl/input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,8 +150,16 @@ fn read_line<W: Write>(engine: &mut Engine<W>) -> Result<String> {

if let Some((expanded_line, diff)) = expand_abbreviation(&line) {
line = expanded_line;
x += diff as u16;
index += diff;

// FIXME: replace with something like `wrapping_add_signed` once
// https://github.com/rust-lang/rust/issues/87840 is in stable
if diff >= 0 {
x = u16::checked_add(x, diff as u16).unwrap_or(0);
index = usize::checked_add(index, diff as usize).unwrap_or(0);
} else {
x = u16::checked_sub(x, diff.unsigned_abs() as u16).unwrap_or(0);
index = usize::checked_sub(index, diff.unsigned_abs()).unwrap_or(0);
}
}

line.insert(index, ' ');
Expand Down Expand Up @@ -270,11 +278,11 @@ fn read_line<W: Write>(engine: &mut Engine<W>) -> Result<String> {
}
}

fn expand_abbreviation<S: AsRef<str>>(line: S) -> Option<(String, usize)> {
fn expand_abbreviation<S: AsRef<str>>(line: S) -> Option<(String, isize)> {
let line = line.as_ref();
for (a, b) in ABBREVIATIONS {
if line == a || line.starts_with(&format!("{a} ")) {
let diff = b.len() - a.len();
let diff = b.len() as isize - a.len() as isize;
return Some((line.replacen(a, b, 1), diff));
}
}
Expand Down

0 comments on commit fc6b55d

Please sign in to comment.