How can I delete the current file in vim?

How can I delete from the disk the current open file from within vim? Would be nice to also close the buffer.

I see you can use NERDTree for that, but I don't use this plugin.


Using an external tool such as rm(1) is fine, but Vim also has its own delete() function for deleting files. This has the advantage of being portable.

:call delete(expand('%'))

An alternative way of expressing this is :call delete(@%), which uses the % (current file) register (tip by @accolade).

To completely purge the current buffer, both the file representation on disk and the Vim buffer, append :bdelete:

:call delete(expand('%')) | bdelete!

You'll probably want to map this according to your preferences.


Take a look at Delete files with a Vim command. The Comments section should have what you're looking for:

Basically, Rm will delete the current file; RM will delete the current file and quit the buffer (without saving) in one go.

Alternatively, you could just issue a shell command to remove the current file:

:!rm %

Sometimes a plugin can be an attractive solution even for a simple problem. In this case we're lucky as there is eunuch.vim by the almighty Tim Pope.

In its own words eunuch.vim provides

Vim sugar for the UNIX shell commands that need it the most. Delete or rename a buffer and the underlying file at the same time. Load a find or a locate into the quickfix list. And so on.

Perfect. It has what we need, plus some additional tools if we're on a UNIX system.

The command you are looking for is

:Remove!

Again, remap it if you need it a lot, e.g. :nnoremap <Leader>rm :Remove!<CR>.


I like being able to delete files from within vim, but I am also paranoid about accidentally deleting important work that, for one reason or another, is not yet under version control. I find it useful to combine the previous information from @glts and @accolade with this answer on how to use the confirm command to prompt before quitting vim.

Putting these together, I added a function to my ~/.vimrc, which prompts before deleting the file and closing the buffer, and mapped it to a key combination:

nnoremap <Leader>d. :call DeleteFileAndCloseBuffer()

fun! DeleteFileAndCloseBuffer()
  let choice = confirm("Delete file and close buffer?", "&Do it!\n&Nonono", 1)
  if choice == 1 | call delete(expand('%:p')) | q! | endif
endfun

If you are one keystroke less paranoid than I am, you can append <CR> to the first line

nnoremap <Leader>d. :call DeleteFileAndCloseBuffer()<CR>

and only have to press return once.