Skip to content

Instantly share code, notes, and snippets.

@chew-z
Created April 7, 2017 11:07
Show Gist options
  • Save chew-z/ec600a22ac510cf9e2ca4480d5c4c094 to your computer and use it in GitHub Desktop.
Save chew-z/ec600a22ac510cf9e2ca4480d5c4c094 to your computer and use it in GitHub Desktop.
Ctrl-Vim fuzzy find last edited files
#!/usr/bin/env zsh
#
# Fuzzy find recently edited with [m(vim)|edit|subl] files
# gource in .zshrc and press (Ctrl-V) to call from shell.
# (Enter) opens in vim or (Ctrl-M) in MacVim. Previev (?)
fzf-edit-file-in-vim-or-mvim() {
local out key file helpline
local Vim_binary='/Applications/MacVim.app/Contents/MacOS/Vim'
helpline="<Ctrl-M> opens in MacVim | <?> toggles preview"
IFS=$'\n' out=($(\
# search history file with ripgrep
rg -N --color never ':0;m?vim\s|:0;edit\s|:0;subl\s' ~/.zsh_history |
# grab what's after [mvim/vim/edit/subl]
awk '{ print $3 }' |
# normalize ~ to full path
sed 's@~@'"$HOME"'@' |
# remove dupicates (NODUPES but still ... )
perl -ne 'print if !$seen{$_}++' |
# fzf - now fuzzy search - preview only if proper file
fzf --header="$helpline" --tac --exit-0 --expect=ctrl-v,ctrl-m \
--preview '[ -f {} ] && head -n 50 {}' \
--preview-window down:25% \
--bind='?:toggle-preview'))
key=$(head -1 <<< "$out")
file=$(head -2 <<< "$out" | tail -1)
if [ -f "$file" ]; then
if [ "$key" = ctrl-v ]; then # open in VIM
$Vim_binary --servername VIM --remote-tab-silent "$file"
# save [simplified] in history so it is on top of stack for next search
print -S "vim $file"
elif [ "$key" = ctrl-m ]; then # open in MacVim (btw Ctrl-M is accept line)
/usr/local/bin/mvim --servername VIM --remote-tab-silent "$file"
# save [simplified] in history so it is on top of stack for next search
print -S "mvim $file"
else
/usr/local/bin/mvim --servername VIM --remote-tab-silent "$file"
# save [simplified] in history so it is on top of stack for next search
print -S "mvim $file"
fi
fi
zle reset-prompt
zle accept-line
}
zle -N fzf-edit-file-in-vim-or-mvim
bindkey '^V' fzf-edit-file-in-vim-or-mvim
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment