History Report a problem
Article Edit this page Discussion

Delete files with a Vim command

From Vim Tips Wiki

Jump to: navigation, search
 

Tip 913Previous TipNext Tip

Created: April 15, 2005 Complexity: basic Author: hari_vim Minimum version: 6.0 Karma: 1/3 Imported from: Tip#913


You can of course create a command/map to execute the external "rm" or "del" command depending on the OS and environment, but Vim has a delete() function which works very well, and I like to do it this way because it works on all environments without much effort. Put the following in your vimrc (all on one line) and you can use the "Remove" command with the normal Vim command-line arguments (such as "%" to remove the current file). It also has filename completion.

command! -complete=file -nargs=1 Remove :echo 'Remove: '.'<f-args>'.' '.(delete(<f-args>) == 0 ? 'SUCCEEDED' : 'FAILED')

Once you execute the command, watch out for the "SUCCEEDED" status for confirmation. This only removes the file on the filesystem, so if you want, you can explicitly delete/wipeout the vim buffer too.

[edit] Comments

To expand slightly, I use the following to delete the current buffer -- this is smart enough to not delete help buffers:

function! DeleteFile(...)
  if(exists('a:1'))
    let theFile=a:1
  elseif ( &ft == 'help' )
    echohl Error
    echo "Cannot delete a help buffer!"
    echohl None
    return -1
  else
    let theFile=expand('%:p')
  endif
  let delStatus=delete(theFile)
  if(delStatus == 0)
    echo "Deleted " . theFile
  else
    echohl WarningMsg
    echo "Failed to delete " . theFile
    echohl None
  endif
  return delStatus
endfunction
"delete the current file
com! Rm call DeleteFile()
"delete the file and quit the buffer (quits vim if this was the last file)
com! RM call DeleteFile() <bar> q!

Basically, Rm will delete the current file; RM will delete the current file and quit the buffer (without saving) in one go. Given that DeleteFile() takes a parameter and uses that instead of the current buffer should allow a version of Rm/RM to take a parameter (or not) quite easily; left to the reader as an exercise.


I don't understand why you would use all those commands and functions.

Why not :echo delete(filename)? Or, if you want to delete file and wipeout buffer, which I guess happens very rarely, you may write :echo delete(@%), and if successfull -- :bw!.


Rate this article:

Share this article:

Hubs Highlights International Sites Wikia messages
Entertainment
Gaming
Cartoons & Comics
Science Fiction
Hobbies
Sports
See all...
Grand Theft Auto
Terminator Wiki
Legend of Zelda Wiki
Flash Gordon
Everquest II Wiki
Yo-Yo Wiki
German
Spanish
Chinese
Japanese
More...
Wikia is hiring for several open positions


Vote for featured Wikia!

Send this article to a friend
"Delete files with a Vim command"
 
 
Hi!

I thought you'd like this page from Wikia!

http://vim.wikia.com

Come check it out!
Send confirmation