0

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.

DJMcMayhem
  • 17,581
  • 5
  • 53
  • 85
Andreas
  • 357
  • 2
  • 10
  • This sounds more like a enhancement request for fzf than a question about Vim. – Ralf Jan 01 '19 at 08: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 01 '19 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 01 '19 at 17:23
  • https://vimways.org/2018/opening-non-vim-file-formats/ – D. Ben Knoble Jan 01 '19 at 17:25
  • @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 01 '19 at 18:02
  • @D.BenKnoble If you make that an answer ill accept it. – Andreas Jan 02 '19 at 20:25

1 Answers1

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
endfunction

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

silent call s:command()
silent call s:nextfile()
D. Ben Knoble
  • 26,070
  • 3
  • 29
  • 65