如何删除 Vim 中的当前文件?

如何从磁盘中删除 vim 中当前打开的文件?最好也关闭缓冲区。

我看到你 可以使用 NERDTree,但我不使用这个插件。

70527 次浏览

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 %

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.

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>.

You can do it with two steps:

  1. save as a new file

    :w newfilename

  2. delete the old file

    ! rm oldfilename

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.

This may be an unpopular opinion but your file tree explorer (Netrw/NerdTree) is going to be the simplest and safest way to delete a file. Even if OP is not using NerdTree, the in-built plugin Netrw will work just as well.