From 47d5501f9f1194e04b6768b695e339b69cf79db7 Mon Sep 17 00:00:00 2001 From: Genna Wingert Date: Thu, 3 Mar 2022 21:07:13 +0100 Subject: [PATCH] Add aliases to command completions (#4708) --- crates/nu-cli/src/completions.rs | 21 +++++++++++++++--- crates/nu-protocol/src/engine/engine_state.rs | 22 +++++++++++++++++++ 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/crates/nu-cli/src/completions.rs b/crates/nu-cli/src/completions.rs index 47816b6dfb..0a93d151f8 100644 --- a/crates/nu-cli/src/completions.rs +++ b/crates/nu-cli/src/completions.rs @@ -141,7 +141,7 @@ impl NuCompleter { ) -> Vec<(reedline::Span, String)> { let prefix = working_set.get_span_contents(span); - let mut results = working_set + let results = working_set .find_commands_by_prefix(prefix) .into_iter() .map(move |x| { @@ -152,8 +152,23 @@ impl NuCompleter { }, String::from_utf8_lossy(&x).to_string(), ) - }) - .collect::>(); + }); + + let results_aliases = + working_set + .find_aliases_by_prefix(prefix) + .into_iter() + .map(move |x| { + ( + reedline::Span { + start: span.start - offset, + end: span.end - offset, + }, + String::from_utf8_lossy(&x).to_string(), + ) + }); + + let mut results = results.chain(results_aliases).collect::>(); let prefix = working_set.get_span_contents(span); let prefix = String::from_utf8_lossy(prefix).to_string(); diff --git a/crates/nu-protocol/src/engine/engine_state.rs b/crates/nu-protocol/src/engine/engine_state.rs index 581764b63a..ddd2e5bde7 100644 --- a/crates/nu-protocol/src/engine/engine_state.rs +++ b/crates/nu-protocol/src/engine/engine_state.rs @@ -462,6 +462,16 @@ impl EngineState { output } + pub fn find_aliases_by_prefix(&self, name: &[u8]) -> Vec> { + self.scope + .iter() + .rev() + .flat_map(|scope| &scope.aliases) + .filter(|decl| decl.0.starts_with(name)) + .map(|decl| decl.0.clone()) + .collect() + } + pub fn get_span_contents(&self, span: &Span) -> &[u8] { for (contents, start, finish) in &self.file_contents { if span.start >= *start && span.end <= *finish { @@ -1248,6 +1258,18 @@ impl<'a> StateWorkingSet<'a> { output } + pub fn find_aliases_by_prefix(&self, name: &[u8]) -> Vec> { + self.delta + .scope + .iter() + .rev() + .flat_map(|scope| &scope.aliases) + .filter(|decl| decl.0.starts_with(name)) + .map(|decl| decl.0.clone()) + .chain(self.permanent_state.find_aliases_by_prefix(name)) + .collect() + } + pub fn get_block(&self, block_id: BlockId) -> &Block { let num_permanent_blocks = self.permanent_state.num_blocks(); if block_id < num_permanent_blocks {