Skip to content
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
34 changes: 31 additions & 3 deletions argv/src/complete.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
//! in a real invocation.

use crate::spec::{ArgMeta, CommandMeta, CommandSelector, FlagMeta, Spec, SpecView};
pub use crate::spec::{Candidate, CompleteCtx, Completer};
pub use crate::spec::{Candidate, CandidateKind, CompleteCtx, Completer};
use crate::{Arg, Command, Error, Flag, Parser};
use core::future::Future;
use core::pin::Pin;
Expand Down Expand Up @@ -820,6 +820,14 @@ pub fn render(answer: &Completions<'_>, shell: Shell) -> String {
out.push_str(&one_line(
candidate.display.as_deref().unwrap_or(&candidate.value),
));
out.push('\t');
out.push_str(match candidate.kind {
CandidateKind::Value => "value",
CandidateKind::Command => "command",
CandidateKind::Flag => "flag",
CandidateKind::File => "file",
CandidateKind::Directory => "directory",
});
}
Shell::Fish | Shell::Nu => {
out.push_str(&candidate.value);
Expand Down Expand Up @@ -1512,6 +1520,7 @@ fn subcommands<'a>(meta: &'a CommandMeta<'a>, token: &str) -> Vec<Candidate<'a>>
if name.starts_with(token) {
out.push(Candidate {
value: (*name).to_string(),
kind: CandidateKind::Command,
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
display: None,
description: deprecated_description(
sub.about,
Expand Down Expand Up @@ -1550,6 +1559,7 @@ fn long_flags<'a>(spec: &'a Spec<'a>, position: &Position<'_>, token: &str) -> V
if value.starts_with(token) {
out.push(Candidate {
value,
kind: CandidateKind::Flag,
display: None,
description: description.clone(),
});
Expand All @@ -1565,6 +1575,7 @@ fn long_flags<'a>(spec: &'a Spec<'a>, position: &Position<'_>, token: &str) -> V
if value.starts_with(token) {
out.push(Candidate {
value,
kind: CandidateKind::Flag,
display: None,
description: description.clone(),
});
Expand Down Expand Up @@ -1598,6 +1609,7 @@ fn short_flags<'a>(spec: &'a Spec<'a>, position: &Position<'_>, token: &str) ->
if asked_about {
out.push(Candidate {
value: format!("-{}", short as char),
kind: CandidateKind::Flag,
display: None,
description: meta.and_then(|m| {
deprecated_description(
Expand Down Expand Up @@ -1656,6 +1668,7 @@ fn positional<'a>(
if token.is_empty() {
return vec![Candidate {
value: "--".to_string(),
kind: CandidateKind::Value,
display: None,
description: None,
}];
Expand Down Expand Up @@ -1733,6 +1746,7 @@ fn choices<'a>(
.filter(|c| c.starts_with(token))
.map(|c| Candidate {
value: (*c).to_string(),
kind: CandidateKind::Value,
display: None,
description: details
.iter()
Expand Down Expand Up @@ -3670,7 +3684,7 @@ mod tests {
// PowerShell also receives its separately selectable display text.
assert_eq!(
render(&answer, Shell::PowerShell),
"plugins\tManage plugins\tplugins\n"
"plugins\tManage plugins\tplugins\tcommand\n"
);

// zsh takes a third field: what to type, which is not always what is shown.
Expand All @@ -3691,14 +3705,28 @@ mod tests {
assert_eq!(render(&answer, Shell::Fish), "iad\tUS East\n");
assert_eq!(
render(&answer, Shell::PowerShell),
"iad\tUS East\tIAD · Virginia\n"
"iad\tUS East\tIAD · Virginia\tvalue\n"
);
assert_eq!(
render(&answer, Shell::Zsh),
"IAD · Virginia\tUS East\tiad\n"
);
}

#[test]
fn powershell_receives_native_candidate_kinds() {
let answer = Completions {
candidates: vec![Candidate::new("deploy").with_kind(CandidateKind::Command)],
files: None,
};
assert_eq!(
render(&answer, Shell::PowerShell),
"deploy\t\tdeploy\tcommand\n"
);
// Shells without a typed candidate API lose only the metadata.
assert_eq!(render(&answer, Shell::Fish), "deploy\n");
}

#[test]
fn a_candidate_a_shell_could_not_read_is_quoted_for_zsh() {
static ODD: Command = Command {
Expand Down
13 changes: 11 additions & 2 deletions argv/src/script.rs
Original file line number Diff line number Diff line change
Expand Up @@ -476,13 +476,22 @@ Register-ArgumentCompleter -Native -CommandName '{name}' -ScriptBlock {{
$extensions = @($entry -split "`t" | Select-Object -Skip 1 | ForEach-Object {{ $_.TrimStart('.') }})
continue
}}
$parts = $entry -split "`t", 3
$parts = $entry -split "`t", 4
$value = $parts[0]
$description = if ($parts.Count -gt 1 -and $parts[1]) {{ $parts[1] }} else {{ $value }}
$display = if ($parts.Count -gt 2 -and $parts[2]) {{ $parts[2] }} else {{ $value }}
$kind = if ($parts.Count -gt 3) {{
switch ($parts[3]) {{
'command' {{ 'Command' }}
'flag' {{ 'ParameterName' }}
'file' {{ 'ProviderItem' }}
'directory' {{ 'ProviderContainer' }}
default {{ 'ParameterValue' }}
}}
}} else {{ 'ParameterValue' }}
$results.Add(
[System.Management.Automation.CompletionResult]::new(
$value, $display, 'ParameterValue', $description
$value, $display, $kind, $description
)
)
}}
Expand Down
24 changes: 24 additions & 0 deletions argv/src/spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -254,13 +254,29 @@ impl<'a> CompleteCtx<'a> {
/// capture anything.
pub type Completer = fn(&CompleteCtx<'_>) -> Vec<Candidate<'static>>;

/// The semantic role of one completion candidate.
///
/// PowerShell presents these with its native result types. Other shells currently preserve the
/// value and description while ignoring the kind.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord)]
#[non_exhaustive]
pub enum CandidateKind {
#[default]
Value,
Command,
Flag,
File,
Directory,
}

/// Something a shell could offer at the cursor.
///
/// `value` is what the shell inserts. `display` may replace it in shells whose completion API
/// separates presentation from insertion, and `description` is the help shown beside it.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Candidate<'a> {
pub value: String,
pub kind: CandidateKind,
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
/// A presentation-only label. Zsh and PowerShell support this distinction; other shells
/// display [`Self::value`] because their native candidate format couples the two.
pub display: Option<::std::borrow::Cow<'a, str>>,
Expand All @@ -273,6 +289,7 @@ impl Candidate<'_> {
pub fn new(value: impl Into<String>) -> Self {
Self {
value: value.into(),
kind: CandidateKind::Value,
display: None,
description: None,
}
Expand All @@ -282,6 +299,7 @@ impl Candidate<'_> {
pub fn described(value: impl Into<String>, description: impl Into<String>) -> Self {
Self {
value: value.into(),
kind: CandidateKind::Value,
display: None,
description: Some(::std::borrow::Cow::Owned(description.into())),
}
Expand All @@ -292,6 +310,12 @@ impl Candidate<'_> {
self.display = Some(::std::borrow::Cow::Owned(display.into()));
self
}

/// Classify the candidate for shells that present semantic result types.
pub fn with_kind(mut self, kind: CandidateKind) -> Self {
self.kind = kind;
self
}
}

/// A whole CLI: the root command plus what describes the program itself.
Expand Down
3 changes: 3 additions & 0 deletions docs/rust/completions.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,9 @@ with `Candidate::new(value)` or `Candidate::described(value, description)`; shel
descriptions show them, shells that don't get the value alone. Chain `.displayed(label)` when a
short insertion needs a more explanatory presentation; zsh and PowerShell keep that label
separate from the text inserted into the command line, while other shells display the value.
Chain `.with_kind(CandidateKind::Command)` (or `Flag`, `File`, or `Directory`) when a runtime
candidate has a more specific role. PowerShell maps it to the corresponding native completion
result type; shells without typed candidates keep the same value and description.

## Tracing an answer

Expand Down