From fc6b55debe0c949151960a182fdd87054b3e74be Mon Sep 17 00:00:00 2001 From: Pontus Laos Date: Sat, 5 Nov 2022 20:01:21 +0100 Subject: [PATCH] feat: Allow abbreviating longer terms into shorter 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: https://github.com/rust-lang/rust/issues/87840). --- src/config.rs | 1 - src/repl/input.rs | 16 ++++++++++++---- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/src/config.rs b/src/config.rs index d0d7d35..b2153ec 100644 --- a/src/config.rs +++ b/src/config.rs @@ -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"), diff --git a/src/repl/input.rs b/src/repl/input.rs index b9378d8..46930d2 100644 --- a/src/repl/input.rs +++ b/src/repl/input.rs @@ -150,8 +150,16 @@ fn read_line(engine: &mut Engine) -> Result { 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, ' '); @@ -270,11 +278,11 @@ fn read_line(engine: &mut Engine) -> Result { } } -fn expand_abbreviation>(line: S) -> Option<(String, usize)> { +fn expand_abbreviation>(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)); } }