| 1 |
use std::ffi::OsString; |
| 2 |
use std::str::FromStr; |
| 3 |
|
| 4 |
use super::EnvCompleter; |
| 5 |
|
| 6 |
/// Bash completion adapter |
| 7 |
#[derive(Copy, Clone, PartialEq, Eq, Debug)] |
| 8 |
pub struct Bash; |
| 9 |
|
| 10 |
impl EnvCompleter for Bash { |
| 11 |
fn name(&self) -> &'static str { |
| 12 |
"bash" |
| 13 |
} |
| 14 |
fn is(&self, name: &str) -> bool { |
| 15 |
name == "bash" |
| 16 |
} |
| 17 |
fn write_registration( |
| 18 |
&self, |
| 19 |
var: &str, |
| 20 |
name: &str, |
| 21 |
bin: &str, |
| 22 |
completer: &str, |
| 23 |
buf: &mut dyn std::io::Write, |
| 24 |
) -> Result<(), std::io::Error> { |
| 25 |
let escaped_name = name.replace('-', "_"); |
| 26 |
|
| 27 |
let completer = |
| 28 |
shlex::try_quote(completer).unwrap_or(std::borrow::Cow::Borrowed(completer)); |
| 29 |
|
| 30 |
let script = r#" |
| 31 |
_clap_complete_NAME() { |
| 32 |
local IFS=$'\013' |
| 33 |
local _CLAP_COMPLETE_INDEX=${COMP_CWORD} |
| 34 |
local _CLAP_COMPLETE_COMP_TYPE=${COMP_TYPE} |
| 35 |
if compopt +o nospace 2> /dev/null; then |
| 36 |
local _CLAP_COMPLETE_SPACE=false |
| 37 |
else |
| 38 |
local _CLAP_COMPLETE_SPACE=true |
| 39 |
fi |
| 40 |
local words=("${COMP_WORDS[@]}") |
| 41 |
if [[ "${BASH_VERSINFO[0]}" -ge 4 ]]; then |
| 42 |
words[COMP_CWORD]="$2" |
| 43 |
fi |
| 44 |
COMPREPLY=( $( \ |
| 45 |
_CLAP_IFS="$IFS" \ |
| 46 |
_CLAP_COMPLETE_INDEX="$_CLAP_COMPLETE_INDEX" \ |
| 47 |
_CLAP_COMPLETE_COMP_TYPE="$_CLAP_COMPLETE_COMP_TYPE" \ |
| 48 |
_CLAP_COMPLETE_SPACE="$_CLAP_COMPLETE_SPACE" \ |
| 49 |
VAR="bash" \ |
| 50 |
"COMPLETER" -- "${words[@]}" \ |
| 51 |
) ) |
| 52 |
if [[ $? != 0 ]]; then |
| 53 |
unset COMPREPLY |
| 54 |
elif [[ $_CLAP_COMPLETE_SPACE == false ]] && [[ "${COMPREPLY-}" =~ [=/:]$ ]]; then |
| 55 |
compopt -o nospace |
| 56 |
fi |
| 57 |
} |
| 58 |
if [[ "${BASH_VERSINFO[0]}" -eq 4 && "${BASH_VERSINFO[1]}" -ge 4 || "${BASH_VERSINFO[0]}" -gt 4 ]]; then |
| 59 |
complete -o nospace -o bashdefault -o nosort -F _clap_complete_NAME BIN |
| 60 |
else |
| 61 |
complete -o nospace -o bashdefault -F _clap_complete_NAME BIN |
| 62 |
fi |
| 63 |
"# |
| 64 |
.replace("NAME", &escaped_name) |
| 65 |
.replace("BIN", bin) |
| 66 |
.replace("COMPLETER", &completer) |
| 67 |
.replace("VAR", var); |
| 68 |
|
| 69 |
writeln!(buf, "{script}")?; |
| 70 |
Ok(()) |
| 71 |
} |
| 72 |
fn write_complete( |
| 73 |
&self, |
| 74 |
cmd: &mut clap::Command, |
| 75 |
args: Vec<OsString>, |
| 76 |
current_dir: Option<&std::path::Path>, |
| 77 |
buf: &mut dyn std::io::Write, |
| 78 |
) -> Result<(), std::io::Error> { |
| 79 |
let index: usize = std::env::var("_CLAP_COMPLETE_INDEX") |
| 80 |
.ok() |
| 81 |
.and_then(|i| i.parse().ok()) |
| 82 |
.unwrap_or_default(); |
| 83 |
let _comp_type: CompType = std::env::var("_CLAP_COMPLETE_COMP_TYPE") |
| 84 |
.ok() |
| 85 |
.and_then(|i| i.parse().ok()) |
| 86 |
.unwrap_or_default(); |
| 87 |
let _space: Option<bool> = std::env::var("_CLAP_COMPLETE_SPACE") |
| 88 |
.ok() |
| 89 |
.and_then(|i| i.parse().ok()); |
| 90 |
let ifs: Option<String> = std::env::var("_CLAP_IFS").ok().and_then(|i| i.parse().ok()); |
| 91 |
let completions = crate::engine::complete(cmd, args, index, current_dir)?; |
| 92 |
|
| 93 |
for (i, candidate) in completions.iter().enumerate() { |
| 94 |
if i != 0 { |
| 95 |
write!(buf, "{}", ifs.as_deref().unwrap_or("\n"))?; |
| 96 |
} |
| 97 |
write!(buf, "{}", candidate.get_value().to_string_lossy())?; |
| 98 |
} |
| 99 |
Ok(()) |
| 100 |
} |
| 101 |
} |
| 102 |
|
| 103 |
/// Type of completion attempted that caused a completion function to be called |
| 104 |
#[derive(Copy, Clone, Debug, PartialEq, Eq)] |
| 105 |
#[non_exhaustive] |
| 106 |
enum CompType { |
| 107 |
/// Normal completion |
| 108 |
Normal, |
| 109 |
/// List completions after successive tabs |
| 110 |
Successive, |
| 111 |
/// List alternatives on partial word completion |
| 112 |
Alternatives, |
| 113 |
/// List completions if the word is not unmodified |
| 114 |
Unmodified, |
| 115 |
/// Menu completion |
| 116 |
Menu, |
| 117 |
} |
| 118 |
|
| 119 |
impl FromStr for CompType { |
| 120 |
type Err = String; |
| 121 |
|
| 122 |
fn from_str(s: &str) -> Result<Self, Self::Err> { |
| 123 |
match s { |
| 124 |
"9" => Ok(Self::Normal), |
| 125 |
"63" => Ok(Self::Successive), |
| 126 |
"33" => Ok(Self::Alternatives), |
| 127 |
"64" => Ok(Self::Unmodified), |
| 128 |
"37" => Ok(Self::Menu), |
| 129 |
_ => Err(format!("unsupported COMP_TYPE `{s}`")), |
| 130 |
} |
| 131 |
} |
| 132 |
} |
| 133 |
|
| 134 |
impl Default for CompType { |
| 135 |
fn default() -> Self { |
| 136 |
Self::Normal |
| 137 |
} |
| 138 |
} |
| 139 |
|
| 140 |
/// Elvish completion adapter |
| 141 |
#[derive(Copy, Clone, PartialEq, Eq, Debug)] |
| 142 |
pub struct Elvish; |
| 143 |
|
| 144 |
impl EnvCompleter for Elvish { |
| 145 |
fn name(&self) -> &'static str { |
| 146 |
"elvish" |
| 147 |
} |
| 148 |
fn is(&self, name: &str) -> bool { |
| 149 |
name == "elvish" |
| 150 |
} |
| 151 |
fn write_registration( |
| 152 |
&self, |
| 153 |
var: &str, |
| 154 |
_name: &str, |
| 155 |
bin: &str, |
| 156 |
completer: &str, |
| 157 |
buf: &mut dyn std::io::Write, |
| 158 |
) -> Result<(), std::io::Error> { |
| 159 |
let bin = shlex::try_quote(bin).unwrap_or(std::borrow::Cow::Borrowed(bin)); |
| 160 |
let completer = |
| 161 |
shlex::try_quote(completer).unwrap_or(std::borrow::Cow::Borrowed(completer)); |
| 162 |
|
| 163 |
let script = r#" |
| 164 |
set edit:completion:arg-completer[BIN] = { |@words| |
| 165 |
var index = (count $words) |
| 166 |
set index = (- $index 1) |
| 167 |
|
| 168 |
put (env _CLAP_IFS="\n" _CLAP_COMPLETE_INDEX=(to-string $index) VAR="elvish" COMPLETER -- $@words) | to-lines |
| 169 |
} |
| 170 |
"# |
| 171 |
.replace("COMPLETER", &completer) |
| 172 |
.replace("BIN", &bin) |
| 173 |
.replace("VAR", var); |
| 174 |
|
| 175 |
writeln!(buf, "{script}")?; |
| 176 |
Ok(()) |
| 177 |
} |
| 178 |
fn write_complete( |
| 179 |
&self, |
| 180 |
cmd: &mut clap::Command, |
| 181 |
args: Vec<OsString>, |
| 182 |
current_dir: Option<&std::path::Path>, |
| 183 |
buf: &mut dyn std::io::Write, |
| 184 |
) -> Result<(), std::io::Error> { |
| 185 |
let index: usize = std::env::var("_CLAP_COMPLETE_INDEX") |
| 186 |
.ok() |
| 187 |
.and_then(|i| i.parse().ok()) |
| 188 |
.unwrap_or_default(); |
| 189 |
let ifs: Option<String> = std::env::var("_CLAP_IFS").ok().and_then(|i| i.parse().ok()); |
| 190 |
let completions = crate::engine::complete(cmd, args, index, current_dir)?; |
| 191 |
|
| 192 |
for (i, candidate) in completions.iter().enumerate() { |
| 193 |
if i != 0 { |
| 194 |
write!(buf, "{}", ifs.as_deref().unwrap_or("\n"))?; |
| 195 |
} |
| 196 |
write!(buf, "{}", candidate.get_value().to_string_lossy())?; |
| 197 |
} |
| 198 |
Ok(()) |
| 199 |
} |
| 200 |
} |
| 201 |
|
| 202 |
/// Fish completion adapter |
| 203 |
#[derive(Copy, Clone, PartialEq, Eq, Debug)] |
| 204 |
pub struct Fish; |
| 205 |
|
| 206 |
impl EnvCompleter for Fish { |
| 207 |
fn name(&self) -> &'static str { |
| 208 |
"fish" |
| 209 |
} |
| 210 |
fn is(&self, name: &str) -> bool { |
| 211 |
name == "fish" |
| 212 |
} |
| 213 |
fn write_registration( |
| 214 |
&self, |
| 215 |
var: &str, |
| 216 |
_name: &str, |
| 217 |
bin: &str, |
| 218 |
completer: &str, |
| 219 |
buf: &mut dyn std::io::Write, |
| 220 |
) -> Result<(), std::io::Error> { |
| 221 |
let bin = shlex::try_quote(bin).unwrap_or(std::borrow::Cow::Borrowed(bin)); |
| 222 |
let completer = |
| 223 |
shlex::try_quote(completer).unwrap_or(std::borrow::Cow::Borrowed(completer)); |
| 224 |
|
| 225 |
writeln!( |
| 226 |
buf, |
| 227 |
r#"complete --keep-order --exclusive --command {bin} --arguments "({var}=fish {completer} -- (commandline --current-process --tokenize --cut-at-cursor) (commandline --current-token))""# |
| 228 |
) |
| 229 |
} |
| 230 |
fn write_complete( |
| 231 |
&self, |
| 232 |
cmd: &mut clap::Command, |
| 233 |
args: Vec<OsString>, |
| 234 |
current_dir: Option<&std::path::Path>, |
| 235 |
buf: &mut dyn std::io::Write, |
| 236 |
) -> Result<(), std::io::Error> { |
| 237 |
let index = args.len() - 1; |
| 238 |
let completions = crate::engine::complete(cmd, args, index, current_dir)?; |
| 239 |
|
| 240 |
for candidate in completions { |
| 241 |
write!(buf, "{}", candidate.get_value().to_string_lossy())?; |
| 242 |
if let Some(help) = candidate.get_help() { |
| 243 |
write!( |
| 244 |
buf, |
| 245 |
"\t{}", |
| 246 |
help.to_string().lines().next().unwrap_or_default() |
| 247 |
)?; |
| 248 |
} |
| 249 |
writeln!(buf)?; |
| 250 |
} |
| 251 |
Ok(()) |
| 252 |
} |
| 253 |
} |
| 254 |
|
| 255 |
/// Powershell completion adapter |
| 256 |
#[derive(Copy, Clone, PartialEq, Eq, Debug)] |
| 257 |
pub struct Powershell; |
| 258 |
|
| 259 |
impl EnvCompleter for Powershell { |
| 260 |
fn name(&self) -> &'static str { |
| 261 |
"powershell" |
| 262 |
} |
| 263 |
fn is(&self, name: &str) -> bool { |
| 264 |
name == "powershell" || name == "powershell_ise" |
| 265 |
} |
| 266 |
fn write_registration( |
| 267 |
&self, |
| 268 |
var: &str, |
| 269 |
_name: &str, |
| 270 |
bin: &str, |
| 271 |
completer: &str, |
| 272 |
buf: &mut dyn std::io::Write, |
| 273 |
) -> Result<(), std::io::Error> { |
| 274 |
let bin = shlex::try_quote(bin).unwrap_or(std::borrow::Cow::Borrowed(bin)); |
| 275 |
let completer = |
| 276 |
shlex::try_quote(completer).unwrap_or(std::borrow::Cow::Borrowed(completer)); |
| 277 |
|
| 278 |
// `completer` may or may not be surrounded by double quotes, enclosing |
| 279 |
// the expression in a here-string ensures the whole thing is |
| 280 |
// interpreted as the first argument to the call operator |
| 281 |
writeln!( |
| 282 |
buf, |
| 283 |
r#" |
| 284 |
Register-ArgumentCompleter -Native -CommandName {bin} -ScriptBlock {{ |
| 285 |
param($wordToComplete, $commandAst, $cursorPosition) |
| 286 |
|
| 287 |
$prev = $env:{var}; |
| 288 |
$env:{var} = "powershell"; |
| 289 |
|
| 290 |
$args = $commandAst.Extent.Text |
| 291 |
$args = $args.Substring(0, [math]::Min($cursorPosition, $args.Length)); |
| 292 |
if ($wordToComplete -eq "") {{ |
| 293 |
$args += " ''"; |
| 294 |
}} |
| 295 |
|
| 296 |
$results = Invoke-Expression @" |
| 297 |
& {completer} -- $args |
| 298 |
"@; |
| 299 |
if ($null -eq $prev) {{ |
| 300 |
Remove-Item Env:\{var}; |
| 301 |
}} else {{ |
| 302 |
$env:{var} = $prev; |
| 303 |
}} |
| 304 |
$results | ForEach-Object {{ |
| 305 |
$split = $_.Split("`t"); |
| 306 |
$cmd = $split[0]; |
| 307 |
|
| 308 |
if ($split.Length -eq 2) {{ |
| 309 |
$help = $split[1]; |
| 310 |
}} |
| 311 |
else {{ |
| 312 |
$help = $split[0]; |
| 313 |
}} |
| 314 |
|
| 315 |
[System.Management.Automation.CompletionResult]::new($cmd, $cmd, 'ParameterValue', $help) |
| 316 |
}} |
| 317 |
}}; |
| 318 |
"# |
| 319 |
) |
| 320 |
} |
| 321 |
|
| 322 |
fn write_complete( |
| 323 |
&self, |
| 324 |
cmd: &mut clap::Command, |
| 325 |
args: Vec<OsString>, |
| 326 |
current_dir: Option<&std::path::Path>, |
| 327 |
buf: &mut dyn std::io::Write, |
| 328 |
) -> Result<(), std::io::Error> { |
| 329 |
let index = args.len() - 1; |
| 330 |
let completions = crate::engine::complete(cmd, args, index, current_dir)?; |
| 331 |
|
| 332 |
for candidate in completions { |
| 333 |
write!(buf, "{}", candidate.get_value().to_string_lossy())?; |
| 334 |
if let Some(help) = candidate.get_help() { |
| 335 |
write!( |
| 336 |
buf, |
| 337 |
"\t{}", |
| 338 |
help.to_string().lines().next().unwrap_or_default() |
| 339 |
)?; |
| 340 |
} |
| 341 |
writeln!(buf)?; |
| 342 |
} |
| 343 |
Ok(()) |
| 344 |
} |
| 345 |
} |
| 346 |
|
| 347 |
/// Zsh completion adapter |
| 348 |
#[derive(Copy, Clone, PartialEq, Eq, Debug)] |
| 349 |
pub struct Zsh; |
| 350 |
|
| 351 |
impl EnvCompleter for Zsh { |
| 352 |
fn name(&self) -> &'static str { |
| 353 |
"zsh" |
| 354 |
} |
| 355 |
fn is(&self, name: &str) -> bool { |
| 356 |
name == "zsh" |
| 357 |
} |
| 358 |
fn write_registration( |
| 359 |
&self, |
| 360 |
var: &str, |
| 361 |
name: &str, |
| 362 |
bin: &str, |
| 363 |
completer: &str, |
| 364 |
buf: &mut dyn std::io::Write, |
| 365 |
) -> Result<(), std::io::Error> { |
| 366 |
let escaped_name = name.replace('-', "_"); |
| 367 |
let bin = shlex::try_quote(bin).unwrap_or(std::borrow::Cow::Borrowed(bin)); |
| 368 |
let completer = |
| 369 |
shlex::try_quote(completer).unwrap_or(std::borrow::Cow::Borrowed(completer)); |
| 370 |
|
| 371 |
let script = r#"#compdef BIN |
| 372 |
function _clap_dynamic_completer_NAME() { |
| 373 |
local _CLAP_COMPLETE_INDEX=$(expr $CURRENT - 1) |
| 374 |
local _CLAP_IFS=$'\n' |
| 375 |
|
| 376 |
local completions=("${(@f)$( \ |
| 377 |
_CLAP_IFS="$_CLAP_IFS" \ |
| 378 |
_CLAP_COMPLETE_INDEX="$_CLAP_COMPLETE_INDEX" \ |
| 379 |
VAR="zsh" \ |
| 380 |
COMPLETER -- "${words[@]}" 2>/dev/null \ |
| 381 |
)}") |
| 382 |
|
| 383 |
if [[ -n $completions ]]; then |
| 384 |
local -a dirs=() |
| 385 |
local -a other=() |
| 386 |
local completion |
| 387 |
for completion in $completions; do |
| 388 |
local value="${completion%%:*}" |
| 389 |
if [[ "$value" == */ ]]; then |
| 390 |
local dir_no_slash="${value%/}" |
| 391 |
if [[ "$completion" == *:* ]]; then |
| 392 |
local desc="${completion#*:}" |
| 393 |
dirs+=("$dir_no_slash:$desc") |
| 394 |
else |
| 395 |
dirs+=("$dir_no_slash") |
| 396 |
fi |
| 397 |
else |
| 398 |
other+=("$completion") |
| 399 |
fi |
| 400 |
done |
| 401 |
[[ -n $dirs ]] && _describe 'values' dirs -S '/' -r '/' |
| 402 |
[[ -n $other ]] && _describe 'values' other |
| 403 |
fi |
| 404 |
} |
| 405 |
|
| 406 |
compdef _clap_dynamic_completer_NAME BIN"# |
| 407 |
.replace("NAME", &escaped_name) |
| 408 |
.replace("COMPLETER", &completer) |
| 409 |
.replace("BIN", &bin) |
| 410 |
.replace("VAR", var); |
| 411 |
|
| 412 |
writeln!(buf, "{script}")?; |
| 413 |
Ok(()) |
| 414 |
} |
| 415 |
fn write_complete( |
| 416 |
&self, |
| 417 |
cmd: &mut clap::Command, |
| 418 |
args: Vec<OsString>, |
| 419 |
current_dir: Option<&std::path::Path>, |
| 420 |
buf: &mut dyn std::io::Write, |
| 421 |
) -> Result<(), std::io::Error> { |
| 422 |
let index: usize = std::env::var("_CLAP_COMPLETE_INDEX") |
| 423 |
.ok() |
| 424 |
.and_then(|i| i.parse().ok()) |
| 425 |
.unwrap_or_default(); |
| 426 |
let ifs: Option<String> = std::env::var("_CLAP_IFS").ok().and_then(|i| i.parse().ok()); |
| 427 |
|
| 428 |
// If the current word is empty, add an empty string to the args |
| 429 |
let mut args = args.clone(); |
| 430 |
if args.len() == index { |
| 431 |
args.push("".into()); |
| 432 |
} |
| 433 |
let completions = crate::engine::complete(cmd, args, index, current_dir)?; |
| 434 |
|
| 435 |
for (i, candidate) in completions.iter().enumerate() { |
| 436 |
if i != 0 { |
| 437 |
write!(buf, "{}", ifs.as_deref().unwrap_or("\n"))?; |
| 438 |
} |
| 439 |
write!( |
| 440 |
buf, |
| 441 |
"{}", |
| 442 |
Self::escape_value(&candidate.get_value().to_string_lossy()) |
| 443 |
)?; |
| 444 |
if let Some(help) = candidate.get_help() { |
| 445 |
write!( |
| 446 |
buf, |
| 447 |
":{}", |
| 448 |
Self::escape_help(help.to_string().lines().next().unwrap_or_default()) |
| 449 |
)?; |
| 450 |
} |
| 451 |
} |
| 452 |
Ok(()) |
| 453 |
} |
| 454 |
} |
| 455 |
|
| 456 |
impl Zsh { |
| 457 |
/// Escape value string |
| 458 |
fn escape_value(string: &str) -> String { |
| 459 |
string.replace('\\', "\\\\").replace(':', "\\:") |
| 460 |
} |
| 461 |
|
| 462 |
/// Escape help string |
| 463 |
fn escape_help(string: &str) -> String { |
| 464 |
string.replace('\\', "\\\\") |
| 465 |
} |
| 466 |
} |
| 467 |
|
| 468 |
#[cfg(test)] |
| 469 |
mod tests { |
| 470 |
use super::*; |
| 471 |
use snapbox::assert_data_eq; |
| 472 |
|
| 473 |
// This test verifies that fish shell path quoting works with or without spaces in the path. |
| 474 |
#[test] |
| 475 |
#[cfg(all(unix, feature = "unstable-dynamic"))] |
| 476 |
#[cfg(feature = "unstable-shell-tests")] |
| 477 |
fn fish_env_completer_path_quoting_works() { |
| 478 |
// Returns the dynamic registration line for the fish shell, for example: |
| 479 |
// complete --keep-order --exclusive --command my-bin --arguments "(COMPLETE=fish /path/to/my-bin ... )" |
| 480 |
let get_fish_registration = |completer_bin: &str| { |
| 481 |
let mut buf = Vec::new(); |
| 482 |
let fish = Fish; |
| 483 |
fish.write_registration( |
| 484 |
"IGNORED_VAR", |
| 485 |
"ignored-name", |
| 486 |
"/ignored/bin", |
| 487 |
completer_bin, |
| 488 |
&mut buf, |
| 489 |
) |
| 490 |
.expect("write_registration failed"); |
| 491 |
return String::from_utf8(buf).expect("Invalid UTF-8"); |
| 492 |
}; |
| 493 |
|
| 494 |
let script = get_fish_registration("completer"); |
| 495 |
assert_data_eq!( |
| 496 |
script.trim(), |
| 497 |
snapbox::str![r#"complete [..] "([..] completer [..])""#] |
| 498 |
); |
| 499 |
|
| 500 |
let script = get_fish_registration("/path/completer"); |
| 501 |
assert_data_eq!( |
| 502 |
script.trim(), |
| 503 |
snapbox::str![r#"complete [..] "([..] /path/completer [..])""#] |
| 504 |
); |
| 505 |
|
| 506 |
let script = get_fish_registration("/path with a space/completer"); |
| 507 |
assert_data_eq!( |
| 508 |
script.trim(), |
| 509 |
snapbox::str![r#"complete [..] "([..] '/path with a space/completer' [..])""#] |
| 510 |
); |
| 511 |
} |
| 512 |
} |