Debian Codegraph @

shell/completion.nu

raw
1 # ____ ____
2 # / __/___ / __/
3 # / /_/_ / / /_
4 # / __/ / /_/ __/
5 # /_/ /___/_/ completion.nu
6
7
8 # An implementation of completion.nu
9 # This loads FZF as a Nushell External Completer
10 # https://www.nushell.sh/cookbook/external_completers.html
11
12
13 # --- Default Environment Variables ---
14 # These can be overridden in your config.nu or environment.
15 # Example: $env.FZF_COMPLETION_TRIGGER = "!<TAB>"
16
17 # - $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)
24
25
26
27 $env.FZF_COMPLETION_TRIGGER = $env.FZF_COMPLETION_TRIGGER? | default '**'
28
29 # Options for fzf completion in general. e.g. '--border'
30 $env.FZF_COMPLETION_OPTS = $env.FZF_COMPLETION_OPTS? | default ''
31
32 # 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 ''
36
37 $env.FZF_COMPLETION_DIR_COMMANDS = $env.FZF_COMPLETION_DIR_COMMANDS? | default ['cd', 'pushd', 'rmdir']
38
39 # --- Helper Functions ---
40
41 # Helper to build default fzf options list
42 def __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 trim
51 }
52
53 # Wrapper for running fzf or fzf-tmux
54 def __fzf_comprun [ context_name: string # e.g., "fzf-completion" , "fzf-helper" - mainly for potential debugging
55 , query: string # The initial query string for fzf
56 , fzf_opts_arg: list<string> # Remaining options for fzf/fzf-tmux
57 ] {
58 let stdin_content = try {
59 # Collect stdin into a single string. Adjust if structured data is expected.
60 $in | into string
61 } catch {
62 null # Set to null if there's no stdin or an error occurs reading it
63 }
64
65 let fzf_default_opts = (__fzf_defaults_completion "" ($env.FZF_COMPLETION_OPTS | default ''))
66 let fzf_prefinal_opt = ['--query', $query, '--reverse'] | append $fzf_opts_arg
67
68 # Get the configured height, defaulting to '40%'
69 let height_opt = $env.FZF_TMUX_HEIGHT? | default '40%'
70
71 # Determine if fzf should generate its own candidates via walker
72 let has_walker = ($fzf_prefinal_opt | find '--walker' | is-not-empty)
73
74 # 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 function
79 } 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-tmux
81 let final_fzf_opts = if ($env.FZF_TMUX_OPTS? | is-not-empty) {
82 $env.FZF_TMUX_OPTS | split row ' ' | append ['--'] | append $fzf_prefinal_opt
83 } else {
84 # Use the default -d option with the configured height for fzf-tmux
85 ['-d', $height_opt, '--'] | append $fzf_prefinal_opt
86 }
87
88 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 }
93
94 } else {
95 # Not in tmux or not configured for fzf-tmux, use fzf directly
96 let final_fzf_opts = $fzf_prefinal_opt
97
98 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 }
105
106 # Generate host list for ssh/telnet
107 def __fzf_list_hosts [] {
108 # Translate the Zsh pipeline using Nu commands and external tools
109 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 { [] }
114
115 [
116 (
117 # Process ssh config files
118 $ssh_configs | append $ssh_configs_d | append $ssh_config_global
119 # 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 keyword
122 | default { hosts: null } # Handle lines that don't match regex
123 | get hosts
124 | where {|it| $it != null }
125 | split row ' '
126 | where {|it| not ($it =~ '[*?%]') } # Exclude patterns containing *, ?, or %
127 )
128 (
129 # Process known_hosts file
130 $known_hosts | parse --regex '^(?:\[)?(?<hosts>[a-z0-9.,:_-]+)' # Extract hostnames (possibly in [], possibly comma-separated) - added underscore
131 | default { hosts: null }
132 | get hosts
133 | where {|it| $it != null }
134 | each { |it| $it | split row ',' } # Split comma-separated hosts if any
135 | flatten
136 )
137 (
138 # Process /etc/hosts file
139 $hosts_file | where { |it| not ($it | str starts-with '#') } # Ignore comments
140 | where { |it| not ($it | str trim | is-empty) } # Ignore empty lines
141 | where { |it| not ($it | str contains '0.0.0.0') } # Ignore 0.0.0.0
142 | str replace --regex '#.*$' '' # Remove trailing comments
143 | parse --regex '^\s*\S+\s+(?<hosts>.+)' # Extract hosts part (after IP)
144 | default { hosts: null }
145 | get hosts
146 | where {|it| $it != null }
147 | split row ' ' # Split multiple hosts on the same line
148 )
149 ]
150 | flatten # Combine all lists into a single stream
151 | where {|it| not ($it | is-empty) } # Remove empty entries
152 | sort | uniq # Sort and remove duplicates
153 }
154
155
156 # Base function for path/directory completion
157 def __fzf_generic_path_completion [ prefix: string # The text before the trigger
158 , fzf_opts_arg: list<string> # Extra options for fzf
159 , suffix: string # Suffix to add to selection (e.g. , "/")
160 ] {
161 # --- Determine walker root and initial query from the prefix ---
162
163 mut walker_root = "."
164 mut initial_query = ""
165
166 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 dirname
173 $initial_query = $prefix | path basename
174 # 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 directory
177 $walker_root = $prefix | str substring 0..-2
178 $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..-2
187 } else { $walker_root = "." } # Fallback if dirname weirdly fails
188 }
189 } else {
190 # Case: "partial**" (no slashes)
191 $walker_root = "."
192 $initial_query = $prefix
193 }
194
195 # --- 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 }
201
202 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-root
208 let needs_tilde_rewrite = ($walker_root | str starts-with '~')
209 let walker_root_expanded = ($walker_root | path expand)
210
211 # Use the 'walker_root' calculated at the beginning
212 let fzf_all_opts = ["--scheme=path", "--walker", $walker_type, "--walker-root", $walker_root_expanded] | append $fzf_opts_arg
213 | append $completion_type_opts
214
215 # Call FZF run
216 let fzf_selection = ( __fzf_comprun "fzf-path-completion-walker" $initial_query $fzf_all_opts ) | str trim
217
218
219 # --- 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 expand
223 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 }
233
234 # Specific path completion wrapper
235 def _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 }
240
241 # General completion helper for commands that feed a list to fzf
242 # This is called by ssh, kill, and user-defined completers.
243 def _fzf_complete [ query: string # The initial query string for fzf
244 , data_gen_closure: closure # Closure that generates candidates
245 , 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 command
249 let candidates = try {
250 do $data_gen_closure
251 } catch {
252 # Capture the actual error object provided by the catch block
253 let actual_error = $in
254 # Print a more informative error message including the actual error details
255 print -e $"Error executing data_gen closure. Closure code: ($data_gen_closure). Actual error: ($actual_error)"
256 []
257 }
258
259 # Run fzf and get selection
260 let fzf_selection = $candidates | to text
261 | __fzf_comprun "fzf-helper" $query $fzf_opts_arg
262 | str trim # Trim potential trailing newline from fzf
263
264 # Apply post-processing if closure provided and selection is not empty
265 let processed_selection = if ($fzf_selection | is-not-empty) and ($post_process_closure | is-not-empty) {
266 # Call the post-processing closure with the selection
267 try {
268 do $post_process_closure $fzf_selection
269 } catch {
270 print -e $"Error executing post_process closure: ($post_process_closure)"
271 $fzf_selection # Return original selection on error
272 }
273 } else {
274 $fzf_selection
275 }
276
277 if not ($processed_selection | is-empty) {
278 [($processed_selection | lines | str join ' ')]
279 } else {
280 []
281 }
282 }
283
284 # SSH/Telnet completion
285 def _fzf_complete_ssh [ prefix: string
286 , input_line_before_trigger: string
287 ] {
288 let words = ($input_line_before_trigger | split row ' ')
289 let word_count = $words | length
290
291 # 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_count
293 # If prefix is not empty, it's the last word, index is word_count - 1
294 let completion_index = if ($prefix | is-empty) { $word_count } else { $word_count - 1 }
295
296 mut handled = false
297 mut completion_result = [] # List of completion strings to return
298
299 # Check for -i, -F, -E flags immediately preceding the cursor position
300 if $completion_index > 0 {
301 let prev_arg = ($words | get ($completion_index - 1))
302 if ($prev_arg in ['-i', '-F', '-E']) {
303 $handled = true
304 # Call path completion with the current prefix
305 $completion_result = (_fzf_path_completion $prefix)
306 }
307 }
308
309 # If not handled by path completion, do host completion
310 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 fzf
313 let query = if ($prefix | str contains "@") { $prefix | split row "@" | last } else { $prefix }
314
315 let host_candidates_gen = {||
316 __fzf_list_hosts
317 | each {|host_item| $user_part + $host_item } # Prepend user@ if present in prefix
318 }
319
320 # Zsh options: +m -- ; Nu: pass ["+m"]
321 # Pass the host part of the prefix to _fzf_complete for the initial query
322 let selected_host = (_fzf_complete $query $host_candidates_gen ["+m"]) # Pass host_prefix here
323 if not ($selected_host | is-empty) {
324 $completion_result = $selected_host # _fzf_complete returns a list
325 }
326 }
327
328 $completion_result
329 }
330
331 # Kill completion post-processor (extracts PID)
332 def _fzf_complete_kill_post_get_pid [selected_line: string] {
333 # Assuming standard ps output where PID is the second column
334 $selected_line | lines | each { $in | from ssv --noheaders | get 0.column1 } | to text
335 }
336
337 # Kill completion to get process PID
338 def _fzf_complete_kill [query: string] {
339 let ps_gen_closure = {|| # Define ps generator as a closure
340 # Try standard ps, then busybox, then cygwin format approximation
341 # Use `^ps` to ensure external command execution
342 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 failure
353 }
354 }
355 }
356 }
357
358 # 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 }
361
362 let fzf_opts = ["-m", "--header-lines=1", "--no-preview", "--wrap", "--color", "fg:dim,nth:regular"]
363
364 _fzf_complete $query $ps_gen_closure $fzf_opts --post_process_closure $kill_post_closure
365 }
366
367
368 # --- Main FZF External Completer ---
369
370 # This function is registered with Nushell's external completion system.
371 # It gets called when Tab is pressed.
372 let fzf_external_completer = {|spans|
373 let trigger: string = $env.FZF_COMPLETION_TRIGGER? | default '**'
374
375 if ($trigger | is-empty) { return null } # Cannot work with empty trigger
376 if (($spans | length ) == 0) { return null } # Nothing to complete
377
378 let last_span = $spans | last
379
380 if ($last_span | str ends-with $trigger) {
381 # --- Trigger Found ---
382
383 # Skip sudo to determine the actual command
384 let cmd_spans = if ($spans | first) == "sudo" { $spans | skip 1 } else { $spans }
385 let cmd_word = ($cmd_spans | first | default "")
386
387 # Calculate the prefix (part before the trigger in the last span)
388 let prefix = $last_span | str substring 0..(-1 * ($trigger | str length) - 1)
389
390 # Reconstruct the line content *before* the trigger for context
391 # This is an approximation based on spans
392 let line_without_trigger = $cmd_spans | take (($cmd_spans | length) - 1) | append $prefix | str join ' '
393
394 # --- Dispatch to Completer ---
395 mut completion_results = [] # Will hold the list of strings from the completer
396
397 # 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 full
401 # command spans (e.g. ["pacman", "-S", "vim**"]), and should return either:
402 # - a list of candidate strings, or
403 # - a record { candidates: [...], opts: [...], post: {|sel| ...} } to pass
404 # 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 matches
431 $completion_results = (_fzf_path_completion $prefix)
432 }
433 }
434 }
435
436 # --- 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 directly
442 } else {
443 # --- Trigger Not Found ---
444 # Return null to let Nushell fall back to other completers (e.g., default file completion).
445 null
446 }
447 }
448
449 # --- WRAPPER AND REGISTRATION ---
450
451 # Guard against re-sourcing: wrapping the completer multiple times would
452 # nest wrappers and grow the call chain on every reload.
453 if ($env.__fzf_completer_registered? | default false) != true {
454
455 # Get the currently configured external completer, if any exists
456 let previous_external_completer = $env.config? | get completions? | get external? | get completer?
457
458 # Define the new wrapper completer
459 let fzf_wrapper_completer = {|spans|
460 # 1. Try the FZF completer logic first
461 let fzf_result = do $fzf_external_completer $spans
462
463 # 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_result
467 } 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 $spans
471 } else {
472 # 4. No previous completer, and FZF didn't handle it. Return null.
473 null
474 }
475 }
476 }
477
478 # Register the new wrapper completer
479 # This ensures external completions are enabled and sets our wrapper.
480 $env.config = $env.config | upsert completions {
481 external: {
482 enable: true
483 completer: $fzf_wrapper_completer
484 }
485 }
486
487 $env.__fzf_completer_registered = true
488 }
489
490 # vim: set sts=2 ts=2 sw=2 tw=120 et :