dotfiles

Personal dotfiles.
git clone git://vcs.sapka.me/dotfiles
Log | Files | Refs | Submodules

commit 531c2b18759e55965c795360774e17ee5246e50f
parent d7f05c3b53dd8e64357701264b1fece6d7ed4fe2
Author: Michal Sapka <michal@sapka.me>
Date:   Sun, 21 Aug 2022 21:31:54 +0200

feature: fish plugins

Diffstat:
Afish/.config/fish/completions/fzf_configure_bindings.fish | 7+++++++
Afish/.config/fish/conf.d/fzf.fish | 28++++++++++++++++++++++++++++
Afish/.config/fish/conf.d/z.fish | 63+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Afish/.config/fish/fish_plugins | 2++
Mfish/.config/fish/fish_variables | 9+++++++++
Afish/.config/fish/functions/__z.fish | 174+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Afish/.config/fish/functions/__z_add.fish | 49+++++++++++++++++++++++++++++++++++++++++++++++++
Afish/.config/fish/functions/__z_clean.fish | 11+++++++++++
Afish/.config/fish/functions/__z_complete.fish | 13+++++++++++++
Afish/.config/fish/functions/_fzf_configure_bindings_help.fish | 43+++++++++++++++++++++++++++++++++++++++++++
Afish/.config/fish/functions/_fzf_extract_var_info.fish | 15+++++++++++++++
Afish/.config/fish/functions/_fzf_preview_changed_file.fish | 30++++++++++++++++++++++++++++++
Afish/.config/fish/functions/_fzf_preview_file.fish | 43+++++++++++++++++++++++++++++++++++++++++++
Afish/.config/fish/functions/_fzf_report_diff_type.fish | 16++++++++++++++++
Afish/.config/fish/functions/_fzf_report_file_type.fish | 6++++++
Afish/.config/fish/functions/_fzf_search_directory.fish | 44++++++++++++++++++++++++++++++++++++++++++++
Afish/.config/fish/functions/_fzf_search_git_log.fish | 28++++++++++++++++++++++++++++
Afish/.config/fish/functions/_fzf_search_git_status.fish | 34++++++++++++++++++++++++++++++++++
Afish/.config/fish/functions/_fzf_search_history.fish | 30++++++++++++++++++++++++++++++
Afish/.config/fish/functions/_fzf_search_processes.fish | 28++++++++++++++++++++++++++++
Afish/.config/fish/functions/_fzf_search_variables.fish | 46++++++++++++++++++++++++++++++++++++++++++++++
Afish/.config/fish/functions/_fzf_wrapper.fish | 20++++++++++++++++++++
Afish/.config/fish/functions/fzf_configure_bindings.fish | 46++++++++++++++++++++++++++++++++++++++++++++++
23 files changed, 785 insertions(+), 0 deletions(-)

