home-config/fish/functions/_fzf_search_variables.fish
73047489d41521336cc9c15673d26415ab3fd1b6
· 2.1 KB · 47 lines
raw
| 1 | # This function expects the following two arguments: |
| 2 | # argument 1 = output of (set --show | psub), i.e. a file with the scope info and values of all variables |
| 3 | # argument 2 = output of (set --names | psub), i.e. a file with all variable names |
| 4 | function _fzf_search_variables --argument-names set_show_output set_names_output --description "Search and preview shell variables. Replace the current token with the selected variable." |
| 5 | if test -z "$set_names_output" |
| 6 | printf '%s\n' '_fzf_search_variables requires 2 arguments.' >&2 |
| 7 | |
| 8 | commandline --function repaint |
| 9 | return 22 # 22 means invalid argument in POSIX |
| 10 | end |
| 11 | |
| 12 | # Exclude the history variable from being piped into fzf because |
| 13 | # 1. it's not included in $set_names_output |
| 14 | # 2. it tends to be a very large value => increases computation time |
| 15 | # 3._fzf_search_history is a much better way to examine history anyway |
| 16 | set -f all_variable_names (string match --invert history <$set_names_output) |
| 17 | |
| 18 | set -f current_token (commandline --current-token) |
| 19 | # Use the current token to pre-populate fzf's query. If the current token begins |
| 20 | # with a $, remove it from the query so that it will better match the variable names |
| 21 | set -f cleaned_curr_token (string replace -- '$' '' $current_token) |
| 22 | |
| 23 | set -f variable_names_selected ( |
| 24 | printf '%s\n' $all_variable_names | |
| 25 | _fzf_wrapper --preview "_fzf_extract_var_info {} $set_show_output" \ |
| 26 | --prompt="Variables> " \ |
| 27 | --preview-window="wrap" \ |
| 28 | --multi \ |
| 29 | --query=$cleaned_curr_token \ |
| 30 | $fzf_variables_opts |
| 31 | ) |
| 32 | |
| 33 | if test $status -eq 0 |
| 34 | # If the current token begins with a $, do not overwrite the $ when |
| 35 | # replacing the current token with the selected variable. |
| 36 | # Uses brace expansion to prepend $ to each variable name. |
| 37 | commandline --current-token --replace ( |
| 38 | if string match --quiet -- '$*' $current_token |
| 39 | string join " " \${$variable_names_selected} |
| 40 | else |
| 41 | string join " " $variable_names_selected |
| 42 | end |
| 43 | ) |
| 44 | end |
| 45 | |
| 46 | commandline --function repaint |
| 47 | end |