completion.nu
This file
Path
shell/completion.nu
490 lines · 20.8 KiB
Last changed by
nushell: fix 0.114.0 nushell str downcase deprecated errorSimon Désaulniersbefore adoption24832e9
History of this fileTake it
1# ____ ____2# / __/___ / __/3# / /_/_ / / /_4# / __/ / /_/ __/5# /_/ /___/_/ completion.nu678# An implementation of completion.nu9# This loads FZF as a Nushell External Completer10# https://www.nushell.sh/cookbook/external_completers.html111213# --- Default Environment Variables ---14# These can be overridden in your config.nu or environment.15# Example: $env.FZF_COMPLETION_TRIGGER = "!<TAB>"1617# - $env.FZF_TMUX (default: 0)18# - $env.FZF_TMUX_OPTS (default: empty)19# - $env.FZF_TMUX_HEIGHT (default: 40%)20# - $env.FZF_COMPLETION_TRIGGER (default: '**')21# - $env.FZF_COMPLETION_OPTS (default: empty)22# - $env.FZF_COMPLETION_PATH_OPTS (default: empty)23# - $env.FZF_COMPLETION_DIR_OPTS (default: empty)24252627$env.FZF_COMPLETION_TRIGGER = $env.FZF_COMPLETION_TRIGGER? | default '**'2829# Options for fzf completion in general. e.g. '--border'30$env.FZF_COMPLETION_OPTS = $env.FZF_COMPLETION_OPTS? | default ''3132# Options specific to path completion. e.g. '--extended'33$env.FZF_COMPLETION_PATH_OPTS = $env.FZF_COMPLETION_PATH_OPTS? | default ''34# Options specific to directory completion. e.g. '--extended'35$env.FZF_COMPLETION_DIR_OPTS = $env.FZF_COMPLETION_DIR_OPTS? | default ''3637$env.FZF_COMPLETION_DIR_COMMANDS = $env.FZF_COMPLETION_DIR_COMMANDS? | default ['cd', 'pushd', 'rmdir']3839# --- Helper Functions ---4041# Helper to build default fzf options list42def __fzf_defaults_completion [prepend: string, append: string]: nothing -> string {43 let base = $"--height ($env.FZF_TMUX_HEIGHT? | default '40%') --min-height 20+ --bind=ctrl-z:ignore ($prepend)"44 let opts_file = if ($env.FZF_DEFAULT_OPTS_FILE? | default '' | is-not-empty) {45 try { open --raw ($env.FZF_DEFAULT_OPTS_FILE) | str trim } catch { '' }46 } else {47 ''48 }49 let default_opts = $env.FZF_DEFAULT_OPTS? | default ''50 $"($base) ($opts_file) ($default_opts) ($append)" | str trim51}5253# Wrapper for running fzf or fzf-tmux54def __fzf_comprun [ context_name: string # e.g., "fzf-completion" , "fzf-helper" - mainly for potential debugging55 , query: string # The initial query string for fzf56 , fzf_opts_arg: list<string> # Remaining options for fzf/fzf-tmux57 ] {58 let stdin_content = try {59 # Collect stdin into a single string. Adjust if structured data is expected.60 $in | into string61 } catch {62 null # Set to null if there's no stdin or an error occurs reading it63 }6465 let fzf_default_opts = (__fzf_defaults_completion "" ($env.FZF_COMPLETION_OPTS | default ''))66 let fzf_prefinal_opt = ['--query', $query, '--reverse'] | append $fzf_opts_arg6768 # Get the configured height, defaulting to '40%'69 let height_opt = $env.FZF_TMUX_HEIGHT? | default '40%'7071 # Determine if fzf should generate its own candidates via walker72 let has_walker = ($fzf_prefinal_opt | find '--walker' | is-not-empty)7374 # Check for custom comprun function (Nu equivalent)75 if (which _fzf_comprun | is-not-empty) {76 # Note: Nushell doesn't have a direct equivalent to Zsh/Bash `type -t _fzf_comprun`.77 # This check assumes a user might define a custom command named `_fzf_comprun`.78 _fzf_comprun $context_name $query ...$fzf_prefinal_opt # Pass args correctly to custom function79 } else if ($env.TMUX_PANE? | default '' | into string | is-not-empty) and (($env.FZF_TMUX? | default 0) != 0 or ($env.FZF_TMUX_OPTS? | is-not-empty)) {80 # Running inside tmux, use fzf-tmux81 let final_fzf_opts = if ($env.FZF_TMUX_OPTS? | is-not-empty) {82 $env.FZF_TMUX_OPTS | split row ' ' | append ['--'] | append $fzf_prefinal_opt83 } else {84 # Use the default -d option with the configured height for fzf-tmux85 ['-d', $height_opt, '--'] | append $fzf_prefinal_opt86 }8788 if $has_walker or ($stdin_content == null) {89 with-env { FZF_DEFAULT_OPTS: $fzf_default_opts, FZF_DEFAULT_OPTS_FILE: '' } { fzf-tmux ...$final_fzf_opts }90 } else {91 $stdin_content | with-env { FZF_DEFAULT_OPTS: $fzf_default_opts, FZF_DEFAULT_OPTS_FILE: '' } { fzf-tmux ...$final_fzf_opts }92 }9394 } else {95 # Not in tmux or not configured for fzf-tmux, use fzf directly96 let final_fzf_opts = $fzf_prefinal_opt9798 if $has_walker or ($stdin_content == null) {99 with-env { FZF_DEFAULT_OPTS: $fzf_default_opts, FZF_DEFAULT_OPTS_FILE: '' } { fzf ...$final_fzf_opts }100 } else {101 $stdin_content | with-env { FZF_DEFAULT_OPTS: $fzf_default_opts, FZF_DEFAULT_OPTS_FILE: '' } { fzf ...$final_fzf_opts }102 }103 }104}105106# Generate host list for ssh/telnet107def __fzf_list_hosts [] {108 # Translate the Zsh pipeline using Nu commands and external tools109 let ssh_configs = try { open ~/.ssh/config | lines } catch { [] }110 let ssh_configs_d = try { open ~/.ssh/config.d/* | lines } catch { [] }111 let ssh_config_global = try { open /etc/ssh/ssh_config | lines } catch { [] }112 let known_hosts = try { open ~/.ssh/known_hosts | lines } catch { [] }113 let hosts_file = try { open /etc/hosts | lines } catch { [] }114115 [116 (117 # Process ssh config files118 $ssh_configs | append $ssh_configs_d | append $ssh_config_global119 # NOTE: str lowercase is new from Nushell 0.114.0. Please upgrade to Nushell >=0.114.0 if you are seeing `extra positional argument` error regarding `str lowercase` in this block.120 | where {|it| ($it | str lowercase | str starts-with 'host') or ($it | str lowercase | str starts-with 'hostname') }121 | parse --regex '^\s*host(?:name)?\s+(?<hosts>.+)' # Extract hosts after keyword122 | default { hosts: null } # Handle lines that don't match regex123 | get hosts124 | where {|it| $it != null }125 | split row ' '126 | where {|it| not ($it =~ '[*?%]') } # Exclude patterns containing *, ?, or %127 )128 (129 # Process known_hosts file130 $known_hosts | parse --regex '^(?:\[)?(?<hosts>[a-z0-9.,:_-]+)' # Extract hostnames (possibly in [], possibly comma-separated) - added underscore131 | default { hosts: null }132 | get hosts133 | where {|it| $it != null }134 | each { |it| $it | split row ',' } # Split comma-separated hosts if any135 | flatten136 )137 (138 # Process /etc/hosts file139 $hosts_file | where { |it| not ($it | str starts-with '#') } # Ignore comments140 | where { |it| not ($it | str trim | is-empty) } # Ignore empty lines141 | where { |it| not ($it | str contains '0.0.0.0') } # Ignore 0.0.0.0142 | str replace --regex '#.*$' '' # Remove trailing comments143 | parse --regex '^\s*\S+\s+(?<hosts>.+)' # Extract hosts part (after IP)144 | default { hosts: null }145 | get hosts146 | where {|it| $it != null }147 | split row ' ' # Split multiple hosts on the same line148 )149 ]150 | flatten # Combine all lists into a single stream151 | where {|it| not ($it | is-empty) } # Remove empty entries152 | sort | uniq # Sort and remove duplicates153}154155156# Base function for path/directory completion157def __fzf_generic_path_completion [ prefix: string # The text before the trigger158 , fzf_opts_arg: list<string> # Extra options for fzf159 , suffix: string # Suffix to add to selection (e.g. , "/")160 ] {161 # --- Determine walker root and initial query from the prefix ---162163 mut walker_root = "."164 mut initial_query = ""165166 if ($prefix | is-empty) {167 # Case: "**"168 $walker_root = "."169 $initial_query = ""170 } else if ($prefix | str contains (char separator)) {171 # Case: "dir/subdir/partial**" or "dir/**"172 $walker_root = $prefix | path dirname173 $initial_query = $prefix | path basename174 # Handle edge case where prefix ends with separator, e.g., "dir/"175 if ($prefix | str ends-with (char separator)) {176 # Remove trailing separator to get the intended directory177 $walker_root = $prefix | str substring 0..-2178 $initial_query = ""179 }180 # Ensure walker_root isn't empty if prefix was like "/file**"181 # or if path dirname returned empty string for some reason (e.g. prefix="file/")182 if ($walker_root | is-empty) {183 if ($prefix | str starts-with (char separator)) {184 $walker_root = (char separator)185 } else if ($prefix | str ends-with (char separator)) {186 $walker_root = $prefix | str substring 0..-2187 } else { $walker_root = "." } # Fallback if dirname weirdly fails188 }189 } else {190 # Case: "partial**" (no slashes)191 $walker_root = "."192 $initial_query = $prefix193 }194195 # --- Prepare FZF options ---196 let completion_type_opts = if $suffix == '/' {197 $env.FZF_COMPLETION_DIR_OPTS? | default '' | split row ' ' | where {not ($in | is-empty)}198 } else {199 $env.FZF_COMPLETION_PATH_OPTS? | default '' | split row ' ' | where {not ($in | is-empty)}200 }201202 let walker_type = if ($suffix == '/') {203 "dir,follow"204 } else {205 "file,dir,follow,hidden"206 }207 # Expand tilde so fzf receives a valid absolute path as walker-root208 let needs_tilde_rewrite = ($walker_root | str starts-with '~')209 let walker_root_expanded = ($walker_root | path expand)210211 # Use the 'walker_root' calculated at the beginning212 let fzf_all_opts = ["--scheme=path", "--walker", $walker_type, "--walker-root", $walker_root_expanded] | append $fzf_opts_arg213 | append $completion_type_opts214215 # Call FZF run216 let fzf_selection = ( __fzf_comprun "fzf-path-completion-walker" $initial_query $fzf_all_opts ) | str trim217218219 # --- Return Result ---220 if ($fzf_selection | is-not-empty) {221 # Restore tilde prefix if the user originally typed ~/222 let home = $nu.home-dir | path expand223 let result = if $needs_tilde_rewrite {224 $fzf_selection | lines | each {|line| $line | str replace $home '~' } | str join ' '225 } else {226 $fzf_selection | lines | str join ' '227 }228 [$result]229 } else {230 []231 }232}233234# Specific path completion wrapper235def _fzf_path_completion [prefix: string] {236 # Zsh args: base, lbuf, _fzf_compgen_path, "-m", "", " "237 # Nu: prefix, empty command name (use find), ["-m"], "", " "238 __fzf_generic_path_completion $prefix ["-m"] ""239}240241# General completion helper for commands that feed a list to fzf242# This is called by ssh, kill, and user-defined completers.243def _fzf_complete [ query: string # The initial query string for fzf244 , data_gen_closure: closure # Closure that generates candidates245 , fzf_opts_arg: list<string> # Extra options for fzf (like -m, +m)246 , --post_process_closure: closure # Closure to process the selected item (optional)247 ] {248 # Generate candidates using the provided command249 let candidates = try {250 do $data_gen_closure251 } catch {252 # Capture the actual error object provided by the catch block253 let actual_error = $in254 # Print a more informative error message including the actual error details255 print -e $"Error executing data_gen closure. Closure code: ($data_gen_closure). Actual error: ($actual_error)"256 []257 }258259 # Run fzf and get selection260 let fzf_selection = $candidates | to text261 | __fzf_comprun "fzf-helper" $query $fzf_opts_arg262 | str trim # Trim potential trailing newline from fzf263264 # Apply post-processing if closure provided and selection is not empty265 let processed_selection = if ($fzf_selection | is-not-empty) and ($post_process_closure | is-not-empty) {266 # Call the post-processing closure with the selection267 try {268 do $post_process_closure $fzf_selection269 } catch {270 print -e $"Error executing post_process closure: ($post_process_closure)"271 $fzf_selection # Return original selection on error272 }273 } else {274 $fzf_selection275 }276277 if not ($processed_selection | is-empty) {278 [($processed_selection | lines | str join ' ')]279 } else {280 []281 }282}283284# SSH/Telnet completion285def _fzf_complete_ssh [ prefix: string286 , input_line_before_trigger: string287 ] {288 let words = ($input_line_before_trigger | split row ' ')289 let word_count = $words | length290291 # Find the index of the word being completed (which is the prefix)292 # If prefix is empty, completion happens after a space, index is word_count293 # If prefix is not empty, it's the last word, index is word_count - 1294 let completion_index = if ($prefix | is-empty) { $word_count } else { $word_count - 1 }295296 mut handled = false297 mut completion_result = [] # List of completion strings to return298299 # Check for -i, -F, -E flags immediately preceding the cursor position300 if $completion_index > 0 {301 let prev_arg = ($words | get ($completion_index - 1))302 if ($prev_arg in ['-i', '-F', '-E']) {303 $handled = true304 # Call path completion with the current prefix305 $completion_result = (_fzf_path_completion $prefix)306 }307 }308309 # If not handled by path completion, do host completion310 if not $handled {311 let user_part = if ($prefix | str contains "@") { ($prefix | split row "@" | first) + "@" } else { "" }312 # The part after '@' (or the whole prefix if no '@') is the initial query for fzf313 let query = if ($prefix | str contains "@") { $prefix | split row "@" | last } else { $prefix }314315 let host_candidates_gen = {||316 __fzf_list_hosts317 | each {|host_item| $user_part + $host_item } # Prepend user@ if present in prefix318 }319320 # Zsh options: +m -- ; Nu: pass ["+m"]321 # Pass the host part of the prefix to _fzf_complete for the initial query322 let selected_host = (_fzf_complete $query $host_candidates_gen ["+m"]) # Pass host_prefix here323 if not ($selected_host | is-empty) {324 $completion_result = $selected_host # _fzf_complete returns a list325 }326 }327328 $completion_result329}330331# Kill completion post-processor (extracts PID)332def _fzf_complete_kill_post_get_pid [selected_line: string] {333 # Assuming standard ps output where PID is the second column334 $selected_line | lines | each { $in | from ssv --noheaders | get 0.column1 } | to text335}336337# Kill completion to get process PID338def _fzf_complete_kill [query: string] {339 let ps_gen_closure = {|| # Define ps generator as a closure340 # Try standard ps, then busybox, then cygwin format approximation341 # Use `^ps` to ensure external command execution342 try {343 ^ps -eo user,pid,ppid,start,time,command | complete | if $in.exit_code == 0 { $in.stdout | lines } else { error make {msg: "ps failed"} }344 } catch {345 try {346 ^ps -eo user,pid,ppid,time,args | complete | if $in.exit_code == 0 { $in.stdout | lines } else { error make {msg: "ps failed"} }347 } catch {348 try {349 ^ps --everyone --full --windows | complete | if $in.exit_code == 0 { $in.stdout | lines } else { error make {msg: "ps failed"} }350 } catch {351 print -e "Error: ps command failed."352 [] # Return empty list on failure353 }354 }355 }356 }357358 # Note: Complex Zsh FZF bindings for kill (click-header transformer) are omitted for simplicity.359 # Users can set custom bindings via FZF_DEFAULT_OPTS if needed.360 let kill_post_closure = {|selected_line| _fzf_complete_kill_post_get_pid $selected_line }361362 let fzf_opts = ["-m", "--header-lines=1", "--no-preview", "--wrap", "--color", "fg:dim,nth:regular"]363364 _fzf_complete $query $ps_gen_closure $fzf_opts --post_process_closure $kill_post_closure365}366367368# --- Main FZF External Completer ---369370# This function is registered with Nushell's external completion system.371# It gets called when Tab is pressed.372let fzf_external_completer = {|spans|373 let trigger: string = $env.FZF_COMPLETION_TRIGGER? | default '**'374375 if ($trigger | is-empty) { return null } # Cannot work with empty trigger376 if (($spans | length ) == 0) { return null } # Nothing to complete377378 let last_span = $spans | last379380 if ($last_span | str ends-with $trigger) {381 # --- Trigger Found ---382383 # Skip sudo to determine the actual command384 let cmd_spans = if ($spans | first) == "sudo" { $spans | skip 1 } else { $spans }385 let cmd_word = ($cmd_spans | first | default "")386387 # Calculate the prefix (part before the trigger in the last span)388 let prefix = $last_span | str substring 0..(-1 * ($trigger | str length) - 1)389390 # Reconstruct the line content *before* the trigger for context391 # This is an approximation based on spans392 let line_without_trigger = $cmd_spans | take (($cmd_spans | length) - 1) | append $prefix | str join ' '393394 # --- Dispatch to Completer ---395 mut completion_results = [] # Will hold the list of strings from the completer396397 # Check for user-defined completer in $env.FZF_COMPLETERS first.398 # Users can define custom completers in their config.nu as a record of closures:399 # $env.FZF_COMPLETERS = { git: {|prefix, spans| ... }, docker: {|prefix, spans| ... } }400 # Each closure receives the prefix (text before the trigger) and the full401 # command spans (e.g. ["pacman", "-S", "vim**"]), and should return either:402 # - a list of candidate strings, or403 # - a record { candidates: [...], opts: [...], post: {|sel| ...} } to pass404 # custom fzf options and/or a post-processing closure.405 # See shell/completion-examples.nu for examples.406 let user_completers = ($env.FZF_COMPLETERS? | default {})407 if ($cmd_word in $user_completers) {408 let user_gen = ($user_completers | get $cmd_word)409 let user_result = (do $user_gen $prefix $cmd_spans)410 if ($user_result | describe | str starts-with 'record') {411 let candidates = ($user_result | get candidates)412 let fzf_opts = ($user_result | get opts? | default ["-m"])413 let post = ($user_result | get post? | default null)414 if ($post != null) {415 $completion_results = (_fzf_complete $prefix {|| $candidates} $fzf_opts --post_process_closure $post)416 } else {417 $completion_results = (_fzf_complete $prefix {|| $candidates} $fzf_opts)418 }419 } else {420 $completion_results = (_fzf_complete $prefix {|| $user_result} ["-m"])421 }422 } else {423 match $cmd_word {424 "ssh" | "scp" | "sftp" | "telnet" => { $completion_results = (_fzf_complete_ssh $prefix $line_without_trigger) }425 "kill" => { $completion_results = (_fzf_complete_kill $prefix) }426 _ if ($cmd_word in $env.FZF_COMPLETION_DIR_COMMANDS) => {427 $completion_results = (__fzf_generic_path_completion $prefix [] "/")428 }429 _ => {430 # Default to path completion if no specific command matches431 $completion_results = (_fzf_path_completion $prefix)432 }433 }434 }435436 # --- Return Results ---437 # The _fzf_... functions return a list of completion strings.438 # Nushell's completer expects the suggestions for the token being completed (prefix + trigger).439 # The results from the helper functions should be the final desired strings.440 # We don't need to manually add spaces; Nushell handles that.441 $completion_results # Return the list directly442 } else {443 # --- Trigger Not Found ---444 # Return null to let Nushell fall back to other completers (e.g., default file completion).445 null446 }447}448449# --- WRAPPER AND REGISTRATION ---450451# Guard against re-sourcing: wrapping the completer multiple times would452# nest wrappers and grow the call chain on every reload.453if ($env.__fzf_completer_registered? | default false) != true {454455 # Get the currently configured external completer, if any exists456 let previous_external_completer = $env.config? | get completions? | get external? | get completer?457458 # Define the new wrapper completer459 let fzf_wrapper_completer = {|spans|460 # 1. Try the FZF completer logic first461 let fzf_result = do $fzf_external_completer $spans462463 # 2. If FZF returned a result (a list, even an empty one), return it.464 # `null` means FZF didn't handle it because the trigger wasn't present.465 if $fzf_result != null {466 $fzf_result467 } else {468 # 3. FZF didn't handle it, so call the previous completer (if it exists).469 if $previous_external_completer != null {470 do $previous_external_completer $spans471 } else {472 # 4. No previous completer, and FZF didn't handle it. Return null.473 null474 }475 }476 }477478 # Register the new wrapper completer479 # This ensures external completions are enabled and sets our wrapper.480 $env.config = $env.config | upsert completions {481 external: {482 enable: true483 completer: $fzf_wrapper_completer484 }485 }486487 $env.__fzf_completer_registered = true488}489490# vim: set sts=2 ts=2 sw=2 tw=120 et :