diff --git a/fish/.config/fish/completions/fzf_configure_bindings.fish b/fish/.config/fish/completions/fzf_configure_bindings.fish @@ -0,0 +1,7 @@ +complete fzf_configure_bindings --no-files +complete fzf_configure_bindings --long help --short h --description "Print help" +complete fzf_configure_bindings --long directory --description "Change the key binding for searching directory" +complete fzf_configure_bindings --long git_log --description "Change the key binding for searching git log" +complete fzf_configure_bindings --long git_status --description "Change the key binding for searching git status" +complete fzf_configure_bindings --long history --description "Change the key binding for searching history" +complete fzf_configure_bindings --long variables --description "Change the key binding for searching variables" diff --git a/fish/.config/fish/conf.d/fzf.fish b/fish/.config/fish/conf.d/fzf.fish @@ -0,0 +1,28 @@ +# fzf.fish is only meant to be used in interactive mode. If not in interactive mode and not in CI, skip the config to speed up shell startup +if not status is-interactive && test "$CI" != true + exit +end + +# Because of scoping rules, to capture the shell variables exactly as they are, we must read +# them before even executing _fzf_search_variables. We use psub to store the +# variables' info in temporary files and pass in the filenames as arguments. +# This variable is global so that it can be referenced by fzf_configure_bindings and in tests +set --global _fzf_search_vars_command '_fzf_search_variables (set --show | psub) (set --names | psub)' + + +# Install the default bindings, which are mnemonic and minimally conflict with fish's preset bindings +fzf_configure_bindings + +# Doesn't erase autoloaded _fzf_* functions because they are not easily accessible once key bindings are erased +function _fzf_uninstall --on-event fzf_uninstall + _fzf_uninstall_bindings + + set --erase _fzf_search_vars_command + functions --erase _fzf_uninstall _fzf_migration_message _fzf_uninstall_bindings fzf_configure_bindings + complete --erase fzf_configure_bindings + + set_color cyan + echo "fzf.fish uninstalled." + echo "You may need to manually remove fzf_configure_bindings from your config.fish if you were using custom key bindings." + set_color normal +end diff --git a/fish/.config/fish/conf.d/z.fish b/fish/.config/fish/conf.d/z.fish @@ -0,0 +1,63 @@ +if test -z "$Z_DATA" + if test -z "$XDG_DATA_HOME" + set -U Z_DATA_DIR "$HOME/.local/share/z" + else + set -U Z_DATA_DIR "$XDG_DATA_HOME/z" + end + set -U Z_DATA "$Z_DATA_DIR/data" +end + +if test ! -e "$Z_DATA" + if test ! -e "$Z_DATA_DIR" + mkdir -p -m 700 "$Z_DATA_DIR" + end + touch "$Z_DATA" +end + +if test -z "$Z_CMD" + set -U Z_CMD z +end + +set -U ZO_CMD "$Z_CMD"o + +if test ! -z $Z_CMD + function $Z_CMD -d "jump around" + __z $argv + end +end + +if test ! -z $ZO_CMD + function $ZO_CMD -d "open target dir" + __z -d $argv + end +end + +if not set -q Z_EXCLUDE + set -U Z_EXCLUDE "^$HOME\$" +else if contains $HOME $Z_EXCLUDE + # Workaround: migrate old default values to a regex (see #90). + set Z_EXCLUDE (string replace -r -- "^$HOME\$" '^'$HOME'$$' $Z_EXCLUDE) +end + +# Setup completions once first +__z_complete + +function __z_on_variable_pwd --on-variable PWD + __z_add +end + +function __z_uninstall --on-event z_uninstall + functions -e __z_on_variable_pwd + functions -e $Z_CMD + functions -e $ZO_CMD + + if test ! -z "$Z_DATA" + printf "To completely erase z's data, remove:\n" >/dev/stderr + printf "%s\n" "$Z_DATA" >/dev/stderr + end + + set -e Z_CMD + set -e ZO_CMD + set -e Z_DATA + set -e Z_EXCLUDE +end diff --git a/fish/.config/fish/fish_plugins b/fish/.config/fish/fish_plugins @@ -0,0 +1,2 @@ +jethrokuan/z +patrickf1/fzf.fish diff --git a/fish/.config/fish/fish_variables b/fish/.config/fish/fish_variables @@ -1,6 +1,15 @@ # This file contains fish universal variable definitions. # VERSION: 3.0 +SETUVAR ZO_CMD:zo +SETUVAR Z_CMD:z +SETUVAR Z_DATA:/home/msapka/\x2elocal/share/z/data +SETUVAR Z_DATA_DIR:/home/msapka/\x2elocal/share/z +SETUVAR Z_EXCLUDE:\x5e/home/msapka\x24 SETUVAR __fish_initialized:3400 +SETUVAR _fisher_jethrokuan_2F_z_files:\x7e/\x2econfig/fish/functions/__z\x2efish\x1e\x7e/\x2econfig/fish/functions/__z_add\x2efish\x1e\x7e/\x2econfig/fish/functions/__z_clean\x2efish\x1e\x7e/\x2econfig/fish/functions/__z_complete\x2efish\x1e\x7e/\x2econfig/fish/conf\x2ed/z\x2efish +SETUVAR _fisher_patrickf1_2F_fzf_2E_fish_files:\x7e/\x2econfig/fish/functions/_fzf_configure_bindings_help\x2efish\x1e\x7e/\x2econfig/fish/functions/_fzf_extract_var_info\x2efish\x1e\x7e/\x2econfig/fish/functions/_fzf_preview_changed_file\x2efish\x1e\x7e/\x2econfig/fish/functions/_fzf_preview_file\x2efish\x1e\x7e/\x2econfig/fish/functions/_fzf_report_diff_type\x2efish\x1e\x7e/\x2econfig/fish/functions/_fzf_report_file_type\x2efish\x1e\x7e/\x2econfig/fish/functions/_fzf_search_directory\x2efish\x1e\x7e/\x2econfig/fish/functions/_fzf_search_git_log\x2efish\x1e\x7e/\x2econfig/fish/functions/_fzf_search_git_status\x2efish\x1e\x7e/\x2econfig/fish/functions/_fzf_search_history\x2efish\x1e\x7e/\x2econfig/fish/functions/_fzf_search_processes\x2efish\x1e\x7e/\x2econfig/fish/functions/_fzf_search_variables\x2efish\x1e\x7e/\x2econfig/fish/functions/_fzf_wrapper\x2efish\x1e\x7e/\x2econfig/fish/functions/fzf_configure_bindings\x2efish\x1e\x7e/\x2econfig/fish/conf\x2ed/fzf\x2efish\x1e\x7e/\x2econfig/fish/completions/fzf_configure_bindings\x2efish +SETUVAR _fisher_plugins:jethrokuan/z\x1epatrickf1/fzf\x2efish +SETUVAR _fisher_upgraded_to_4_4:\x1d SETUVAR fish_color_autosuggestion:555\x1ebrblack SETUVAR fish_color_cancel:\x2dr SETUVAR fish_color_command:blue diff --git a/fish/.config/fish/functions/__z.fish b/fish/.config/fish/functions/__z.fish @@ -0,0 +1,174 @@ +function __z -d "Jump to a recent directory." + function __print_help -d "Print z help." + printf "Usage: $Z_CMD [-celrth] string1 string2...\n\n" + printf " -c --clean Removes directories that no longer exist from $Z_DATA\n" + printf " -d --dir Opens matching directory using system file manager.\n" + printf " -e --echo Prints best match, no cd\n" + printf " -l --list List matches and scores, no cd\n" + printf " -p --purge Delete all entries from $Z_DATA\n" + printf " -r --rank Search by rank\n" + printf " -t --recent Search by recency\n" + printf " -x --delete Removes the current directory from $Z_DATA\n" + printf " -h --help Print this help\n\n" + end + function __z_legacy_escape_regex + # taken from escape_string_pcre2 in fish + # used to provide compatibility with fish 2 + for c in (string split '' $argv) + if contains $c (string split '' '.^$*+()?[{}\\|-]') + printf \\ + end + printf '%s' $c + end + end + + set -l options h/help c/clean e/echo l/list p/purge r/rank t/recent d/directory x/delete + + argparse $options -- $argv + + if set -q _flag_help + __print_help + return 0 + else if set -q _flag_clean + __z_clean + printf "%s cleaned!\n" $Z_DATA + return 0 + else if set -q _flag_purge + echo >$Z_DATA + printf "%s purged!\n" $Z_DATA + return 0 + else if set -q _flag_delete + sed -i -e "\:^$PWD|.*:d" $Z_DATA + return 0 + end + + set -l typ + + if set -q _flag_rank + set typ rank + else if set -q _flag_recent + set typ recent + end + + set -l z_script ' + function frecent(rank, time) { + dx = t-time + if( dx < 3600 ) return rank*4 + if( dx < 86400 ) return rank*2 + if( dx < 604800 ) return rank/2 + return rank/4 + } + + function output(matches, best_match, common) { + # list or return the desired directory + if( list ) { + cmd = "sort -nr" + for( x in matches ) { + if( matches[x] ) { + printf "%-10s %s\n", matches[x], x | cmd + } + } + } else { + if( common ) best_match = common + print best_match + } + } + + function common(matches) { + # find the common root of a list of matches, if it exists + for( x in matches ) { + if( matches[x] && (!short || length(x) < length(short)) ) { + short = x + } + } + if( short == "/" ) return + for( x in matches ) if( matches[x] && index(x, short) != 1 ) { + return + } + return short + } + + BEGIN { + hi_rank = ihi_rank = -9999999999 + } + { + if( typ == "rank" ) { + rank = $2 + } else if( typ == "recent" ) { + rank = $3 - t + } else rank = frecent($2, $3) + if( $1 ~ q ) { + matches[$1] = rank + } else if( tolower($1) ~ tolower(q) ) imatches[$1] = rank + if( matches[$1] && matches[$1] > hi_rank ) { + best_match = $1 + hi_rank = matches[$1] + } else if( imatches[$1] && imatches[$1] > ihi_rank ) { + ibest_match = $1 + ihi_rank = imatches[$1] + } + } + + END { + # prefer case sensitive + if( best_match ) { + output(matches, best_match, common(matches)) + } else if( ibest_match ) { + output(imatches, ibest_match, common(imatches)) + } + } + ' + + set -l qs + for arg in $argv + set -l escaped $arg + if string escape --style=regex '' >/dev/null 2>&1 # use builtin escape if available + set escaped (string escape --style=regex $escaped) + else + set escaped (__z_legacy_escape_regex $escaped) + end + # Need to escape twice, see https://www.math.utah.edu/docs/info/gawk_5.html#SEC32 + set escaped (string replace --all \\ \\\\ $escaped) + set qs $qs $escaped + end + set -l q (string join '.*' $qs) + + if set -q _flag_list + # Handle list separately as it can print common path information to stderr + # which cannot be captured from a subcommand. + command awk -v t=(date +%s) -v list="list" -v typ="$typ" -v q="$q" -F "|" $z_script "$Z_DATA" + return + end + + set target (command awk -v t=(date +%s) -v typ="$typ" -v q="$q" -F "|" $z_script "$Z_DATA") + + if test "$status" -gt 0 + return + end + + if test -z "$target" + printf "'%s' did not match any results\n" "$argv" + return 1 + end + + if set -q _flag_echo + printf "%s\n" "$target" + else if set -q _flag_directory + if test -n "$ZO_METHOD" + type -q "$ZO_METHOD"; and "$ZO_METHOD" "$target"; and return $status + echo "Cannot open with ZO_METHOD set to $ZO_METHOD"; and return 1 + else if test "$OS" = Windows_NT + # Be careful, in msys2, explorer always return 1 + type -q explorer; and explorer "$target" + return 0 + echo "Cannot open file explorer" + return 1 + else + type -q xdg-open; and xdg-open "$target"; and return $status + type -q open; and open "$target"; and return $status + echo "Not sure how to open file manager"; and return 1 + end + else + pushd "$target" + end +end diff --git a/fish/.config/fish/functions/__z_add.fish b/fish/.config/fish/functions/__z_add.fish @@ -0,0 +1,49 @@ +function __z_add -d "Add PATH to .z file" + test -n "$fish_private_mode"; and return 0 + + for i in $Z_EXCLUDE + if string match -r $i $PWD >/dev/null + return 0 #Path excluded + end + end + + set -l tmpfile (mktemp $Z_DATA.XXXXXX) + + if test -f $tmpfile + set -l path (string replace --all \\ \\\\ $PWD) + command awk -v path=$path -v now=(date +%s) -F "|" ' + BEGIN { + rank[path] = 1 + time[path] = now + } + $2 >= 1 { + if( $1 == path ) { + rank[$1] = $2 + 1 + time[$1] = now + } + else { + rank[$1] = $2 + time[$1] = $3 + } + count += $2 + } + END { + if( count > 1000 ) { + for( i in rank ) print i "|" 0.9*rank[i] "|" time[i] # aging + } + else for( i in rank ) print i "|" rank[i] "|" time[i] + } + ' $Z_DATA 2>/dev/null >$tmpfile + + if test ! -z "$Z_OWNER" + chown $Z_OWNER:(id -ng $Z_OWNER) $tmpfile + end + # + # Don't use redirection here as it can lead to a race condition where $Z_DATA is clobbered. + # Note: There is a still a possible race condition where an old version of $Z_DATA is + # read by one instance of Fish before another instance of Fish writes its copy. + # + command mv $tmpfile $Z_DATA + or command rm $tmpfile + end +end diff --git a/fish/.config/fish/functions/__z_clean.fish b/fish/.config/fish/functions/__z_clean.fish @@ -0,0 +1,11 @@ +function __z_clean -d "Clean up .z file to remove paths no longer valid" + set -l tmpfile (mktemp $Z_DATA.XXXXXX) + + if test -f $tmpfile + while read line + set -l path (string split '|' $line)[1] + test -d $path; and echo $line + end <$Z_DATA >$tmpfile + command mv -f $tmpfile $Z_DATA + end +end diff --git a/fish/.config/fish/functions/__z_complete.fish b/fish/.config/fish/functions/__z_complete.fish @@ -0,0 +1,13 @@ +function __z_complete -d "add completions" + complete -c $Z_CMD -a "(__z -l | string replace -r '^\\S*\\s*' '')" -f -k + complete -c $ZO_CMD -a "(__z -l | string replace -r '^\\S*\\s*' '')" -f -k + + complete -c $Z_CMD -s c -l clean -d "Cleans out $Z_DATA" + complete -c $Z_CMD -s e -l echo -d "Prints best match, no cd" + complete -c $Z_CMD -s l -l list -d "List matches, no cd" + complete -c $Z_CMD -s p -l purge -d "Purges $Z_DATA" + complete -c $Z_CMD -s r -l rank -d "Searches by rank, cd" + complete -c $Z_CMD -s t -l recent -d "Searches by recency, cd" + complete -c $Z_CMD -s h -l help -d "Print help" + complete -c $Z_CMD -s x -l delete -d "Removes the current directory from $Z_DATA" +end diff --git a/fish/.config/fish/functions/_fzf_configure_bindings_help.fish b/fish/.config/fish/functions/_fzf_configure_bindings_help.fish @@ -0,0 +1,43 @@ +function _fzf_configure_bindings_help --description "Prints the help message for fzf_configure_bindings." + echo "\ +USAGE: + fzf_configure_bindings [--FEATURE[=KEY_SEQUENCE]...] + +DESCRIPTION + By default, fzf_configure_bindings installs mnemonic key bindings for fzf.fish's features. Each + feature's binding can be customized through a corresponding namesake option: + FEATURE | MNEMONIC KEY SEQUENCE | CORRESPONDING OPTION + Search directory | Ctrl+Alt+F (F for file) | --directory + Search git log | Ctrl+Alt+L (L for log) | --git_log + Search git status | Ctrl+Alt+S (S for status) | --git_status + Search history | Ctrl+R (R for reverse) | --history + Search variables | Ctrl+V (V for variable) | --variables + Search processes | Ctrl+Alt+P (P for process) | --processes + An option with a key sequence value overrides the binding for its feature, while an option + without a value disables the binding. A feature that is not customized retains its default + menomonic binding specified above. Key bindings are installed for default and insert modes. + + In terms of validation, fzf_configure_bindings fails if passed unknown options. Furthermore, it + expects an equals sign between an option's name and value. However, it does not validate key + sequences. Rather, consider using fish_key_reader to manually validate them. + + In terms of experimentation, fzf_configure_bindings erases any bindings it previously installed + before installing new ones so it can be repeatedly executed in the same fish session without + problem. Once the desired fzf_configure_bindings command has been found, add it to config.fish + in order to persist the bindings. + + The -h and --help options print this help message. + +EXAMPLES + Install the default mnemonic bindings + \$ fzf_configure_bindings + Install the default bindings but override git log's binding to Ctrl+G + \$ fzf_configure_bindings --git_log=\cg + Install the default bindings but leave search history unbound + \$ fzf_configure_bindings --history + Alternative style of disabling search history + \$ fzf_configure_bindings --history= + An agglomeration of all the options + \$ fzf_configure_bindings --git_status=\cg --history=\ch --variables --directory --git_log +" +end diff --git a/fish/.config/fish/functions/_fzf_extract_var_info.fish b/fish/.config/fish/functions/_fzf_extract_var_info.fish @@ -0,0 +1,15 @@ +# helper function for _fzf_search_variables +function _fzf_extract_var_info --argument-names variable_name set_show_output --description "Extract and reformat lines pertaining to \$variable_name from \$set_show_output." + # Extract only the lines about the variable, all of which begin with either + # $variable_name: ...or... $variable_name[ + string match --regex "^\\\$$variable_name(?::|\[).*" <$set_show_output | + + # Strip the variable name prefix, including ": " for scope info lines + string replace --regex "^\\\$$variable_name(?:: )?" '' | + + # Distill the lines of values, replacing... + # [1]: |value| + # ...with... + # [1] value + string replace --regex ": \|(.*)\|" ' $1' +end diff --git a/fish/.config/fish/functions/_fzf_preview_changed_file.fish b/fish/.config/fish/functions/_fzf_preview_changed_file.fish @@ -0,0 +1,30 @@ +# helper for _fzf_search_git_status +# arg should be a line from git status --short, e.g. +# MM functions/_fzf_preview_changed_file.fish +# D README.md +# R LICENSE.md -> LICENSE +function _fzf_preview_changed_file --description "Show the untracked, staged, and/or unstaged changes in the given file." + set -l path (string split ' ' $argv)[-1] + # first letter of short format shows index, second letter shows working tree + # https://git-scm.com/docs/git-status/2.35.0#_output + set -l index_status (string sub --length 1 $argv) + set -l working_tree_status (string sub --start 2 --length 1 $argv) + + if test $index_status = '?' + _fzf_report_diff_type Untracked + _fzf_preview_file $path + else + # no-prefix because the file is always being compared to itself so is unecessary + set diff_opts --color=always --no-prefix + + if test $index_status != ' ' + _fzf_report_diff_type Staged + git diff --staged $diff_opts -- $path + end + + if test $working_tree_status != ' ' + _fzf_report_diff_type Unstaged + git diff $diff_opts -- $path + end + end +end diff --git a/fish/.config/fish/functions/_fzf_preview_file.fish b/fish/.config/fish/functions/_fzf_preview_file.fish @@ -0,0 +1,43 @@ +# helper function for _fzf_search_directory and _fzf_search_git_status +function _fzf_preview_file --description "Print a preview for the given file based on its file type." + # because there's no way to guarantee that _fzf_search_directory passes the path to _fzf_preview_file + # as one argument, we collect all the arguments into one single variable and treat that as the path + set file_path $argv + + if test -L "$file_path" # symlink + # notify user and recurse on the target of the symlink, which can be any of these file types + set -l target_path (realpath "$file_path") + + set_color yellow + echo "'$file_path' is a symlink to '$target_path'." + set_color normal + + _fzf_preview_file "$target_path" + else if test -f "$file_path" # regular file + if set --query fzf_preview_file_cmd + # need to escape quotes to make sure eval receives file_path as a single arg + eval "$fzf_preview_file_cmd '$file_path'" + else + bat --style=numbers --color=always "$file_path" + end + else if test -d "$file_path" # directory + if set --query fzf_preview_dir_cmd + # see above + eval "$fzf_preview_dir_cmd '$file_path'" + else + # -A list hidden files as well, except for . and .. + # -F helps classify files by appending symbols after the file name + command ls -A -F "$file_path" + end + else if test -c "$file_path" + _fzf_report_file_type "$file_path" "character device file" + else if test -b "$file_path" + _fzf_report_file_type "$file_path" "block device file" + else if test -S "$file_path" + _fzf_report_file_type "$file_path" socket + else if test -p "$file_path" + _fzf_report_file_type "$file_path" "named pipe" + else + echo "$file_path doesn't exist." >&2 + end +end diff --git a/fish/.config/fish/functions/_fzf_report_diff_type.fish b/fish/.config/fish/functions/_fzf_report_diff_type.fish @@ -0,0 +1,16 @@ +# helper for _fzf_preview_changed_file +# prints out something like +# +--------+ +# | Staged | +# +--------+ +function _fzf_report_diff_type --argument-names diff_type --description "Print a distinct colored header meant to preface a git patch." + # number of "-" to draw is the length of the string to box + 2 for padding + set repeat_count (math 2 + (string length $diff_type)) + set horizontal_border +(string repeat --count $repeat_count -)+ + + set_color yellow + echo $horizontal_border + echo "| $diff_type |" + echo $horizontal_border + set_color normal +end diff --git a/fish/.config/fish/functions/_fzf_report_file_type.fish b/fish/.config/fish/functions/_fzf_report_file_type.fish @@ -0,0 +1,6 @@ +# helper function for _fzf_preview_file +function _fzf_report_file_type --argument-names file_path file_type --description "Explain the file type for a file." + set_color red + echo "Cannot preview '$file_path': it is a $file_type." + set_color normal +end diff --git a/fish/.config/fish/functions/_fzf_search_directory.fish b/fish/.config/fish/functions/_fzf_search_directory.fish @@ -0,0 +1,44 @@ +function _fzf_search_directory --description "Search the current directory. Replace the current token with the selected file paths." + # --string-cwd-prefix prevents fd >= 8.3.0 from prepending ./ to relative paths + set fd_opts --color=always --strip-cwd-prefix $fzf_fd_opts + + set fzf_arguments --multi --ansi $fzf_dir_opts + set token (commandline --current-token) + # expand any variables or leading tilde (~) in the token + set expanded_token (eval echo -- $token) + # unescape token because it's already quoted so backslashes will mess up the path + set unescaped_exp_token (string unescape -- $expanded_token) + + # If the current token is a directory and has a trailing slash, + # then use it as fd's base directory. + if string match --quiet -- "*/" $unescaped_exp_token && test -d "$unescaped_exp_token" + set --append fd_opts --base-directory=$unescaped_exp_token + # use the directory name as fzf's prompt to indicate the search is limited to that directory + set --prepend fzf_arguments --prompt="$unescaped_exp_token" --preview="_fzf_preview_file $expanded_token{}" + set file_paths_selected $unescaped_exp_token(fd $fd_opts 2>/dev/null | _fzf_wrapper $fzf_arguments) + else + set --prepend fzf_arguments --query="$unescaped_exp_token" --preview='_fzf_preview_file {}' + set file_paths_selected (fd $fd_opts 2>/dev/null | _fzf_wrapper $fzf_arguments) + end + + + if test $status -eq 0 + # Fish will cd implicitly if a directory name ending in a slash is provided. + # To help the user leverage this feature, we automatically append / to the selected path if + # - only one path was selected, + # - the user was in the middle of inputting the first token, + # - the path is a directory + # Then, the user only needs to hit Enter once more to cd into that directory. + if test (count $file_paths_selected) = 1 + set commandline_tokens (commandline --tokenize) + if test "$commandline_tokens" = "$token" -a -d "$file_paths_selected" \ + -a (fd --version | string replace --regex --all '[^\d]' '') -lt 840 + set file_paths_selected $file_paths_selected/ + end + end + + commandline --current-token --replace -- (string escape -- $file_paths_selected | string join ' ') + end + + commandline --function repaint +end diff --git a/fish/.config/fish/functions/_fzf_search_git_log.fish b/fish/.config/fish/functions/_fzf_search_git_log.fish @@ -0,0 +1,28 @@ +function _fzf_search_git_log --description "Search the output of git log and preview commits. Replace the current token with the selected commit hash." + if not git rev-parse --git-dir >/dev/null 2>&1 + echo '_fzf_search_git_log: Not in a git repository.' >&2 + else + # see documentation for git format placeholders at https://git-scm.com/docs/git-log#Documentation/git-log.txt-emnem + # %h gives you the abbreviated commit hash, which is useful for saving screen space, but we will have to expand it later below + set log_fmt_str '%C(bold blue)%h%C(reset) - %C(cyan)%ad%C(reset) %C(yellow)%d%C(reset) %C(normal)%s%C(reset) %C(dim normal)[%an]%C(reset)' + set selected_log_lines ( + git log --color=always --format=format:$log_fmt_str --date=short | \ + _fzf_wrapper --ansi \ + --multi \ + --tiebreak=index \ + --preview='git show --color=always --stat --patch {1}' \ + --query=(commandline --current-token) \ + $fzf_git_log_opts + ) + if test $status -eq 0 + for line in $selected_log_lines + set abbreviated_commit_hash (string split --field 1 " " $line) + set full_commit_hash (git rev-parse $abbreviated_commit_hash) + set --append commit_hashes $full_commit_hash + end + commandline --current-token --replace (string join ' ' $commit_hashes) + end + end + + commandline --function repaint +end diff --git a/fish/.config/fish/functions/_fzf_search_git_status.fish b/fish/.config/fish/functions/_fzf_search_git_status.fish @@ -0,0 +1,34 @@ +function _fzf_search_git_status --description "Search the output of git status. Replace the current token with the selected file paths." + if not git rev-parse --git-dir >/dev/null 2>&1 + echo '_fzf_search_git_status: Not in a git repository.' >&2 + else + set selected_paths ( + # Pass configuration color.status=always to force status to use colors even though output is sent to a pipe + git -c color.status=always status --short | + _fzf_wrapper --ansi \ + --multi \ + --query=(commandline --current-token) \ + --preview='_fzf_preview_changed_file {}' \ + $fzf_git_status_opts + ) + if test $status -eq 0 + # git status --short automatically escapes the paths of most files for us so not going to bother trying to handle + # the few edges cases of weird file names that should be extremely rare (e.g. "this;needs;escaping") + set cleaned_paths + + for path in $selected_paths + if test (string sub --length 1 $path) = R + # path has been renamed and looks like "R LICENSE -> LICENSE.md" + # extract the path to use from after the arrow + set --append cleaned_paths (string split -- "-> " $path)[-1] + else + set --append cleaned_paths (string sub --start=4 $path) + end + end + + commandline --current-token --replace -- (string join ' ' $cleaned_paths) + end + end + + commandline --function repaint +end diff --git a/fish/.config/fish/functions/_fzf_search_history.fish b/fish/.config/fish/functions/_fzf_search_history.fish @@ -0,0 +1,30 @@ +function _fzf_search_history --description "Search command history. Replace the command line with the selected command." + # history merge incorporates history changes from other fish sessions + # it errors out if called in private mode + if test -z "$fish_private_mode" + builtin history merge + end + + # Delinate commands throughout pipeline using null rather than newlines because commands can be multi-line + set commands_selected ( + # Reference https://devhints.io/strftime to understand strftime format symbols + builtin history --null --show-time="%m-%d %H:%M:%S │ " | + _fzf_wrapper --read0 \ + --print0 \ + --multi \ + --tiebreak=index \ + --query=(commandline) \ + --preview="echo -- {4..} | fish_indent --ansi" \ + --preview-window="bottom:3:wrap" \ + $fzf_history_opts | + string split0 | + # remove timestamps from commands selected + string replace --regex '^\d\d-\d\d \d\d:\d\d:\d\d │ ' '' + ) + + if test $status -eq 0 + commandline --replace -- $commands_selected + end + + commandline --function repaint +end diff --git a/fish/.config/fish/functions/_fzf_search_processes.fish b/fish/.config/fish/functions/_fzf_search_processes.fish @@ -0,0 +1,28 @@ +function _fzf_search_processes --description "Search all running processes. Replace the current token with the pid of the selected process." + # use all caps to be consistent with ps default format + # snake_case because ps doesn't seem to allow spaces in the field names + set ps_preview_fmt (string join ',' 'pid' 'ppid=PARENT' 'user' '%cpu' 'rss=RSS_IN_KB' 'start=START_TIME' 'command') + set processes_selected ( + ps -A -opid,command | \ + _fzf_wrapper --multi \ + --query (commandline --current-token) \ + --ansi \ + # first line outputted by ps is a header, so we need to mark it as so + --header-lines=1 \ + # ps uses exit code 1 if the process was not found, in which case show an message explaining so + --preview="ps -o '$ps_preview_fmt' -p {1} || echo 'Cannot preview {1} because it exited.'" \ + --preview-window="bottom:4:wrap" \ + $fzf_processes_opts + ) + + if test $status -eq 0 + for process in $processes_selected + set --append pids_selected (string split --no-empty --field=1 -- " " $process) + end + + # string join to replace the newlines outputted by string split with spaces + commandline --current-token --replace -- (string join ' ' $pids_selected) + end + + commandline --function repaint +end diff --git a/fish/.config/fish/functions/_fzf_search_variables.fish b/fish/.config/fish/functions/_fzf_search_variables.fish @@ -0,0 +1,46 @@ +# This function expects the following two arguments: +# argument 1 = output of (set --show | psub), i.e. a file with the scope info and values of all variables +# argument 2 = output of (set --names | psub), i.e. a file with all variable names +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." + if test -z "$set_names_output" + printf '%s\n' '_fzf_search_variables requires 2 arguments.' >&2 + + commandline --function repaint + return 22 # 22 means invalid argument in POSIX + end + + # Exclude the history variable from being piped into fzf because + # 1. it's not included in $set_names_output + # 2. it tends to be a very large value => increases computation time + # 3._fzf_search_history is a much better way to examine history anyway + set all_variable_names (string match --invert history <$set_names_output) + + set current_token (commandline --current-token) + # Use the current token to pre-populate fzf's query. If the current token begins + # with a $, remove it from the query so that it will better match the variable names + set cleaned_curr_token (string replace -- '$' '' $current_token) + + set variable_names_selected ( + printf '%s\n' $all_variable_names | + _fzf_wrapper --preview "_fzf_extract_var_info {} $set_show_output" \ + --preview-window="wrap" \ + --multi \ + --query=$cleaned_curr_token \ + $fzf_shell_vars_opts + ) + + if test $status -eq 0 + # If the current token begins with a $, do not overwrite the $ when + # replacing the current token with the selected variable. + # Uses brace expansion to prepend $ to each variable name. + commandline --current-token --replace ( + if string match --quiet -- '$*' $current_token + string join " " \${$variable_names_selected} + else + string join " " $variable_names_selected + end + ) + end + + commandline --function repaint +end diff --git a/fish/.config/fish/functions/_fzf_wrapper.fish b/fish/.config/fish/functions/_fzf_wrapper.fish @@ -0,0 +1,20 @@ +function _fzf_wrapper --description "Prepares some environment variables before executing fzf." + # Make sure fzf uses fish to execute preview commands, some of which + # are autoloaded fish functions so don't exist in other shells. + # Use --local so that it doesn't clobber SHELL outside of this function. + set --local --export SHELL (command --search fish) + + # If FZF_DEFAULT_OPTS is not set, then set some sane defaults. + # See https://github.com/junegunn/fzf#environment-variables + if not set --query FZF_DEFAULT_OPTS + # cycle allows jumping between the first and last results, making scrolling faster + # layout=reverse lists results top to bottom, mimicking the familiar layouts of git log, history, and env + # border shows where the fzf window begins and ends + # height=90% leaves space to see the current command and some scrollback, maintaining context of work + # preview-window=wrap wraps long lines in the preview window, making reading easier + # marker=* makes the multi-select marker more distinguishable from the pointer (since both default to >) + set --export FZF_DEFAULT_OPTS '--cycle --layout=reverse --border --height=90% --preview-window=wrap --marker="*"' + end + + fzf $argv +end diff --git a/fish/.config/fish/functions/fzf_configure_bindings.fish b/fish/.config/fish/functions/fzf_configure_bindings.fish @@ -0,0 +1,46 @@ +# Always installs bindings for insert and default mode for simplicity and b/c it has almost no side-effect +# https://gitter.im/fish-shell/fish-shell?at=60a55915ee77a74d685fa6b1 +function fzf_configure_bindings --description "Installs the default key bindings for fzf.fish with user overrides passed as options." + # no need to install bindings if not in interactive mode or running tests + status is-interactive || test "$CI" = true; or return + + set options_spec h/help 'directory=?' 'git_log=?' 'git_status=?' 'history=?' 'variables=?' 'processes=?' + argparse --max-args=0 --ignore-unknown $options_spec -- $argv 2>/dev/null + if test $status -ne 0 + echo "Invalid option or a positional argument was provided." >&2 + _fzf_configure_bindings_help + return 22 + else if set --query _flag_help + _fzf_configure_bindings_help + return + else + # Initialize with default key sequences and then override or disable them based on flags + # index 1 = directory, 2 = git_log, 3 = git_status, 4 = history, 5 = variables, 6 = processes + set key_sequences \e\cf \e\cl \e\cs \cr \cv \e\cp # \c = control, \e = escape + set --query _flag_directory && set key_sequences[1] "$_flag_directory" + set --query _flag_git_log && set key_sequences[2] "$_flag_git_log" + set --query _flag_git_status && set key_sequences[3] "$_flag_git_status" + set --query _flag_history && set key_sequences[4] "$_flag_history" + set --query _flag_variables && set key_sequences[5] "$_flag_variables" + set --query _flag_processes && set key_sequences[6] "$_flag_processes" + + # If fzf bindings already exists, uninstall it first for a clean slate + if functions --query _fzf_uninstall_bindings + _fzf_uninstall_bindings + end + + for mode in default insert + test -n $key_sequences[1] && bind --mode $mode $key_sequences[1] _fzf_search_directory + test -n $key_sequences[2] && bind --mode $mode $key_sequences[2] _fzf_search_git_log + test -n $key_sequences[3] && bind --mode $mode $key_sequences[3] _fzf_search_git_status + test -n $key_sequences[4] && bind --mode $mode $key_sequences[4] _fzf_search_history + test -n $key_sequences[5] && bind --mode $mode $key_sequences[5] "$_fzf_search_vars_command" + test -n $key_sequences[6] && bind --mode $mode $key_sequences[6] _fzf_search_processes + end + + function _fzf_uninstall_bindings --inherit-variable key_sequences + bind --erase -- $key_sequences + bind --erase --mode insert -- $key_sequences + end + end +end