Skip to content

Instantly share code, notes, and snippets.

@nelsonuhan
Created September 9, 2018 16:48
Show Gist options
  • Save nelsonuhan/85431a0dcff1d3f68e4662adda21d940 to your computer and use it in GitHub Desktop.
Save nelsonuhan/85431a0dcff1d3f68e4662adda21d940 to your computer and use it in GitHub Desktop.
Use ranger as file/directory picker in vim (GUI MacVim in particular)
" Rudimentary vimscript to use ranger as a file/directory picker
" Nelson Uhan
" 2018.9.9
"
" Uses Vim 8's terminal to open ranger in a new window
" Tested on MacVim 8.1.120, GUI and terminal versions
"
" Put this in your .vimrc (or equivalent)
" :RangerFiles opens ranger as a file picker in a new window
" :RangerDirs opens ranger as a directory picker in a new window
" Map these commands as you like
" ranger file picker
function! RangerFilePicker()
" Temp file for Ranger selections
let tempfile = tempname()
" Dictionary function
let ranger = { 'tempfile' : tempfile }
function! ranger.OnExit(...)
" Is temp file readable?
if !filereadable(self.tempfile)
return
endif
" Read ranger selections, delete temp file
let selections = readfile(self.tempfile)
call delete(self.tempfile)
" Are there any selections?
if empty(selections)
return
endif
" Close the terminal window, edit the first item
close
exec 'edit ' . fnameescape(selections[0])
" Add any remaining items to the arg/buffer list
for sel in selections[1:]
exec 'argadd '. fnameescape(sel)
endfor
endfunction
" Open ranger in a new terminal window
let pwd = getcwd()
let cmd = 'ranger --choosefiles=' . fnameescape(tempfile) . ' ' . fnameescape(pwd)
let buf = term_start(cmd, {'term_finish' : 'close', 'exit_cb' : ranger.OnExit})
endfunction
command! RangerFiles call RangerFilePicker()
" ranger directory picker
function! RangerDirPicker()
" Temp file for Ranger selections
let tempfile = tempname()
" Dictionary function
let ranger = { 'tempfile' : tempfile }
function! ranger.OnExit(...)
" Is temp file readable?
if !filereadable(self.tempfile)
return
endif
" Read ranger selections, delete temp file
let selections = readfile(self.tempfile)
call delete(self.tempfile)
" Are there any selections?
if empty(selections)
return
endif
" Close the terminal window, change current directory
close
exec 'cd ' . fnameescape(selections[0])
endfunction
" Open ranger in a new terminal window
let pwd = getcwd()
let cmd = 'ranger --show-only-dirs --choosedir=' . fnameescape(tempfile) . ' ' . fnameescape(pwd)
let buf = term_start(cmd, {'term_finish' : 'close', 'exit_cb' : ranger.OnExit})
endfunction
command! RangerDirs call RangerDirPicker()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment