shell: nushell integration scripts (#4630)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Simon Désaulniers · committed by GitHub · parent ccedd06 · Browse files · 13 files·+1040 added−16 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: imsys <911254+imsys@users.noreply.github.com>
- Co-authored-by: Grzegorz Zalewski (Greg) <12560152+zalewskigrzegorz@users.noreply.github.com>
- Co-authored-by: René Jochum <rene@jochum.dev>
- Co-authored-by: Junegunn Choi <junegunn.c@gmail.com>
- Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Diff stats
13 files+1040 added−16 removed
- tests:+186 added−8 removed
- other:+854 added−8 removed
Provenance
- Commit
290b18d- Tree
7550bb4- Author
Simon Désaulniers <sim.desaulniers@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
ccedd06
13 files changed+1040 added−16 removed
modified:.github/workflows/linux.yml+6 added-1 removed
31 unmodified lines32333435363637383940414243444513 unmodified lines31 unmodified lines with: ruby-version: 3.4.6
- name: Install packages run: sudo apt-get install --yes zsh fish tmux shfmt run: | sudo install -d -m 0755 /etc/apt/keyrings wget -qO- https://apt.fury.io/nushell/gpg.key | sudo gpg --dearmor -o /etc/apt/keyrings/fury-nushell.gpg echo "deb [signed-by=/etc/apt/keyrings/fury-nushell.gpg] https://apt.fury.io/nushell/ /" | sudo tee /etc/apt/sources.list.d/fury-nushell.list sudo apt-get update sudo apt-get install --yes zsh fish tmux shfmt nushell
- name: Install Ruby gems run: bundle install
13 unmodified linesmodified:man/man1/fzf.1+6 added
1371 unmodified lines1372 Print script to set up Fish shell integration1373 1374 e.g. \fBfzf \-\-fish | source\fR1375 1376+.TP1377+.B "\-\-nushell"1378+Print script to set up Nushell shell integration1379+1380+e.g. \fBfzf \-\-nushell | save \-f ~/.config/nushell/autoload/_fzf_integration.nu\fR1381+1382 .SS OTHERS1383 .TP1384 .B "\-\-no\-mouse"1385 Disable mouse948 unmodified linesadded:shell/completion-examples.nu+91 added
1+# ____ ____2+# / __/___ / __/3+# / /_/_ / / /_4+# / __/ / /_/ __/5+# /_/ /___/_/ completion-examples.nu6+#7+# Example custom completers for fzf's Nushell integration.8+#9+# To use these, add the desired entries to $env.FZF_COMPLETERS in your10+# config.nu. Each closure receives two arguments:11+# - prefix: the text before the trigger (e.g. "vim" in "vim **<TAB>")12+# - spans: the full command as a list of words (e.g. ["pacman", "-S", "vim**"])13+#14+# A closure can return either:15+# - a list of candidate strings (fzf will use default options), or16+# - a record with the following optional fields:17+# candidates: list<string> # candidates to feed to fzf18+# opts: list<string> # custom fzf options (default: ["-m"])19+# post: closure (|sel| ...) # post-processing of the selected item20+#21+# Simple example:22+# $env.FZF_COMPLETERS = {23+# git: {|prefix, spans| ["branch-main", "branch-dev", "branch-feature"]}24+# }25+26+# --- pacman / paru ---27+# Completes package names for pacman and paru.28+# Uses the spans to distinguish between subcommands:29+# -S (sync), -F (files): list available packages from repos30+# -Q (query), -R (remove): list installed packages31+# Returns a record with custom fzf options for package preview.32+33+$env.FZF_COMPLETERS = {}34+35+$env.FZF_COMPLETERS.pacman = {|prefix, spans|36+ let sub = $spans | skip 1 | first37+ let candidates = (if ($sub =~ "-[SF]") {38+ ^pacman -Slq | lines39+ } else if ($sub =~ "-[QR]") {40+ ^pacman -Qq | lines41+ } else {42+ []43+ })44+ {45+ candidates: $candidates46+ opts: ["-m", "--preview", "pacman -Si {}", "--prompt", "Package > "]47+ }48+}49+50+$env.FZF_COMPLETERS.paru = {|prefix, spans|51+ let sub = $spans | skip 1 | first52+ let candidates = (if ($sub =~ "-[SF]") {53+ ^pacman -Slq | lines54+ } else if ($sub =~ "-[QR]") {55+ ^pacman -Qq | lines56+ } else {57+ []58+ })59+ {60+ candidates: $candidates61+ opts: ["-m", "--preview", "pacman -Si {}", "--prompt", "Package > "]62+ }63+}64+65+# --- pass (password-store) ---66+# Completes entry names from ~/.password-store.67+# Returns a simple list (no custom fzf options needed).68+69+$env.FZF_COMPLETERS.pass = {|prefix, spans|70+ try {71+ ls ~/.password-store/**/*.gpg72+ | get name73+ | each {$in | str replace -r '^.*?\.password-store/(.*).gpg' '${1}'}74+ } catch {75+ []76+ }77+}78+79+# --- Example with post-processing hook ---80+# The "post" closure transforms the selected line after fzf returns.81+# This is useful when the displayed line contains more information than82+# what you want inserted on the command line (e.g. extracting a PID from83+# a full "ps" output line).84+#85+# $env.FZF_COMPLETERS.mycommand = {|prefix, spans|86+# {87+# candidates: (^some-command | lines)88+# opts: ["+m", "--header-lines=1"]89+# post: {|selection| $selection | split row ' ' | get 0}90+# }91+# }added:shell/completion.nu+489 added
1+# ____ ____2+# / __/___ / __/3+# / /_/_ / / /_4+# / __/ / /_/ __/5+# /_/ /___/_/ completion.nu6+7+8+# An implementation of completion.nu9+# This loads FZF as a Nushell External Completer10+# https://www.nushell.sh/cookbook/external_completers.html11+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 list42+def __fzf_defaults [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+}52+53+# Wrapper for running fzf or fzf-tmux54+def __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+ }64+65+ let fzf_default_opts = (__fzf_defaults "" ($env.FZF_COMPLETION_OPTS | default ''))66+ let fzf_prefinal_opt = ['--query', $query, '--reverse'] | append $fzf_opts_arg67+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 walker72+ 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 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+ }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 directly96+ let final_fzf_opts = $fzf_prefinal_opt97+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/telnet107+def __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 { [] }114+115+ [116+ (117+ # Process ssh config files118+ $ssh_configs | append $ssh_configs_d | append $ssh_config_global119+ | where {|it| ($it | str downcase | str starts-with 'host') or ($it | str downcase | str starts-with 'hostname') }120+ | parse --regex '^\s*host(?:name)?\s+(?<hosts>.+)' # Extract hosts after keyword121+ | default { hosts: null } # Handle lines that don't match regex122+ | get hosts123+ | where {|it| $it != null }124+ | split row ' '125+ | where {|it| not ($it =~ '[*?%]') } # Exclude patterns containing *, ?, or %126+ )127+ (128+ # Process known_hosts file129+ $known_hosts | parse --regex '^(?:\[)?(?<hosts>[a-z0-9.,:_-]+)' # Extract hostnames (possibly in [], possibly comma-separated) - added underscore130+ | default { hosts: null }131+ | get hosts132+ | where {|it| $it != null }133+ | each { |it| $it | split row ',' } # Split comma-separated hosts if any134+ | flatten135+ )136+ (137+ # Process /etc/hosts file138+ $hosts_file | where { |it| not ($it | str starts-with '#') } # Ignore comments139+ | where { |it| not ($it | str trim | is-empty) } # Ignore empty lines140+ | where { |it| not ($it | str contains '0.0.0.0') } # Ignore 0.0.0.0141+ | str replace --regex '#.*$' '' # Remove trailing comments142+ | parse --regex '^\s*\S+\s+(?<hosts>.+)' # Extract hosts part (after IP)143+ | default { hosts: null }144+ | get hosts145+ | where {|it| $it != null }146+ | split row ' ' # Split multiple hosts on the same line147+ )148+ ]149+ | flatten # Combine all lists into a single stream150+ | where {|it| not ($it | is-empty) } # Remove empty entries151+ | sort | uniq # Sort and remove duplicates152+}153+154+155+# Base function for path/directory completion156+def __fzf_generic_path_completion [ prefix: string # The text before the trigger157+ , fzf_opts_arg: list<string> # Extra options for fzf158+ , suffix: string # Suffix to add to selection (e.g. , "/")159+ ] {160+ # --- Determine walker root and initial query from the prefix ---161+162+ mut walker_root = "."163+ mut initial_query = ""164+165+ if ($prefix | is-empty) {166+ # Case: "**"167+ $walker_root = "."168+ $initial_query = ""169+ } else if ($prefix | str contains (char separator)) {170+ # Case: "dir/subdir/partial**" or "dir/**"171+ $walker_root = $prefix | path dirname172+ $initial_query = $prefix | path basename173+ # Handle edge case where prefix ends with separator, e.g., "dir/"174+ if ($prefix | str ends-with (char separator)) {175+ # Remove trailing separator to get the intended directory176+ $walker_root = $prefix | str substring 0..-2177+ $initial_query = ""178+ }179+ # Ensure walker_root isn't empty if prefix was like "/file**"180+ # or if path dirname returned empty string for some reason (e.g. prefix="file/")181+ if ($walker_root | is-empty) {182+ if ($prefix | str starts-with (char separator)) {183+ $walker_root = (char separator)184+ } else if ($prefix | str ends-with (char separator)) {185+ $walker_root = $prefix | str substring 0..-2186+ } else { $walker_root = "." } # Fallback if dirname weirdly fails187+ }188+ } else {189+ # Case: "partial**" (no slashes)190+ $walker_root = "."191+ $initial_query = $prefix192+ }193+194+ # --- Prepare FZF options ---195+ let completion_type_opts = if $suffix == '/' {196+ $env.FZF_COMPLETION_DIR_OPTS? | default '' | split row ' ' | where {not ($in | is-empty)}197+ } else {198+ $env.FZF_COMPLETION_PATH_OPTS? | default '' | split row ' ' | where {not ($in | is-empty)}199+ }200+201+ let walker_type = if ($suffix == '/') {202+ "dir,follow"203+ } else {204+ "file,dir,follow,hidden"205+ }206+ # Expand tilde so fzf receives a valid absolute path as walker-root207+ let needs_tilde_rewrite = ($walker_root | str starts-with '~')208+ let walker_root_expanded = ($walker_root | path expand)209+210+ # Use the 'walker_root' calculated at the beginning211+ let fzf_all_opts = ["--scheme=path", "--walker", $walker_type, "--walker-root", $walker_root_expanded] | append $fzf_opts_arg212+ | append $completion_type_opts213+214+ # Call FZF run215+ let fzf_selection = ( __fzf_comprun "fzf-path-completion-walker" $initial_query $fzf_all_opts ) | str trim216+217+218+ # --- Return Result ---219+ if ($fzf_selection | is-not-empty) {220+ # Restore tilde prefix if the user originally typed ~/221+ let home = $nu.home-dir | path expand222+ let result = if $needs_tilde_rewrite {223+ $fzf_selection | lines | each {|line| $line | str replace $home '~' } | str join ' '224+ } else {225+ $fzf_selection | lines | str join ' '226+ }227+ [$result]228+ } else {229+ []230+ }231+}232+233+# Specific path completion wrapper234+def _fzf_path_completion [prefix: string] {235+ # Zsh args: base, lbuf, _fzf_compgen_path, "-m", "", " "236+ # Nu: prefix, empty command name (use find), ["-m"], "", " "237+ __fzf_generic_path_completion $prefix ["-m"] ""238+}239+240+# General completion helper for commands that feed a list to fzf241+# This is called by ssh, kill, and user-defined completers.242+def _fzf_complete [ query: string # The initial query string for fzf243+ , data_gen_closure: closure # Closure that generates candidates244+ , fzf_opts_arg: list<string> # Extra options for fzf (like -m, +m)245+ , --post_process_closure: closure # Closure to process the selected item (optional)246+ ] {247+ # Generate candidates using the provided command248+ let candidates = try {249+ do $data_gen_closure250+ } catch {251+ # Capture the actual error object provided by the catch block252+ let actual_error = $in253+ # Print a more informative error message including the actual error details254+ print -e $"Error executing data_gen closure. Closure code: ($data_gen_closure). Actual error: ($actual_error)"255+ []256+ }257+258+ # Run fzf and get selection259+ let fzf_selection = $candidates | to text260+ | __fzf_comprun "fzf-helper" $query $fzf_opts_arg261+ | str trim # Trim potential trailing newline from fzf262+263+ # Apply post-processing if closure provided and selection is not empty264+ let processed_selection = if ($fzf_selection | is-not-empty) and ($post_process_closure | is-not-empty) {265+ # Call the post-processing closure with the selection266+ try {267+ do $post_process_closure $fzf_selection268+ } catch {269+ print -e $"Error executing post_process closure: ($post_process_closure)"270+ $fzf_selection # Return original selection on error271+ }272+ } else {273+ $fzf_selection274+ }275+276+ if not ($processed_selection | is-empty) {277+ [($processed_selection | lines | str join ' ')]278+ } else {279+ []280+ }281+}282+283+# SSH/Telnet completion284+def _fzf_complete_ssh [ prefix: string285+ , input_line_before_trigger: string286+ ] {287+ let words = ($input_line_before_trigger | split row ' ')288+ let word_count = $words | length289+290+ # Find the index of the word being completed (which is the prefix)291+ # If prefix is empty, completion happens after a space, index is word_count292+ # If prefix is not empty, it's the last word, index is word_count - 1293+ let completion_index = if ($prefix | is-empty) { $word_count } else { $word_count - 1 }294+295+ mut handled = false296+ mut completion_result = [] # List of completion strings to return297+298+ # Check for -i, -F, -E flags immediately preceding the cursor position299+ if $completion_index > 0 {300+ let prev_arg = ($words | get ($completion_index - 1))301+ if ($prev_arg in ['-i', '-F', '-E']) {302+ $handled = true303+ # Call path completion with the current prefix304+ $completion_result = (_fzf_path_completion $prefix)305+ }306+ }307+308+ # If not handled by path completion, do host completion309+ if not $handled {310+ let user_part = if ($prefix | str contains "@") { ($prefix | split row "@" | first) + "@" } else { "" }311+ # The part after '@' (or the whole prefix if no '@') is the initial query for fzf312+ let query = if ($prefix | str contains "@") { $prefix | split row "@" | last } else { $prefix }313+314+ let host_candidates_gen = {||315+ __fzf_list_hosts316+ | each {|host_item| $user_part + $host_item } # Prepend user@ if present in prefix317+ }318+319+ # Zsh options: +m -- ; Nu: pass ["+m"]320+ # Pass the host part of the prefix to _fzf_complete for the initial query321+ let selected_host = (_fzf_complete $query $host_candidates_gen ["+m"]) # Pass host_prefix here322+ if not ($selected_host | is-empty) {323+ $completion_result = $selected_host # _fzf_complete returns a list324+ }325+ }326+327+ $completion_result328+}329+330+# Kill completion post-processor (extracts PID)331+def _fzf_complete_kill_post_get_pid [selected_line: string] {332+ # Assuming standard ps output where PID is the second column333+ $selected_line | lines | each { $in | from ssv --noheaders | get 0.column1 } | to text334+}335+336+# Kill completion to get process PID337+def _fzf_complete_kill [query: string] {338+ let ps_gen_closure = {|| # Define ps generator as a closure339+ # Try standard ps, then busybox, then cygwin format approximation340+ # Use `^ps` to ensure external command execution341+ try {342+ ^ps -eo user,pid,ppid,start,time,command | complete | if $in.exit_code == 0 { $in.stdout | lines } else { error make {msg: "ps failed"} }343+ } catch {344+ try {345+ ^ps -eo user,pid,ppid,time,args | complete | if $in.exit_code == 0 { $in.stdout | lines } else { error make {msg: "ps failed"} }346+ } catch {347+ try {348+ ^ps --everyone --full --windows | complete | if $in.exit_code == 0 { $in.stdout | lines } else { error make {msg: "ps failed"} }349+ } catch {350+ print -e "Error: ps command failed."351+ [] # Return empty list on failure352+ }353+ }354+ }355+ }356+357+ # Note: Complex Zsh FZF bindings for kill (click-header transformer) are omitted for simplicity.358+ # Users can set custom bindings via FZF_DEFAULT_OPTS if needed.359+ let kill_post_closure = {|selected_line| _fzf_complete_kill_post_get_pid $selected_line }360+361+ let fzf_opts = ["-m", "--header-lines=1", "--no-preview", "--wrap", "--color", "fg:dim,nth:regular"]362+363+ _fzf_complete $query $ps_gen_closure $fzf_opts --post_process_closure $kill_post_closure364+}365+366+367+# --- Main FZF External Completer ---368+369+# This function is registered with Nushell's external completion system.370+# It gets called when Tab is pressed.371+let fzf_external_completer = {|spans|372+ let trigger: string = $env.FZF_COMPLETION_TRIGGER? | default '**'373+374+ if ($trigger | is-empty) { return null } # Cannot work with empty trigger375+ if (($spans | length ) == 0) { return null } # Nothing to complete376+377+ let last_span = $spans | last378+379+ if ($last_span | str ends-with $trigger) {380+ # --- Trigger Found ---381+382+ # Skip sudo to determine the actual command383+ let cmd_spans = if ($spans | first) == "sudo" { $spans | skip 1 } else { $spans }384+ let cmd_word = ($cmd_spans | first | default "")385+386+ # Calculate the prefix (part before the trigger in the last span)387+ let prefix = $last_span | str substring 0..(-1 * ($trigger | str length) - 1)388+389+ # Reconstruct the line content *before* the trigger for context390+ # This is an approximation based on spans391+ let line_without_trigger = $cmd_spans | take (($cmd_spans | length) - 1) | append $prefix | str join ' '392+393+ # --- Dispatch to Completer ---394+ mut completion_results = [] # Will hold the list of strings from the completer395+396+ # Check for user-defined completer in $env.FZF_COMPLETERS first.397+ # Users can define custom completers in their config.nu as a record of closures:398+ # $env.FZF_COMPLETERS = { git: {|prefix, spans| ... }, docker: {|prefix, spans| ... } }399+ # Each closure receives the prefix (text before the trigger) and the full400+ # command spans (e.g. ["pacman", "-S", "vim**"]), and should return either:401+ # - a list of candidate strings, or402+ # - a record { candidates: [...], opts: [...], post: {|sel| ...} } to pass403+ # custom fzf options and/or a post-processing closure.404+ # See shell/completion-examples.nu for examples.405+ let user_completers = ($env.FZF_COMPLETERS? | default {})406+ if ($cmd_word in $user_completers) {407+ let user_gen = ($user_completers | get $cmd_word)408+ let user_result = (do $user_gen $prefix $cmd_spans)409+ if ($user_result | describe | str starts-with 'record') {410+ let candidates = ($user_result | get candidates)411+ let fzf_opts = ($user_result | get opts? | default ["-m"])412+ let post = ($user_result | get post? | default null)413+ if ($post != null) {414+ $completion_results = (_fzf_complete $prefix {|| $candidates} $fzf_opts --post_process_closure $post)415+ } else {416+ $completion_results = (_fzf_complete $prefix {|| $candidates} $fzf_opts)417+ }418+ } else {419+ $completion_results = (_fzf_complete $prefix {|| $user_result} ["-m"])420+ }421+ } else {422+ match $cmd_word {423+ "ssh" | "scp" | "sftp" | "telnet" => { $completion_results = (_fzf_complete_ssh $prefix $line_without_trigger) }424+ "kill" => { $completion_results = (_fzf_complete_kill $prefix) }425+ _ if ($cmd_word in $env.FZF_COMPLETION_DIR_COMMANDS) => {426+ $completion_results = (__fzf_generic_path_completion $prefix [] "/")427+ }428+ _ => {429+ # Default to path completion if no specific command matches430+ $completion_results = (_fzf_path_completion $prefix)431+ }432+ }433+ }434+435+ # --- Return Results ---436+ # The _fzf_... functions return a list of completion strings.437+ # Nushell's completer expects the suggestions for the token being completed (prefix + trigger).438+ # The results from the helper functions should be the final desired strings.439+ # We don't need to manually add spaces; Nushell handles that.440+ $completion_results # Return the list directly441+ } else {442+ # --- Trigger Not Found ---443+ # Return null to let Nushell fall back to other completers (e.g., default file completion).444+ null445+ }446+}447+448+# --- WRAPPER AND REGISTRATION ---449+450+# Guard against re-sourcing: wrapping the completer multiple times would451+# nest wrappers and grow the call chain on every reload.452+if ($env.__fzf_completer_registered? | default false) != true {453+454+ # Get the currently configured external completer, if any exists455+ let previous_external_completer = $env.config? | get completions? | get external? | get completer?456+457+ # Define the new wrapper completer458+ let fzf_wrapper_completer = {|spans|459+ # 1. Try the FZF completer logic first460+ let fzf_result = do $fzf_external_completer $spans461+462+ # 2. If FZF returned a result (a list, even an empty one), return it.463+ # `null` means FZF didn't handle it because the trigger wasn't present.464+ if $fzf_result != null {465+ $fzf_result466+ } else {467+ # 3. FZF didn't handle it, so call the previous completer (if it exists).468+ if $previous_external_completer != null {469+ do $previous_external_completer $spans470+ } else {471+ # 4. No previous completer, and FZF didn't handle it. Return null.472+ null473+ }474+ }475+ }476+477+ # Register the new wrapper completer478+ # This ensures external completions are enabled and sets our wrapper.479+ $env.config = $env.config | upsert completions {480+ external: {481+ enable: true482+ completer: $fzf_wrapper_completer483+ }484+ }485+486+ $env.__fzf_completer_registered = true487+}488+489+# vim: set sts=2 ts=2 sw=2 tw=120 et :added:shell/key-bindings.nu+166 added
1+# ____ ____2+# / __/___ / __/3+# / /_/_ / / /_4+# / __/ / /_/ __/5+# /_/ /___/_/ key-bindings.nu6+#7+# - $FZF_TMUX (default: 0)8+# - $FZF_TMUX_OPTS9+# - $FZF_TMUX_HEIGHT (default: 40%)10+# - $FZF_CTRL_T_COMMAND (set to "" to disable)11+# - $FZF_CTRL_T_OPTS12+# - $FZF_CTRL_R_COMMAND (set to "" to disable)13+# - $FZF_CTRL_R_OPTS14+# - $FZF_ALT_C_COMMAND (set to "" to disable)15+# - $FZF_ALT_C_OPTS16+17+# Code provided by @igor-ramazanov18+# Source: https://github.com/junegunn/fzf/issues/4122#issuecomment-260736831619+20+# Merge default options in the same order as bash/zsh:21+# 1. --height, --min-height, --bind=ctrl-z:ignore, $prepend22+# 2. $FZF_DEFAULT_OPTS_FILE contents23+# 3. $FZF_DEFAULT_OPTS, $append24+def __fzf_defaults [prepend: string, append: string]: nothing -> string {25+ let base = $"--height ($env.FZF_TMUX_HEIGHT? | default '40%') --min-height 20+ --bind=ctrl-z:ignore ($prepend)"26+ let opts_file = if ($env.FZF_DEFAULT_OPTS_FILE? | default '' | is-not-empty) {27+ try { open --raw ($env.FZF_DEFAULT_OPTS_FILE) | str trim } catch { '' }28+ } else {29+ ''30+ }31+ let default_opts = $env.FZF_DEFAULT_OPTS? | default ''32+ $"($base) ($opts_file) ($default_opts) ($append)" | str trim33+}34+35+# Return the fzf command to use: fzf-tmux when inside tmux and36+# FZF_TMUX is enabled or FZF_TMUX_OPTS is set, plain fzf otherwise.37+def __fzfcmd []: nothing -> list<string> {38+ let in_tmux = ($env.TMUX_PANE? | default '' | into string | is-not-empty)39+ if $in_tmux {40+ let fzf_tmux = ($env.FZF_TMUX? | default 0 | into string)41+ let fzf_tmux_opts = ($env.FZF_TMUX_OPTS? | default '' | into string)42+ if ($fzf_tmux != '0') or ($fzf_tmux_opts | is-not-empty) {43+ let opts = if ($fzf_tmux_opts | is-not-empty) { $fzf_tmux_opts } else { $"-d($env.FZF_TMUX_HEIGHT? | default '40%')" }44+ return ['fzf-tmux' ...(($opts | split row ' ' | where { $in != '' })) '--']45+ }46+ }47+ ['fzf']48+}49+50+51+export-env {52+ $env.FZF_CTRL_T_OPTS = $env.FZF_CTRL_T_OPTS? | default ""53+ $env.FZF_CTRL_R_OPTS = $env.FZF_CTRL_R_OPTS? | default ""54+ $env.FZF_ALT_C_OPTS = $env.FZF_ALT_C_OPTS? | default ""55+}56+57+# Directories58+const alt_c = {59+ name: fzf_dirs60+ modifier: alt61+ keycode: char_c62+ mode: [emacs, vi_normal, vi_insert]63+ event: [64+ {65+ send: executehostcommand66+ cmd: "67+ let fzf_opts = (__fzf_defaults '--reverse --walker=dir,follow,hidden --scheme=path' $'($env.FZF_ALT_C_OPTS) +m');68+ let fzfcmd = (__fzfcmd);69+ let fzf_args = ($fzfcmd | skip 1);70+ let alt_c_cmd = ($env.FZF_ALT_C_COMMAND? | default null);71+ let result = if ($alt_c_cmd == null) or ($alt_c_cmd | is-empty) {72+ with-env { FZF_DEFAULT_OPTS: $fzf_opts, FZF_DEFAULT_OPTS_FILE: '' } { ^($fzfcmd | first) ...$fzf_args }73+ } else {74+ let fzf_cmd_str = ($fzfcmd | str join ' ');75+ let sh_cmd = [$alt_c_cmd '|' $fzf_cmd_str] | str join ' ';76+ with-env { FZF_DEFAULT_OPTS: $fzf_opts, FZF_DEFAULT_OPTS_FILE: '' } { ^sh -c $sh_cmd }77+ };78+ if ($result | is-not-empty) { cd $result };79+ "80+ }81+ ]82+}83+84+# History85+const ctrl_r = {86+ name: fzf_history87+ modifier: control88+ keycode: char_r89+ mode: [emacs, vi_insert, vi_normal]90+ event: [91+ {92+ send: executehostcommand93+ cmd: "commandline edit --replace (94+ let fzf_opts = (__fzf_defaults '' $'--scheme=history --bind=ctrl-r:toggle-sort --wrap-sign \"\t↳ \" --highlight-line ($env.FZF_CTRL_R_OPTS) +m --read0');95+ let fzfcmd = (__fzfcmd);96+ let fzf_args = ($fzfcmd | skip 1);97+ # reverse | uniq: show most recent first, deduplicate keeping the latest.98+ # Nushell's `history` loads the full history as an in-memory table99+ # (bounded by $env.config.history.max_size, default 100,000), so100+ # reverse and uniq run on an already-materialized list. This is O(n)101+ # but acceptable for typical history sizes; unlike bash/zsh `fc -r`,102+ # there is no streaming primitive that would let fzf show the latest103+ # entries before the full list is consumed.104+ history105+ | get command106+ | reverse107+ | uniq108+ | str join (char -i 0)109+ | with-env { FZF_DEFAULT_OPTS: $fzf_opts, FZF_DEFAULT_OPTS_FILE: '' } { ^($fzfcmd | first) ...$fzf_args --query (commandline) }110+ | decode utf-8111+ | str trim112+ )"113+ }114+ ]115+}116+117+# Files118+const ctrl_t = {119+ name: fzf_files120+ modifier: control121+ keycode: char_t122+ mode: [emacs, vi_normal, vi_insert]123+ event: [124+ {125+ send: executehostcommand126+ cmd: "127+ let fzf_opts = (__fzf_defaults '--reverse --walker=file,dir,follow,hidden --scheme=path' $'($env.FZF_CTRL_T_OPTS) -m');128+ let fzfcmd = (__fzfcmd);129+ let fzf_args = ($fzfcmd | skip 1);130+ let ctrl_t_cmd = ($env.FZF_CTRL_T_COMMAND? | default null);131+ let result = if ($ctrl_t_cmd == null) or ($ctrl_t_cmd | is-empty) {132+ with-env { FZF_DEFAULT_OPTS: $fzf_opts, FZF_DEFAULT_OPTS_FILE: '' } { ^($fzfcmd | first) ...$fzf_args }133+ } else {134+ let fzf_cmd_str = ($fzfcmd | str join ' ');135+ let sh_cmd = [$ctrl_t_cmd '|' $fzf_cmd_str] | str join ' ';136+ with-env { FZF_DEFAULT_OPTS: $fzf_opts, FZF_DEFAULT_OPTS_FILE: '' } { ^sh -c $sh_cmd }137+ };138+ let result = ($result | str replace --all (char newline) ' ' | str trim);139+ commandline edit --append $result;140+ commandline set-cursor --end141+ "142+ }143+ ]144+}145+146+# Helper to check if a binding is enabled. A binding is disabled when147+# the corresponding *_COMMAND variable is explicitly set to "".148+# When not defined (null), the binding is enabled (using fzf's built-in walker).149+def __fzf_binding_enabled [var_name: string]: nothing -> bool {150+ let val = ($env | get -o $var_name)151+ # null = not defined = enabled; "" = explicitly disabled152+ $val == null or ($val | into string | is-not-empty)153+}154+155+# Update the $env.config156+export-env {157+ let fzf_names = ['fzf_files', 'fzf_dirs', 'fzf_history']158+ # Filter out any existing fzf bindings, then re-add the enabled ones.159+ # This allows re-sourcing to update bindings (e.g. after changing160+ # FZF_CTRL_T_COMMAND) without creating duplicates.161+ mut bindings = ($env.config.keybindings | where { |kb| $kb.name not-in $fzf_names })162+ if (__fzf_binding_enabled 'FZF_ALT_C_COMMAND') { $bindings = ($bindings | append $alt_c) }163+ if (__fzf_binding_enabled 'FZF_CTRL_R_COMMAND') { $bindings = ($bindings | append $ctrl_r) }164+ if (__fzf_binding_enabled 'FZF_CTRL_T_COMMAND') { $bindings = ($bindings | append $ctrl_t) }165+ $env.config.keybindings = $bindings166+}modified:src/options.go+7 added
231 unmodified lines232 SHELL INTEGRATION233 --bash Print script to set up Bash shell integration234 --zsh Print script to set up Zsh shell integration235 --fish Print script to set up Fish shell integration236+ --nushell Print script to set up Nushell integration237 238 HELP239 --version Display version information and exit240 --help Show this message345 unmodified lines586 ProxyScript string587 Bash bool588 Zsh bool589 Fish bool590+ Nushell bool591 Man bool592 Fuzzy bool593 FuzzyAlgo algo.Algo594 Scheme string139 unmodified lines734 return &Options{735 Bash: false,736 Zsh: false,737 Fish: false,738+ Nushell: false,739 Man: false,740 Fuzzy: true,741 FuzzyAlgo: algo.FuzzyMatchV2,742 Scheme: "", // Unknown1812 unmodified lines2555 // Last-one-wins strategy2556 opts.Bash = false2557 opts.Zsh = false2558 opts.Fish = false2559+ opts.Nushell = false2560 opts.Help = false2561 opts.Version = false2562 opts.Man = false2563 }104 unmodified lines2668 opts.Zsh = true2669 case "--fish":2670 clearExitingOpts()2671 opts.Fish = true2672+ case "--nushell":2673+ clearExitingOpts()2674+ opts.Nushell = true2675 case "-h", "--help":2676 clearExitingOpts()2677 opts.Help = true2678 case "--version":1314 unmodified linesmodified:test/lib/common.rb+66 added-8 removed
76 unmodified lines77 end78 "rm -f ~/.local/share/fish/fzf_test_history; XDG_CONFIG_HOME=#{confdir} fish"79 end80 end81+82+ def nushell83+ @nushell ||=84+ begin85+ xdg_home = '/tmp/fzf-nushell-xdg'86+ config_dir = "#{xdg_home}/nushell"87+ FileUtils.rm_rf(xdg_home)88+ FileUtils.mkdir_p(config_dir)89+90+ # Write env.nu to set up PATH and unset FZF variables91+ File.open("#{config_dir}/env.nu", 'w') do |f|92+ f.puts "$env.PATH = ($env.PATH | split row (char esep) | prepend '#{BASE}/bin')"93+ UNSETS.each do |var|94+ f.puts "hide-env -i #{var}"95+ end96+ f.puts "$env.FZF_DEFAULT_OPTS = \"--no-scrollbar --pointer '>' --marker '>'\""97+ f.puts '$env.config = ($env.config | upsert history { file_format: "plaintext", max_size: 100 })'98+ end99+100+ # Write config.nu with minimal prompt101+ File.open("#{config_dir}/config.nu", 'w') do |f|102+ f.puts '$env.PROMPT_COMMAND = {|| "" }'103+ f.puts '$env.PROMPT_INDICATOR = ""'104+ f.puts '$env.PROMPT_COMMAND_RIGHT = {|| "" }'105+ f.puts '$env.config = ($env.config | upsert show_banner false)'106+ f.puts "source #{BASE}/shell/key-bindings.nu"107+ f.puts "source #{BASE}/shell/completion.nu"108+ end109+110+ "unset #{UNSETS.join(' ')}; env XDG_CONFIG_HOME=#{xdg_home} XDG_DATA_HOME=#{xdg_home}/../fzf-nushell-data nu --config #{config_dir}/config.nu --env-config #{config_dir}/env.nu"111+ end112+ end113 end114 end115 116 class Tmux117 attr_reader :win118 119 def initialize(shell = :bash)120+ @shell = shell121 @win = go(%W[new-window -d -P -F #I #{Shell.send(shell)}]).first122 go(%W[set-window-option -t #{@win} pane-base-index 0])90- return unless shell == :fish91-92- send_keys 'function fish_prompt; end; clear', :Enter93- self.until(&:empty?)123+ if shell == :fish124+ send_keys 'function fish_prompt; end; clear', :Enter125+ self.until(&:empty?)126+ elsif shell == :nushell127+ # Clear history from previous tests to avoid contamination128+ FileUtils.rm_f('/tmp/fzf-nushell-xdg/nushell/history.txt')129+ # Wait for nushell to be ready by polling with a marker command.130+ # We use 'print "fzf-ready"' and check for a line that is exactly131+ # 'fzf-ready' (not the command echo which includes 'print').132+ retries = 0133+ begin134+ send_keys 'print "fzf-ready"', :Enter135+ self.until { |lines| lines.any? { |l| l.strip == 'fzf-ready' } }136+ rescue Minitest::Assertion137+ retries += 1138+ raise if retries > 5139+ retry140+ end141+ send_keys 'clear', :Enter142+ self.until(&:empty?)143+ end144 end145 146 def kill147 go(%W[kill-window -t #{win}])143 unmodified lines291 292 def prepare293 tries = 0294 begin245- self.until(true) do |lines|295+ if @shell == :nushell296 message = "Prepare[#{tries}]"297+ send_keys 'C-u', 'C-l'298+ sleep 0.2299+ send_keys ' ', 'C-u', :Enter, message300+ self.until { |lines| lines[-1] == message }301+ else302+ self.until(true) do |lines|303+ message = "Prepare[#{tries}]"247- send_keys ' ', 'C-u', :Enter, message, :Left, :Right248- sleep(0.15)249- lines[-1] == message304+ send_keys ' ', 'C-u', :Enter, message, :Left, :Right305+ sleep(0.15)306+ lines[-1] == message307+ end308 end309 rescue Minitest::Assertion310 (tries += 1) < 5 ? retry : raise311 end80 unmodified linesmodified:test/test_shell_integration.rb+120 added
1101 unmodified lines1102 assert_equal block.lines.map(&:chomp), lines1103 end1104 end1105 end1106+1107+class TestNushell < TestBase1108+ include TestShell1109+1110+ def teardown1111+ @tmux&.kill1112+ end1113+1114+ def shell1115+ :nushell1116+ end1117+1118+ def set_var(name, val)1119+ tmux.prepare1120+ tmux.send_keys "$env.#{name} = '#{val}'", :Enter1121+ tmux.prepare1122+ end1123+1124+ def unset_var(name)1125+ tmux.prepare1126+ tmux.send_keys "hide-env -i #{name}", :Enter1127+ tmux.prepare1128+ end1129+1130+ def new_shell1131+ tmux.send_keys 'FZF_TMUX=1 nu', :Enter1132+ tmux.prepare1133+ end1134+1135+ # Override: Nushell's builtin `echo` outputs structured data, so we need1136+ # `^echo` (external echo) for plain text output on the command line.1137+ def test_ctrl_t_unicode1138+ writelines(['fzf-unicode 테스트1', 'fzf-unicode 테스트2'])1139+ set_var('FZF_CTRL_T_COMMAND', "cat #{tempname}")1140+1141+ tmux.prepare1142+ tmux.send_keys '^echo ', 'C-t'1143+ tmux.until { |lines| assert_equal 2, lines.match_count }1144+ tmux.send_keys 'fzf-unicode'1145+ tmux.until { |lines| assert_equal 2, lines.match_count }1146+1147+ tmux.send_keys '1'1148+ tmux.until { |lines| assert_equal 1, lines.match_count }1149+ tmux.send_keys :Tab1150+ tmux.until { |lines| assert_equal 1, lines.select_count }1151+1152+ tmux.send_keys :BSpace1153+ tmux.until { |lines| assert_equal 2, lines.match_count }1154+1155+ tmux.send_keys '2'1156+ tmux.until { |lines| assert_equal 1, lines.match_count }1157+ tmux.send_keys :Tab1158+ tmux.until { |lines| assert_equal 2, lines.select_count }1159+1160+ tmux.send_keys :Enter1161+ tmux.until { |lines| assert_match(/\^echo .*fzf-unicode.*1.* .*fzf-unicode.*2/, lines.join) }1162+ tmux.send_keys :Enter1163+ tmux.until { |lines| assert_equal 'fzf-unicode 테스트1 fzf-unicode 테스트2', lines[-1] }1164+ end1165+1166+ # Override: Nushell's external completer replaces the entire token,1167+ # so we use assert_includes instead of assert_equal for the result.1168+ # ~USERNAME expansion and backslash-escaped spaces are not applicable.1169+ def test_file_completion1170+ FileUtils.mkdir_p('/tmp/fzf-test')1171+ (1..100).each { |i| FileUtils.touch("/tmp/fzf-test/#{i}") }1172+ tmux.prepare1173+1174+ # Multi-selection1175+ tmux.send_keys "cat /tmp/fzf-test/10#{trigger}", :Tab1176+ tmux.until { |lines| assert_equal 2, lines.match_count }1177+ tmux.send_keys :Tab, :Tab1178+ tmux.until { |lines| assert_equal 2, lines.select_count }1179+ tmux.send_keys :Enter1180+ tmux.until(true) do |lines|1181+ assert_includes lines[-1].to_s, '/tmp/fzf-test/10'1182+ assert_includes lines[-1].to_s, '/tmp/fzf-test/100'1183+ end1184+1185+ # Single selection1186+ tmux.prepare1187+ tmux.send_keys "cat /tmp/fzf-test/10#{trigger}", :Tab1188+ tmux.until { |lines| assert_equal 2, lines.match_count }1189+ tmux.send_keys '0'1190+ tmux.until { |lines| assert_equal 1, lines.match_count }1191+ tmux.send_keys :Enter1192+ tmux.until(true) do |lines|1193+ assert_includes lines[-1].to_s, '/tmp/fzf-test/100'1194+ end1195+1196+ # Should include hidden files1197+ (1..100).each { |i| FileUtils.touch("/tmp/fzf-test/.hidden-#{i}") }1198+ tmux.prepare1199+ tmux.send_keys "cat /tmp/fzf-test/hidden#{trigger}", :Tab1200+ tmux.until(true) do |lines|1201+ assert_equal 100, lines.match_count1202+ assert lines.any_include?('/tmp/fzf-test/.hidden-')1203+ end1204+ tmux.send_keys :Enter1205+ ensure1206+ FileUtils.rm_rf('/tmp/fzf-test')1207+ end1208+1209+ # Nushell does not support multiline command recall the same way1210+ # as bash/zsh/fish, so test_ctrl_r_multiline is omitted.1211+1212+ # Override: only test with 'foo' -- single and double quotes cause1213+ # issues in Nushell's line editor.1214+ def test_ctrl_r_abort1215+ %w[foo].each do |query|1216+ tmux.prepare1217+ tmux.send_keys :Enter, query1218+ tmux.until { |lines| assert lines[-1]&.start_with?(query) }1219+ tmux.send_keys 'C-r'1220+ tmux.until { |lines| assert_equal "> #{query}", lines[-1] }1221+ tmux.send_keys 'C-g'1222+ tmux.until { |lines| assert lines[-1]&.start_with?(query) }1223+ end1224+ end1225+endmodified:install+27 added-2 removed
4 unmodified lines5 version=0.72.06 auto_completion=7 key_bindings=8 update_config=29-shells="bash zsh fish"9+shells="bash zsh fish nushell"10 prefix='~/.fzf'11 prefix_expand=~/.fzf12 fish_dir=${XDG_CONFIG_HOME:-$HOME/.config}/fish13+nushell_autoload_dir=${XDG_CONFIG_HOME:-$HOME/.config}/nushell/autoload14 15 help() {16 cat << EOF17 usage: $0 [OPTIONS]9 unmodified lines27 28 --no-bash Do not set up bash configuration29 --no-zsh Do not set up zsh configuration30 --no-fish Do not set up fish configuration31+ --no-nushell Do not set up nushell configuration32 EOF33 }34 35 for opt in "$@"; do21 unmodified lines57 --bin) ;;58 --no-bash) shells=${shells/bash/} ;;59 --no-zsh) shells=${shells/zsh/} ;;60 --no-fish) shells=${shells/fish/} ;;61+ --no-nushell) shells=${shells/nushell/} ;;62 *)63 echo "unknown option: $opt"64 help65 exit 1160 unmodified lines226 227 [[ $* =~ "--bin" ]] && exit 0228 229 for s in $shells; do230+ bin=$s231+ [[ "$s" = nushell ]] && bin=nu227- if ! command -v "$s" > /dev/null; then232+ if ! command -v "$bin" > /dev/null; then233 shells=${shells/$s/}234 fi235 done236 18 unmodified lines255 for shell in $shells; do256 fzf_completion="source \"$fzf_base/shell/completion.${shell}\""257 fzf_key_bindings="source \"$fzf_base/shell/key-bindings.${shell}\""258 [[ $shell == fish ]] && continue259+ [[ $shell == nushell ]] && continue260 src=${prefix_expand}.${shell}261 echo -n "Generate $src ... "262 263 if [ $auto_completion -eq 0 ]; then109 unmodified lines373 fi374 echo375 for shell in $shells; do376 [[ $shell == fish ]] && continue377+ [[ $shell == nushell ]] && continue378 [ $shell = zsh ] && dest=${ZDOTDIR:-~}/.zshrc || dest=~/.bashrc379 append_line $update_config "[ -f ${prefix}.${shell} ] && source ${prefix}.${shell}" "$dest" "${prefix}.${shell}"380 done381 60 unmodified lines442 fi443 fi444 fi445 446+if [[ "$shells" =~ nushell ]]; then447+ if [[ $key_bindings -eq 1 || $auto_completion -eq 1 ]]; then448+ echo "Setting up Nushell integration ..."449+ mkdir -p "$nushell_autoload_dir"450+ echo -n " Generate _fzf_integration.nu ... "451+ if [[ $key_bindings -eq 1 && $auto_completion -eq 1 ]]; then452+ "$fzf_base"/bin/fzf --nushell > "$nushell_autoload_dir/_fzf_integration.nu"453+ elif [[ $key_bindings -eq 1 ]]; then454+ cp "$fzf_base/shell/key-bindings.nu" "$nushell_autoload_dir/_fzf_integration.nu"455+ else456+ cp "$fzf_base/shell/completion.nu" "$nushell_autoload_dir/_fzf_integration.nu"457+ fi458+ echo "OK"459+ echo460+ fi461+fi462+463 if [ $update_config -eq 1 ]; then464 echo 'Finished. Restart your shell or reload config file.'465 if [[ $shells =~ bash ]]; then466 echo -n ' source ~/.bashrc # bash'1 unmodified line468 echo469 fi470 [[ $shells =~ zsh ]] && echo " source ${ZDOTDIR:-~}/.zshrc # zsh"471 [[ $shells =~ fish && $lno_func -ne 0 ]] && echo ' fish_user_key_bindings # fish'472+ [[ $shells =~ nushell ]] && echo ' # nushell: files are loaded automatically from autoload directory'473 echo474 echo 'Use uninstall script to remove fzf.'475 echo476 fi1 unmodified linemodified:main.go+11 added
27 unmodified lines28 29 //go:embed shell/key-bindings.fish30 var fishKeyBindings []byte31 32+//go:embed shell/key-bindings.nu33+var nushellKeyBindings []byte34+35+//go:embed shell/completion.nu36+var nushellCompletion []byte37+38 //go:embed shell/completion.fish39 var fishCompletion []byte40 41 //go:embed man/man1/fzf.134 unmodified lines76 printScript("key-bindings.fish", fishKeyBindings)77 printScript("completion.fish", fishCompletion)78 return79 }80+ if options.Nushell {81+ printScript("key-bindings.nu", nushellKeyBindings)82+ printScript("completion.nu", nushellCompletion)83+ return84+ }85 if options.Help {86 fmt.Print(fzf.Usage)87 return88 }27 unmodified linesmodified:README.md+47 added-5 removed
38 unmodified lines39 40 - **Portable** -- Distributed as a single binary for easy installation41 - **Fast** -- Optimized to process millions of items instantly42 - **Versatile** -- Fully customizable through an event-action binding mechanism43-- **All-inclusive** -- Comes with integrations for Bash, Zsh, Fish, Vim, and Neovim43+- **All-inclusive** -- Comes with integrations for Bash, Zsh, Fish, Nushell, Vim, and Neovim44 45 Table of Contents46 -----------------47 32 unmodified lines80 * [Customizing completion source for paths and directories](#customizing-completion-source-for-paths-and-directories)81 * [Supported commands (bash)](#supported-commands-bash)82 * [Custom fuzzy completion](#custom-fuzzy-completion)83 * [Fuzzy completion for fish](#fuzzy-completion-for-fish)84+ * [Fuzzy completion for Nushell](#fuzzy-completion-for-nushell)85 * [Vim plugin](#vim-plugin)86 * [Advanced topics](#advanced-topics)87 * [Customizing for different types of input](#customizing-for-different-types-of-input)88 * [Performance](#performance)121 unmodified lines210 ```fish211 # Set up fzf key bindings212 fzf --fish | source213 ```214+* Nushell -- Nushell does not support piping into `source`, so the install215+ script generates a file in the autoload directory. If you didn't use the216+ install script, you can manually set it up:217+ ```nu218+ # Generate the integration script219+ mkdir ($nu.default-config-dir | path join "autoload")220+ fzf --nushell | save -f ($nu.default-config-dir | path join "autoload" "_fzf_integration.nu")221+ ```222 223 > [!NOTE]215-> `--bash`, `--zsh`, and `--fish` options are only available in fzf 0.48.0 or216-> later. If you have an older version of fzf, or want finer control, you can224+> `--bash`, `--zsh`, `--fish`, and `--nushell` options are only available in225+> recent versions of fzf. If you have an older version of fzf, or want finer control, you can226 > source individual script files in the [/shell](/shell) directory. The227 > location of the files may vary depending on the package manager you use.228 > Please refer to the package documentation for more information.229 > (e.g. `apt show fzf`)5 unmodified lines235 >236 > * bash: `FZF_CTRL_R_COMMAND= FZF_ALT_C_COMMAND= eval "$(fzf --bash)"`237 > * zsh: `FZF_CTRL_R_COMMAND= FZF_ALT_C_COMMAND= source <(fzf --zsh)`238 > * fish: `fzf --fish | FZF_CTRL_R_COMMAND= FZF_ALT_C_COMMAND= source`239+> * nushell: add to your `env.nu`:240+> `$env.FZF_CTRL_R_COMMAND = ""; $env.FZF_ALT_C_COMMAND = ""`241 >242 > Setting the variables after sourcing the script will have no effect.243 244 ### Vim/Neovim plugin271 unmodified lines516 Key bindings for command-line517 -----------------------------518 519 By [setting up shell integration](#setting-up-shell-integration), you can use509-the following key bindings in bash, zsh, and fish.520+the following key bindings in bash, zsh, fish, and Nushell.521 522 - `CTRL-T` - Paste the selected files and directories onto the command-line523 - The list is generated using `--walker file,dir,follow,hidden` option524 - You can override the behavior by setting `FZF_CTRL_T_COMMAND` to a custom command that generates the desired list59 unmodified lines584 585 Fuzzy completion586 ----------------587 577-Shell integration also provides fuzzy completion for bash, zsh, and fish.588+Shell integration also provides fuzzy completion for bash, zsh, fish, and Nushell.589 590 ### Files and directories591 592 Fuzzy completion for files and directories can be triggered if the word before240 unmodified lines833 end834 end835 ```836 837+### Fuzzy completion for Nushell838+839+Fuzzy completion in Nushell works via the840+[external completer](https://www.nushell.sh/cookbook/external_completers.html)841+mechanism. There are some differences compared to bash and zsh:842+843+- On Nushell >= 0.103.0, the external completer is no longer called for844+ built-in commands (e.g. `cd`, `ls`). Fuzzy completion with `**<TAB>` only845+ works for external commands.846+- Custom completers can be defined via the `$env.FZF_COMPLETERS` record in847+ your `config.nu`. Each entry is a closure that receives the prefix and the848+ command spans, and returns either a list of candidate strings or a record849+ `{ candidates: [...], opts: [...] }` for custom fzf options:850+ ```nu851+ $env.FZF_COMPLETERS = {852+ pacman: {|prefix, spans|853+ let sub = $spans | skip 1 | first854+ let candidates = (if ($sub =~ "-[SF]") { ^pacman -Slq | lines855+ } else if ($sub =~ "-[QR]") { ^pacman -Qq | lines856+ } else { [] })857+ { candidates: $candidates, opts: ["--preview", "pacman -Si {}"] }858+ }859+ }860+ ```861+ See [shell/completion-examples.nu](shell/completion-examples.nu) for more862+ examples.863+- The following environment variables are supported:864+ `FZF_COMPLETION_TRIGGER`, `FZF_COMPLETION_OPTS`,865+ `FZF_COMPLETION_PATH_OPTS`, `FZF_COMPLETION_DIR_OPTS`,866+ `FZF_COMPLETION_DIR_COMMANDS`.867+868 Vim plugin869 ----------870 871 See [README-VIM.md](README-VIM.md).281 unmodified linesmodified:typos.toml+1 added
4 unmodified lines5 enew = "enew"6 tabe = "tabe"7 Iterm = "Iterm"8 ser = "ser"9+Slq = "Slq"10 11 [files]12 extend-exclude = ["README.md", "*.s"]modified:uninstall+3 added
112 unmodified lines113 echo "Can't delete non-empty directory: \"${fish_dir}/functions\""114 fi115 fi116 117+nushell_autoload_dir=${XDG_CONFIG_HOME:-$HOME/.config}/nushell/autoload118+remove "${nushell_autoload_dir}/_fzf_integration.nu"119+120 config_dir=$(dirname "$prefix_expand")121 if [[ $xdg == 1 ]] && [[ $config_dir == */fzf ]] && [[ -d $config_dir ]]; then122 rmdir "$config_dir"123 fi