I would like to have a file extension aware :FZF command, so that when I choose a file with enter from the fzf prompt, and that file has an extension that matches a list (say (pdf|mp3|jpg)), it opens the file with some external bash command (say open, I'm on mac), and otherwhise just opens it in vim buffer ar normal.

I have the following in my .vimrc

let g:fzf_action = {
  \ 'ctrl-t': 'tab split',
  \ 'ctrl-x': '!open',
  \ 'ctrl-v': 'vsplit', }

which lets me open files with an external program with ctrl-x from the prompts, but my brain can't handle this very well and I often press enter instead of ctrl-x. One single context aware command would be much better.

  • This sounds more like a enhancement request for fzf than a question about Vim.
    – Ralf
    Jan 1, 2019 at 8:57
  • @Ralf Maybe. I thought with a little bit of vimscript it aught not to be too difficult. That's why i posted here.
    – Andreas
    Jan 1, 2019 at 11:48
  • I saw a post somewhere recently about using filetype plugins to trigger specific commands (e.g. !open %, then bdelete, then b #) for filetypes like the ones you suggest. I’ll see if I can dig it up
    – D. Ben Knoble
    Jan 1, 2019 at 17:23
  • @Knoble That does indeed solve the problem. Seems like like a bit of a detour though to load a video as vim buffer before running it with an external program. This method also effectively changes the alternative # buffer (by opening the non textfile as a buffer, making that the # buffer, and then deleting it) which can be annoying.
    – Andreas
    Jan 1, 2019 at 18:02

1 Answer 1


Based on what I read at Vimways, I would do something like this:

First, we need filetype-detection working, so for every filetype you need, in ~/.vim/ftdetect/<filetype>.vim, put

autocommand BufRead,BufNewFile *.<ext>[,*.<ext>] set filetype=<filetype>

(The example in the article uses video as a filetype, with a plethora of extensions matching.)

Next, we must execute the appropriate actions, so in ~/.vim/after/ftplugin/<filetype>.vim you'll want to

silent execute "!<external commands to view the file>" | buffer# | bdelete# | redraw! | syntax on

If, like me, you prefer to reorganize the code a bit:

function! s:command() abort
  " execute the external viewing command

function! s:nextfile() abort
  buffer #
  bdelete #
  " this may or may not be necessary...
  " it might also be 'syntax enable' or even just 'edit'
  syntax on

silent call s:command()
silent call s:nextfile()
  • One could also use silent!, though in this case I may want error messages
    – D. Ben Knoble
    Jan 8, 2019 at 15:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.