Skip to content

Instantly share code, notes, and snippets.

@vvvvv
Created March 3, 2024 08:03
Show Gist options
  • Save vvvvv/d94610169add6e603f6922453675ff60 to your computer and use it in GitHub Desktop.
Save vvvvv/d94610169add6e603f6922453675ff60 to your computer and use it in GitHub Desktop.
fzf - cd into any dir from anywhere
#!/usr/bin/env zsh
# Use fzf to cd into any directory in your home directory.
#
# Name this script fzf_super_cd and add it to your fpath.
# Add the following to your .zshrc to bind it to Ctrl+E.
#
# zle -N fzf_super_cd
# bindkey -M emacs '^E' fzf_super_cd
# bindkey -M vicmd '^E' fzf_super_cd
# bindkey -M viins '^E' fzf_super_cd
function _fzf_cd() {
setopt localoptions pipefail no_aliases 2> /dev/null
local general_exclude="-E '**/ocaml/**/*esy*' -E '**/ocaml/**/_{build,opam}' -E 'node_modules/*' -E '**/go/pkg/*'"
local home_dir_exclude="-E '{.Trash,Documents,Library,Movies,Music,Pictures,Public,.cache}/*/**'"
local all_dirs
if [[ "${PWD}" != ~ ]]; then
# add all_dirss from the current dir we're in at the top
# and exclude those dirs from the default fd
all_dirs="$({ fd . --hidden --type d "${general_exclude}"; \
fd . --type d --hidden "${general_exclude}" ${home_dir_exclude} ~/ | rg -v "$(pwd)" } \
| FZF_DEFAULT_OPTS="--height ${FZF_TMUX_HEIGHT:-40%} ${FZF_DEFAULT_OPTS-} -n2..,.. --reverse --bind=ctrl-g:toggle-sort,ctrl-z:ignore ${FZF_CTRL_G_OPTS-} --query=${(qqq)LBUFFER} +m" $(__fzfcmd))"
else
# in home dir just execute the default fd command
all_dirs="$(fd . --type d --hidden "${general_exclude}" ${home_dir_exclude} ~/ \
| FZF_DEFAULT_OPTS="--height ${FZF_TMUX_HEIGHT:-40%} ${FZF_DEFAULT_OPTS-} -n2..,.. --reverse --bind=ctrl-g:toggle-sort,ctrl-z:ignore ${FZF_CTRL_G_OPTS-} --query=${(qqq)LBUFFER} +m" $(__fzfcmd))"
fi
local ret=$?
if [ -z "${all_dirs}" ]; then
num=$selected[1]
zle redisplay
return 0
fi
zle push-line
BUFFER="cd -- ${(q)all_dirs}"
zle accept-line
local ret=$?
unset all_dirs
zle reset-prompt
return $ret
}
_fzf_cd "${@}"
#vim fd=zsh
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment